auth_framework/auth_operations.rs
1//! Grouped operation facades over [`AuthFramework`].
2//!
3//! Each `*Operations` struct is a lightweight view (holds only a lifetime-bound
4//! reference to the framework) that exposes a focused subset of the full API.
5//! They are created by the corresponding accessor on `AuthFramework` (e.g. [`users()`]).
6//!
7//! # Request structs
8//!
9//! Several operations accept structured request types instead of long
10//! parameter lists. These types carry required parameters via a
11//! constructor and optional parameters via builder methods:
12//!
13//! - [`SessionCreateRequest`] — session creation with optional IP / user-agent.
14//! - [`AuditLogQuery`] — filtered audit log queries.
15//! - [`UserListQuery`] — user listing with pagination and filtering.
16//! - [`PermissionContext`] — context data for dynamic permission evaluation.
17//! - [`DelegationRequest`] — permission delegation with required fields.
18//! - [`ExecutionMode`] — `DryRun` vs `Execute` for maintenance operations.
19//! - [`UserStatus`] — `Active` vs `Inactive` for user account state.
20//! - [`SessionFilter`] — `ActiveOnly` vs `IncludeInactive` for session listing.
21//!
22//! [`users()`]: crate::auth::AuthFramework::users
23
24use crate::audit::SecurityAuditStats;
25use crate::auth::{AuthFramework, AuthStats, UserInfo};
26use crate::errors::{AuthError, Result};
27use crate::maintenance::{BackupReport, ResetReport, RestoreReport};
28use crate::methods::MfaChallenge;
29use crate::permissions::Role;
30use crate::storage::SessionData;
31use crate::tokens::AuthToken;
32use std::sync::Arc;
33use std::time::Duration;
34
35/// Controls whether a maintenance operation (backup, restore, reset) actually
36/// modifies state or merely previews what *would* happen.
37///
38/// Replaces bare `bool` parameters for better call-site readability.
39///
40/// # Example
41///
42/// ```rust,ignore
43/// use auth_framework::auth_operations::ExecutionMode;
44///
45/// // Preview:
46/// let preview = auth.maintenance().backup("backup.json", ExecutionMode::DryRun).await?;
47/// // For real:
48/// let report = auth.maintenance().backup("backup.json", ExecutionMode::Execute).await?;
49/// ```
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum ExecutionMode {
52 /// Report what the operation would do without making changes.
53 DryRun,
54 /// Actually perform the operation.
55 Execute,
56}
57
58impl ExecutionMode {
59 /// Returns `true` when this is a dry-run (preview) execution.
60 pub fn is_dry_run(self) -> bool {
61 matches!(self, Self::DryRun)
62 }
63}
64
65impl From<ExecutionMode> for bool {
66 /// Converts to the legacy `dry_run: bool` parameter (`DryRun → true`).
67 fn from(mode: ExecutionMode) -> bool {
68 mode.is_dry_run()
69 }
70}
71
72/// Whether a user account should be active (able to log in) or inactive
73/// (locked out).
74///
75/// Replaces bare `bool` parameters for better call-site readability.
76///
77/// # Example
78///
79/// ```rust,ignore
80/// use auth_framework::auth_operations::UserStatus;
81///
82/// // Deactivate a user:
83/// auth.users().set_status(&user_id, UserStatus::Inactive).await?;
84/// // Re-activate:
85/// auth.users().set_status(&user_id, UserStatus::Active).await?;
86/// ```
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
88pub enum UserStatus {
89 /// Account is active and can authenticate.
90 Active,
91 /// Account is disabled and all login attempts will be rejected.
92 Inactive,
93}
94
95impl UserStatus {
96 /// Returns `true` when the user should be active.
97 pub fn is_active(self) -> bool {
98 matches!(self, Self::Active)
99 }
100}
101
102impl From<UserStatus> for bool {
103 /// Converts to the legacy `active: bool` parameter (`Active → true`).
104 fn from(status: UserStatus) -> bool {
105 status.is_active()
106 }
107}
108
109impl From<bool> for UserStatus {
110 fn from(active: bool) -> Self {
111 if active { Self::Active } else { Self::Inactive }
112 }
113}
114
115/// Filter for session listing queries.
116///
117/// Replaces `include_inactive: bool` for self-documenting call sites.
118///
119/// # Example
120///
121/// ```rust,ignore
122/// use auth_framework::auth_operations::SessionFilter;
123///
124/// let active = mgr.get_user_sessions(user_id, SessionFilter::ActiveOnly).await?;
125/// let all = mgr.get_user_sessions(user_id, SessionFilter::IncludeInactive).await?;
126/// ```
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128pub enum SessionFilter {
129 /// Return only active sessions.
130 ActiveOnly,
131 /// Return all sessions including expired/revoked ones.
132 IncludeInactive,
133}
134
135impl SessionFilter {
136 /// Returns `true` when inactive sessions should be included.
137 pub fn include_inactive(self) -> bool {
138 matches!(self, Self::IncludeInactive)
139 }
140}
141
142impl From<SessionFilter> for bool {
143 /// Converts to the legacy `include_inactive: bool` parameter.
144 fn from(filter: SessionFilter) -> bool {
145 filter.include_inactive()
146 }
147}
148
149// ──────────────────────────────────────────────────────────────────────────────
150// Request / query structs
151// ──────────────────────────────────────────────────────────────────────────────
152
153/// Filtering criteria for [`AuditOperations::query_permission_logs`].
154///
155/// All fields are optional — an empty query returns unfiltered results.
156///
157/// # Example
158///
159/// ```rust,ignore
160/// let query = AuditLogQuery::new()
161/// .user("user_123")
162/// .action("read")
163/// .limit(50);
164/// ```
165#[derive(Debug, Clone, Default)]
166pub struct AuditLogQuery {
167 user_id: Option<String>,
168 action: Option<String>,
169 resource: Option<String>,
170 limit: Option<usize>,
171}
172
173impl AuditLogQuery {
174 /// Create an empty query (matches everything).
175 pub fn new() -> Self {
176 Self::default()
177 }
178
179 /// Filter by user ID.
180 pub fn user(mut self, user_id: impl Into<String>) -> Self {
181 self.user_id = Some(user_id.into());
182 self
183 }
184
185 /// Filter by action (e.g. `"read"`, `"write"`).
186 pub fn action(mut self, action: impl Into<String>) -> Self {
187 self.action = Some(action.into());
188 self
189 }
190
191 /// Filter by resource path.
192 pub fn resource(mut self, resource: impl Into<String>) -> Self {
193 self.resource = Some(resource.into());
194 self
195 }
196
197 /// Limit the number of returned entries.
198 pub fn limit(mut self, limit: usize) -> Self {
199 self.limit = Some(limit);
200 self
201 }
202
203 /// Returns the user-ID filter, if set.
204 pub fn get_user_id(&self) -> Option<&str> {
205 self.user_id.as_deref()
206 }
207
208 /// Returns the action filter, if set.
209 pub fn get_action(&self) -> Option<&str> {
210 self.action.as_deref()
211 }
212
213 /// Returns the resource filter, if set.
214 pub fn get_resource(&self) -> Option<&str> {
215 self.resource.as_deref()
216 }
217
218 /// Returns the maximum number of entries to return, if set.
219 pub fn get_limit(&self) -> Option<usize> {
220 self.limit
221 }
222}
223
224/// Query type for listing users with pagination and filtering.
225///
226/// Provides a fluent API for configuring user listing parameters.
227///
228/// # Example
229///
230/// ```rust
231/// # use auth_framework::auth_operations::UserListQuery;
232/// let query = UserListQuery::new()
233/// .limit(50)
234/// .active_only();
235/// ```
236#[derive(Debug, Clone, Default)]
237pub struct UserListQuery {
238 limit: Option<usize>,
239 offset: Option<usize>,
240 active_only: bool,
241}
242
243impl UserListQuery {
244 /// Create an empty query (returns all users).
245 pub fn new() -> Self {
246 Self::default()
247 }
248
249 /// Limit the number of users returned.
250 pub fn limit(mut self, limit: usize) -> Self {
251 self.limit = Some(limit);
252 self
253 }
254
255 /// Skip the first N users (for pagination).
256 pub fn offset(mut self, offset: usize) -> Self {
257 self.offset = Some(offset);
258 self
259 }
260
261 /// Only return active users (default: false).
262 pub fn active_only(mut self) -> Self {
263 self.active_only = true;
264 self
265 }
266
267 /// Conditionally restrict the query to active users.
268 pub fn active_only_if(mut self, active_only: bool) -> Self {
269 self.active_only = active_only;
270 self
271 }
272
273 /// Conditionally apply a limit when one is provided.
274 pub fn limit_if_some(mut self, limit: Option<usize>) -> Self {
275 if let Some(limit) = limit {
276 self.limit = Some(limit);
277 }
278 self
279 }
280
281 /// Returns the maximum number of users to return, if set.
282 pub fn get_limit(&self) -> Option<usize> {
283 self.limit
284 }
285
286 /// Returns the pagination offset, if set.
287 pub fn get_offset(&self) -> Option<usize> {
288 self.offset
289 }
290
291 /// Returns `true` when only active users should be listed.
292 pub fn get_active_only(&self) -> bool {
293 self.active_only
294 }
295}
296
297/// Context data for dynamic permission evaluation (ABAC).
298///
299/// Provides a structured way to pass environmental and contextual information
300/// for attribute-based access control decisions.
301///
302/// # Example
303///
304/// ```rust
305/// # use auth_framework::auth_operations::PermissionContext;
306/// let context = PermissionContext::new()
307/// .with_attribute("time_of_day", "business_hours")
308/// .with_attribute("ip_location", "office")
309/// .with_attribute("device_type", "trusted");
310/// ```
311#[derive(Debug, Clone, Default)]
312pub struct PermissionContext {
313 attributes: std::collections::HashMap<String, String>,
314}
315
316impl PermissionContext {
317 /// Create an empty context.
318 pub fn new() -> Self {
319 Self::default()
320 }
321
322 /// Add a context attribute.
323 pub fn with_attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
324 self.attributes.insert(key.into(), value.into());
325 self
326 }
327
328 /// Add multiple attributes from an iterator.
329 pub fn with_attributes<I, K, V>(mut self, attributes: I) -> Self
330 where
331 I: IntoIterator<Item = (K, V)>,
332 K: Into<String>,
333 V: Into<String>,
334 {
335 for (key, value) in attributes {
336 self.attributes.insert(key.into(), value.into());
337 }
338 self
339 }
340
341 /// Get the underlying attributes map.
342 pub fn into_attributes(self) -> std::collections::HashMap<String, String> {
343 self.attributes
344 }
345
346 /// Get a reference to the attributes map.
347 pub fn attributes(&self) -> &std::collections::HashMap<String, String> {
348 &self.attributes
349 }
350}
351
352/// Request type for [`AdminOperations::delegate`].
353///
354/// Bundles the four required delegation fields and the optional duration
355/// into a single self-documenting value.
356///
357/// # Example
358///
359/// ```rust,ignore
360/// let req = DelegationRequest::new("admin_1", "user_2", "write", "reports")
361/// .duration(Duration::from_secs(3600));
362/// ```
363#[derive(Debug, Clone)]
364pub struct DelegationRequest {
365 delegator_id: String,
366 delegatee_id: String,
367 action: String,
368 resource: String,
369 duration: Duration,
370}
371
372impl DelegationRequest {
373 /// Create a delegation request with required parameters.
374 ///
375 /// The default duration is 1 hour. Override with [`duration`](Self::duration).
376 pub fn new(
377 delegator_id: impl Into<String>,
378 delegatee_id: impl Into<String>,
379 action: impl Into<String>,
380 resource: impl Into<String>,
381 ) -> Self {
382 Self {
383 delegator_id: delegator_id.into(),
384 delegatee_id: delegatee_id.into(),
385 action: action.into(),
386 resource: resource.into(),
387 duration: Duration::from_secs(3600),
388 }
389 }
390
391 /// Set the delegation duration (replaces the default of 1 hour).
392 pub fn duration(mut self, duration: Duration) -> Self {
393 self.duration = duration;
394 self
395 }
396
397 /// Returns the ID of the user granting permissions.
398 pub fn delegator_id(&self) -> &str {
399 &self.delegator_id
400 }
401
402 /// Returns the ID of the user receiving permissions.
403 pub fn delegatee_id(&self) -> &str {
404 &self.delegatee_id
405 }
406
407 /// Returns the action being delegated (e.g. `"write"`).
408 pub fn action(&self) -> &str {
409 &self.action
410 }
411
412 /// Returns the resource being delegated (e.g. `"reports"`).
413 pub fn resource(&self) -> &str {
414 &self.resource
415 }
416
417 /// Returns how long the delegation is valid.
418 pub fn get_duration(&self) -> Duration {
419 self.duration
420 }
421}
422
423// ──────────────────────────────────────────────────────────────────────────────
424// User operations
425// ──────────────────────────────────────────────────────────────────────────────
426
427/// Focused user-management operations exposed from [`AuthFramework::users`].
428///
429/// # Example
430///
431/// ```rust,no_run
432/// # use auth_framework::prelude::*;
433/// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
434/// // Register
435/// let uid = auth.users().register("alice", "alice@example.com", "P@ssw0rd!").await?;
436///
437/// // Look up
438/// let user = auth.users().get(&uid).await?;
439/// assert_eq!(user.username, "alice");
440///
441/// // Update password
442/// auth.users().update_password_by_id(&uid, "NewP@ss!").await?;
443/// # Ok(())
444/// # }
445/// ```
446pub struct UserOperations<'a> {
447 pub(crate) framework: &'a AuthFramework,
448}
449
450impl UserOperations<'_> {
451 /// Register a new user and return the generated user ID.
452 pub async fn register(&self, username: &str, email: &str, password: &str) -> Result<String> {
453 self.framework
454 .register_user(username, email, password)
455 .await
456 }
457
458 /// List users from the canonical user index.
459 ///
460 /// **Prefer [`list_with_query`](Self::list_with_query)** which uses a
461 /// [`UserListQuery`] builder for better readability at call sites.
462 #[deprecated(
463 since = "0.6.0",
464 note = "use `list_with_query(UserListQuery::new().limit(n).active_only())` instead"
465 )]
466 pub async fn list(
467 &self,
468 limit: Option<usize>,
469 offset: Option<usize>,
470 active_only: bool,
471 ) -> Result<Vec<UserInfo>> {
472 self.framework
473 .list_users_with_query(
474 UserListQuery::new()
475 .offset(offset.unwrap_or(0))
476 .active_only_if(active_only)
477 .limit_if_some(limit),
478 )
479 .await
480 }
481
482 /// List users using a [`UserListQuery`] for better readability.
483 ///
484 /// # Example
485 ///
486 /// ```rust,no_run
487 /// # use auth_framework::prelude::*;
488 /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
489 /// let active = auth.users()
490 /// .list_with_query(UserListQuery::new().limit(50).active_only())
491 /// .await?;
492 /// # Ok(())
493 /// # }
494 /// ```
495 pub async fn list_with_query(&self, query: UserListQuery) -> Result<Vec<UserInfo>> {
496 self.framework.list_users_with_query(query).await
497 }
498
499 /// Fetch a user record by canonical user ID.
500 pub async fn get(&self, user_id: &str) -> Result<UserInfo> {
501 self.framework.get_user_record(user_id).await
502 }
503
504 /// Check whether a username exists.
505 pub async fn exists_by_username(&self, username: &str) -> Result<bool> {
506 self.framework.username_exists(username).await
507 }
508
509 /// Check whether an email exists.
510 pub async fn exists_by_email(&self, email: &str) -> Result<bool> {
511 self.framework.email_exists(email).await
512 }
513
514 /// Fetch a user record by username.
515 pub async fn get_by_username(
516 &self,
517 username: &str,
518 ) -> Result<std::collections::HashMap<String, serde_json::Value>> {
519 self.framework.get_user_by_username(username).await
520 }
521
522 /// Fetch an application-level user profile.
523 pub async fn profile(&self, user_id: &str) -> Result<crate::providers::ProviderProfile> {
524 self.framework.get_user_profile(user_id).await
525 }
526
527 /// Update a user's password.
528 pub async fn update_password(&self, username: &str, new_password: &str) -> Result<()> {
529 self.framework
530 .update_user_password(username, new_password)
531 .await
532 }
533
534 /// Update a user's password by user ID.
535 pub async fn update_password_by_id(&self, user_id: &str, new_password: &str) -> Result<()> {
536 self.framework
537 .update_user_password_by_id(user_id, new_password)
538 .await
539 }
540
541 /// Update the roles assigned to a user.
542 pub async fn update_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
543 self.framework.update_user_roles(user_id, roles).await
544 }
545
546 /// Enable or disable a user.
547 #[deprecated(since = "0.5.0", note = "use `set_status(id, UserStatus)` instead")]
548 pub async fn set_active(&self, user_id: &str, active: bool) -> Result<()> {
549 self.framework.set_user_active(user_id, active).await
550 }
551
552 /// Change whether a user account is active or inactive.
553 ///
554 /// Inactive users cannot authenticate until re-activated.
555 ///
556 /// # Example
557 ///
558 /// ```rust,ignore
559 /// auth.users().set_status(&user_id, UserStatus::Inactive).await?;
560 /// ```
561 pub async fn set_status(&self, user_id: &str, status: UserStatus) -> Result<()> {
562 self.framework
563 .set_user_active(user_id, status.is_active())
564 .await
565 }
566
567 /// Update a user's email address.
568 pub async fn update_email(&self, user_id: &str, email: &str) -> Result<()> {
569 self.framework.update_user_email(user_id, email).await
570 }
571
572 /// Verify a user's password.
573 pub async fn verify_password(&self, user_id: &str, password: &str) -> Result<bool> {
574 self.framework.verify_user_password(user_id, password).await
575 }
576
577 /// Resolve a username from a user ID.
578 pub async fn username(&self, user_id: &str) -> Result<String> {
579 self.framework.get_username_by_id(user_id).await
580 }
581
582 /// Delete a user by username.
583 pub async fn delete(&self, username: &str) -> Result<()> {
584 self.framework.delete_user(username).await
585 }
586
587 /// Delete a user by user ID.
588 pub async fn delete_by_id(&self, user_id: &str) -> Result<()> {
589 self.framework.delete_user_by_id(user_id).await
590 }
591
592 /// Validate a username against the configured format rules.
593 ///
594 /// Returns `Ok(())` when the username is acceptable, or
595 /// `Err(AuthError::Validation { .. })` describing the policy violation.
596 ///
597 /// # Example
598 ///
599 /// ```rust,no_run
600 /// # use auth_framework::prelude::*;
601 /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
602 /// auth.users().check_username("alice")?;
603 /// // Returns Err explaining why the name is invalid:
604 /// assert!(auth.users().check_username("").is_err());
605 /// # Ok(())
606 /// # }
607 /// ```
608 pub fn check_username(&self, username: &str) -> Result<()> {
609 crate::utils::validation::validate_username(username)
610 }
611
612 /// Validate a password against the active security policy.
613 ///
614 /// Returns `Ok(())` when the password meets production strength
615 /// requirements, or `Err(AuthError::Validation { .. })` with feedback.
616 ///
617 /// # Example
618 ///
619 /// ```rust,no_run
620 /// # use auth_framework::prelude::*;
621 /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
622 /// auth.users().check_password_strength("C0mpl3x!Pa$$word")?;
623 /// assert!(auth.users().check_password_strength("weak").is_err());
624 /// # Ok(())
625 /// # }
626 /// ```
627 pub fn check_password_strength(&self, password: &str) -> Result<()> {
628 let strength = crate::utils::password::check_password_strength(password);
629 if crate::utils::password::meets_production_strength(strength.level) {
630 Ok(())
631 } else {
632 Err(AuthError::validation(format!(
633 "Password does not meet strength requirements: {}",
634 strength.feedback.join(", ")
635 )))
636 }
637 }
638
639 /// Validate an email address against RFC 5322 format rules.
640 ///
641 /// Returns `Ok(())` when the email is acceptable, or
642 /// `Err(AuthError::Validation { .. })` describing the issue.
643 ///
644 /// # Example
645 ///
646 /// ```rust,no_run
647 /// # use auth_framework::prelude::*;
648 /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
649 /// auth.users().check_email("alice@example.com")?;
650 /// assert!(auth.users().check_email("not-an-email").is_err());
651 /// # Ok(())
652 /// # }
653 /// ```
654 pub fn check_email(&self, email: &str) -> Result<()> {
655 crate::utils::validation::validate_email(email)
656 }
657}
658
659// ──────────────────────────────────────────────────────────────────────────────
660// Session operations
661// ──────────────────────────────────────────────────────────────────────────────
662
663/// Request type for [`SessionOperations::create`].
664///
665/// Bundles the required session parameters (user ID, lifetime) with optional
666/// context (IP address, user-agent) so callers never need to pass `None`
667/// explicitly.
668///
669/// # Example
670///
671/// ```rust,no_run
672/// # use auth_framework::auth_operations::SessionCreateRequest;
673/// # use std::time::Duration;
674/// // Minimal — no optional fields:
675/// let req = SessionCreateRequest::new("user-123", Duration::from_secs(3600));
676///
677/// // With optional context:
678/// let req = SessionCreateRequest::new("user-123", Duration::from_secs(3600))
679/// .ip_address("10.0.0.1")
680/// .user_agent("Mozilla/5.0");
681/// ```
682#[derive(Debug, Clone)]
683pub struct SessionCreateRequest {
684 user_id: String,
685 expires_in: Duration,
686 ip_address: Option<String>,
687 user_agent: Option<String>,
688}
689
690impl SessionCreateRequest {
691 /// Create a request with the required fields.
692 pub fn new(user_id: impl Into<String>, expires_in: Duration) -> Self {
693 Self {
694 user_id: user_id.into(),
695 expires_in,
696 ip_address: None,
697 user_agent: None,
698 }
699 }
700
701 /// Attach a client IP address for audit / geolocation.
702 pub fn ip_address(mut self, ip: impl Into<String>) -> Self {
703 self.ip_address = Some(ip.into());
704 self
705 }
706
707 /// Attach a `User-Agent` string for device tracking.
708 pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
709 self.user_agent = Some(ua.into());
710 self
711 }
712
713 /// Returns the user ID this session is being created for.
714 pub fn get_user_id(&self) -> &str {
715 &self.user_id
716 }
717
718 /// Returns how long until the session expires.
719 pub fn get_expires_in(&self) -> Duration {
720 self.expires_in
721 }
722
723 /// Returns the client IP address, if attached.
724 pub fn get_ip_address(&self) -> Option<&str> {
725 self.ip_address.as_deref()
726 }
727
728 /// Returns the `User-Agent` header value, if attached.
729 pub fn get_user_agent(&self) -> Option<&str> {
730 self.user_agent.as_deref()
731 }
732}
733
734/// Focused session-management operations exposed from [`AuthFramework::sessions`].
735///
736/// # Example
737///
738/// ```rust,no_run
739/// # use auth_framework::prelude::*;
740/// # use auth_framework::auth_operations::SessionCreateRequest;
741/// # use std::time::Duration;
742/// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
743/// // Using the request struct (recommended):
744/// let req = SessionCreateRequest::new("user-123", Duration::from_secs(3600))
745/// .ip_address("10.0.0.1");
746/// let sid = auth.sessions().create_session(req).await?;
747///
748/// // Positional shorthand still works:
749/// let sid = auth.sessions().create("user-123", Duration::from_secs(3600), None, None).await?;
750///
751/// let session = auth.sessions().get(&sid).await?;
752/// auth.sessions().delete(&sid).await?;
753/// # Ok(())
754/// # }
755/// ```
756pub struct SessionOperations<'a> {
757 pub(crate) framework: &'a AuthFramework,
758}
759
760impl SessionOperations<'_> {
761 /// Create a new session from a [`SessionCreateRequest`].
762 ///
763 /// This is the preferred entry point — it avoids passing `None` for
764 /// optional parameters and makes the call site self-documenting.
765 pub async fn create_session(&self, req: SessionCreateRequest) -> Result<String> {
766 self.framework
767 .create_session(&req.user_id, req.expires_in, req.ip_address, req.user_agent)
768 .await
769 }
770
771 /// Create a new session for a user (positional convenience).
772 ///
773 /// Prefer [`create_session`](Self::create_session) with a
774 /// [`SessionCreateRequest`] when you need optional fields.
775 pub async fn create(
776 &self,
777 user_id: &str,
778 expires_in: Duration,
779 ip_address: Option<String>,
780 user_agent: Option<String>,
781 ) -> Result<String> {
782 self.framework
783 .create_session(user_id, expires_in, ip_address, user_agent)
784 .await
785 }
786
787 /// Fetch a session by ID.
788 pub async fn get(&self, session_id: &str) -> Result<Option<SessionData>> {
789 self.framework.get_session(session_id).await
790 }
791
792 /// Delete a session by ID.
793 pub async fn delete(&self, session_id: &str) -> Result<()> {
794 self.framework.delete_session(session_id).await
795 }
796
797 /// List all sessions owned by a user.
798 pub async fn list_for_user(&self, user_id: &str) -> Result<Vec<SessionData>> {
799 self.framework.storage().list_user_sessions(user_id).await
800 }
801
802 /// List sessions owned by a user, optionally filtering out expired ones.
803 ///
804 /// # Example
805 ///
806 /// ```rust,no_run
807 /// # use auth_framework::prelude::*;
808 /// # use auth_framework::auth_operations::SessionFilter;
809 /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
810 /// let active = auth.sessions()
811 /// .list_for_user_filtered("user-1", SessionFilter::ActiveOnly)
812 /// .await?;
813 /// # Ok(())
814 /// # }
815 /// ```
816 pub async fn list_for_user_filtered(
817 &self,
818 user_id: &str,
819 filter: SessionFilter,
820 ) -> Result<Vec<SessionData>> {
821 let sessions = self.framework.storage().list_user_sessions(user_id).await?;
822 if filter.include_inactive() {
823 Ok(sessions)
824 } else {
825 Ok(sessions.into_iter().filter(|s| !s.is_expired()).collect())
826 }
827 }
828
829 /// Remove expired sessions and tokens.
830 pub async fn cleanup_expired(&self) -> Result<()> {
831 self.framework.cleanup_expired_data().await
832 }
833}
834
835// ──────────────────────────────────────────────────────────────────────────────
836// Token operations
837// ──────────────────────────────────────────────────────────────────────────────
838
839/// Builder for [`TokenOperations::create_token`].
840///
841/// Bundles the required token parameters (user ID, auth method) with optional
842/// scopes and lifetime, keeping call sites readable.
843///
844/// # Example
845///
846/// ```rust,no_run
847/// # use auth_framework::prelude::*;
848/// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
849/// let token = auth.tokens().create_token(
850/// TokenCreateRequest::new("user-123", "jwt")
851/// .scope("read")
852/// .scope("write")
853/// .lifetime(std::time::Duration::from_secs(7200))
854/// ).await?;
855/// # Ok(())
856/// # }
857/// ```
858#[derive(Debug, Clone)]
859pub struct TokenCreateRequest {
860 user_id: String,
861 method: String,
862 scopes: Vec<String>,
863 lifetime: Option<Duration>,
864}
865
866impl TokenCreateRequest {
867 /// Create a new token request for a user authenticated via `method`.
868 pub fn new(user_id: impl Into<String>, method: impl Into<String>) -> Self {
869 Self {
870 user_id: user_id.into(),
871 method: method.into(),
872 scopes: Vec::new(),
873 lifetime: None,
874 }
875 }
876
877 /// Add a single scope.
878 pub fn scope(mut self, scope: impl Into<String>) -> Self {
879 self.scopes.push(scope.into());
880 self
881 }
882
883 /// Add multiple scopes at once.
884 pub fn scopes<I, S>(mut self, scopes: I) -> Self
885 where
886 I: IntoIterator<Item = S>,
887 S: Into<String>,
888 {
889 self.scopes.extend(scopes.into_iter().map(Into::into));
890 self
891 }
892
893 /// Override the default token lifetime.
894 pub fn lifetime(mut self, duration: Duration) -> Self {
895 self.lifetime = Some(duration);
896 self
897 }
898}
899
900/// Focused token-management operations exposed from [`AuthFramework::tokens`].
901///
902/// # Example
903///
904/// ```rust,no_run
905/// # use auth_framework::prelude::*;
906/// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
907/// // Issue a JWT token
908/// let token = auth.tokens().create("user-123", &["read"], "jwt", None).await?;
909///
910/// // Validate
911/// assert!(auth.tokens().validate(&token).await?);
912///
913/// // Refresh
914/// let new_token = auth.tokens().refresh(&token).await?;
915///
916/// // Revoke
917/// auth.tokens().revoke(&new_token).await?;
918/// # Ok(())
919/// # }
920/// ```
921pub struct TokenOperations<'a> {
922 pub(crate) framework: &'a AuthFramework,
923}
924
925impl TokenOperations<'_> {
926 /// Create a new authentication token for a user.
927 ///
928 /// `scopes` accepts any iterator of string-like values, so all of these
929 /// work:
930 ///
931 /// ```rust,ignore
932 /// // Vec<String>
933 /// tokens.create("uid", vec!["read".into()], "jwt", None).await?;
934 /// // Slice of &str
935 /// tokens.create("uid", &["read", "write"], "jwt", None).await?;
936 /// // Empty
937 /// tokens.create("uid", std::iter::empty::<&str>(), "jwt", None).await?;
938 /// ```
939 ///
940 /// # Arguments
941 ///
942 /// * `user_id` — the user to issue a token for
943 /// * `scopes` — permission scopes to embed in the token
944 /// * `method_name` — the auth method that authenticated the user (e.g. `"jwt"`)
945 /// * `lifetime` — custom lifetime, or `None` for the configured default
946 pub async fn create<I, S>(
947 &self,
948 user_id: impl Into<String>,
949 scopes: I,
950 method_name: impl Into<String>,
951 lifetime: Option<Duration>,
952 ) -> Result<AuthToken>
953 where
954 I: IntoIterator<Item = S>,
955 S: AsRef<str>,
956 {
957 let scopes: Vec<String> = scopes.into_iter().map(|s| s.as_ref().to_owned()).collect();
958 self.framework
959 .create_auth_token(user_id, scopes, method_name, lifetime)
960 .await
961 }
962
963 /// Create a token from a [`TokenCreateRequest`].
964 ///
965 /// This is the preferred entry point — it replaces positional `Option`
966 /// parameters with a self-documenting builder.
967 ///
968 /// # Example
969 ///
970 /// ```rust,no_run
971 /// # use auth_framework::prelude::*;
972 /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
973 /// let token = auth.tokens().create_token(
974 /// TokenCreateRequest::new("user-123", "jwt")
975 /// .scope("read")
976 /// .scope("write")
977 /// ).await?;
978 /// # Ok(())
979 /// # }
980 /// ```
981 pub async fn create_token(&self, req: TokenCreateRequest) -> Result<AuthToken> {
982 self.framework
983 .create_auth_token(req.user_id, req.scopes, req.method, req.lifetime)
984 .await
985 }
986
987 /// Validate an authentication token.
988 pub async fn validate(&self, token: &AuthToken) -> Result<bool> {
989 self.framework.validate_token(token).await
990 }
991
992 /// Refresh an authentication token.
993 pub async fn refresh(&self, token: &AuthToken) -> Result<AuthToken> {
994 self.framework.refresh_token(token).await
995 }
996
997 /// Revoke an authentication token.
998 pub async fn revoke(&self, token: &AuthToken) -> Result<()> {
999 self.framework.revoke_token(token).await
1000 }
1001
1002 /// List all tokens belonging to a user.
1003 pub async fn list_for_user(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1004 self.framework.list_user_tokens(user_id).await
1005 }
1006
1007 /// Create an API key for a user.
1008 pub async fn create_api_key(
1009 &self,
1010 user_id: &str,
1011 expires_in: Option<Duration>,
1012 ) -> Result<String> {
1013 self.framework.create_api_key(user_id, expires_in).await
1014 }
1015
1016 /// Create an API key that carries `role`; see [`AuthFramework::create_api_key_with_role`].
1017 pub async fn create_api_key_with_role(
1018 &self,
1019 user_id: &str,
1020 role: &str,
1021 expires_in: Option<Duration>,
1022 ) -> Result<String> {
1023 self.framework
1024 .create_api_key_with_role(user_id, role, expires_in)
1025 .await
1026 }
1027
1028 /// Replace an API key with a new one; see [`AuthFramework::rotate_api_key`].
1029 pub async fn rotate_api_key(&self, old_key: &str) -> Result<String> {
1030 self.framework.rotate_api_key(old_key).await
1031 }
1032
1033 /// Replace an API key, choosing the new key's lifetime; see
1034 /// [`AuthFramework::rotate_api_key_with_expiry`].
1035 pub async fn rotate_api_key_with_expiry(
1036 &self,
1037 old_key: &str,
1038 expires_in: Option<Duration>,
1039 ) -> Result<String> {
1040 self.framework
1041 .rotate_api_key_with_expiry(old_key, expires_in)
1042 .await
1043 }
1044
1045 /// Validate an API key and return the associated user info.
1046 pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
1047 self.framework.validate_api_key(api_key).await
1048 }
1049
1050 /// Revoke an API key.
1051 pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
1052 self.framework.revoke_api_key(api_key).await
1053 }
1054}
1055
1056// ──────────────────────────────────────────────────────────────────────────────
1057// Authorization operations
1058// ──────────────────────────────────────────────────────────────────────────────
1059
1060/// Focused authorization operations exposed via [`AuthFramework::authorization()`].
1061///
1062/// Provides role-based access control (RBAC), direct permission grants, and
1063/// effective-permission queries.
1064///
1065/// # Example
1066///
1067/// ```rust,no_run
1068/// # async fn example(auth: &auth_framework::AuthFramework) -> auth_framework::Result<()> {
1069/// use auth_framework::permissions::{Permission, Role};
1070/// use auth_framework::tokens::AuthToken;
1071///
1072/// let authz = auth.authorization();
1073/// let token = AuthToken::builder("token_123", "user_123", "access_token").build();
1074///
1075/// // Create a role and assign it to a user
1076/// let mut editor = Role::new("editor");
1077/// editor.add_permission(Permission::new("articles", "edit"));
1078/// authz.create_role(editor).await?;
1079/// authz.assign_role("user_123", "editor").await?;
1080///
1081/// // Check permission via token
1082/// let allowed = authz.check(&token, "edit", "articles").await?;
1083/// # Ok(())
1084/// # }
1085/// ```
1086pub struct AuthorizationOperations<'a> {
1087 pub(crate) framework: &'a AuthFramework,
1088}
1089
1090impl AuthorizationOperations<'_> {
1091 /// Check whether a token grants access to an action on a resource.
1092 pub async fn check(&self, token: &AuthToken, action: &str, resource: &str) -> Result<bool> {
1093 self.framework
1094 .check_permission(token, action, resource)
1095 .await
1096 }
1097
1098 /// Grant a direct permission to a user.
1099 pub async fn grant(&self, user_id: &str, action: &str, resource: &str) -> Result<()> {
1100 self.framework
1101 .grant_permission(user_id, action, resource)
1102 .await
1103 }
1104
1105 /// Revoke a direct permission from a user.
1106 pub async fn revoke(&self, user_id: &str, action: &str, resource: &str) -> Result<()> {
1107 self.framework
1108 .revoke_permission(user_id, action, resource)
1109 .await
1110 }
1111
1112 /// Create a role.
1113 pub async fn create_role(&self, role: Role) -> Result<()> {
1114 self.framework.create_role(role).await
1115 }
1116
1117 /// List all defined roles.
1118 pub async fn list_roles(&self) -> Vec<Role> {
1119 self.framework.list_roles().await
1120 }
1121
1122 /// Fetch a role definition by name.
1123 pub async fn role(&self, role_name: &str) -> Result<Role> {
1124 self.framework.get_role(role_name).await
1125 }
1126
1127 /// Add a permission to an existing role.
1128 pub async fn add_role_permission(
1129 &self,
1130 role_name: &str,
1131 permission: crate::permissions::Permission,
1132 ) -> Result<()> {
1133 self.framework
1134 .add_role_permission(role_name, permission)
1135 .await
1136 }
1137
1138 /// Assign a role to a user.
1139 pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
1140 self.framework.assign_role(user_id, role_name).await
1141 }
1142
1143 /// Remove a role from a user.
1144 pub async fn remove_role(&self, user_id: &str, role_name: &str) -> Result<()> {
1145 self.framework.remove_role(user_id, role_name).await
1146 }
1147
1148 /// Check whether a user currently has a role.
1149 pub async fn has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
1150 self.framework.user_has_role(user_id, role_name).await
1151 }
1152
1153 /// List effective permissions for a user.
1154 pub async fn effective_permissions(&self, user_id: &str) -> Result<crate::types::Permissions> {
1155 self.framework
1156 .get_effective_permissions(user_id)
1157 .await
1158 .map(crate::types::Permissions)
1159 }
1160
1161 /// List the currently assigned runtime roles for a user.
1162 pub async fn roles_for_user(&self, user_id: &str) -> Result<crate::types::Roles> {
1163 self.framework
1164 .list_user_roles(user_id)
1165 .await
1166 .map(crate::types::Roles)
1167 }
1168}
1169
1170/// Focused maintenance operations exposed via [`AuthFramework::maintenance()`].
1171///
1172/// Backup, restore, and reset authentication state in the configured storage
1173/// backend. All operations support an [`ExecutionMode`] parameter that
1174/// controls whether changes are applied or merely previewed.
1175///
1176/// # Example
1177///
1178/// ```rust,no_run
1179/// # use auth_framework::auth_operations::ExecutionMode;
1180/// # async fn example(auth: &auth_framework::AuthFramework) -> auth_framework::Result<()> {
1181/// let maint = auth.maintenance();
1182///
1183/// // Preview a backup without writing to disk
1184/// let preview = maint.backup("/tmp/auth_backup.json", ExecutionMode::DryRun).await?;
1185/// println!("Would export {} records", preview.manifest.user_count);
1186///
1187/// // Perform the real backup
1188/// let report = maint.backup("/tmp/auth_backup.json", ExecutionMode::Execute).await?;
1189/// # Ok(())
1190/// # }
1191/// ```
1192pub struct MaintenanceOperations<'a> {
1193 pub(crate) framework: &'a AuthFramework,
1194}
1195
1196impl MaintenanceOperations<'_> {
1197 /// Export a logical snapshot to disk.
1198 ///
1199 /// Uses [`ExecutionMode`] for clarity at call sites.
1200 pub async fn backup(&self, output_path: &str, mode: ExecutionMode) -> Result<BackupReport> {
1201 crate::maintenance::backup_to_file(self.framework, output_path, mode.is_dry_run()).await
1202 }
1203
1204 /// Export a logical snapshot to disk (legacy API).
1205 ///
1206 /// Prefer [`backup`](Self::backup) with an [`ExecutionMode`] for
1207 /// self-documenting call sites.
1208 pub async fn backup_to_file(&self, output_path: &str, dry_run: bool) -> Result<BackupReport> {
1209 crate::maintenance::backup_to_file(self.framework, output_path, dry_run).await
1210 }
1211
1212 /// Restore a logical snapshot from disk.
1213 ///
1214 /// Uses [`ExecutionMode`] for clarity at call sites.
1215 pub async fn restore(&self, backup_path: &str, mode: ExecutionMode) -> Result<RestoreReport> {
1216 crate::maintenance::restore_from_file(self.framework, backup_path, mode.is_dry_run()).await
1217 }
1218
1219 /// Restore a logical snapshot from disk (legacy API).
1220 ///
1221 /// Prefer [`restore`](Self::restore) with an [`ExecutionMode`] for
1222 /// self-documenting call sites.
1223 pub async fn restore_from_file(
1224 &self,
1225 backup_path: &str,
1226 dry_run: bool,
1227 ) -> Result<RestoreReport> {
1228 crate::maintenance::restore_from_file(self.framework, backup_path, dry_run).await
1229 }
1230
1231 /// Reset logical authentication state in the configured backend.
1232 ///
1233 /// Uses [`ExecutionMode`] for clarity at call sites.
1234 pub async fn reset_with_mode(&self, mode: ExecutionMode) -> Result<ResetReport> {
1235 crate::maintenance::reset_runtime_data(self.framework, mode.is_dry_run()).await
1236 }
1237
1238 /// Reset logical authentication state in the configured backend (legacy API).
1239 ///
1240 /// Prefer [`reset_with_mode`](Self::reset_with_mode) with an
1241 /// [`ExecutionMode`] for self-documenting call sites.
1242 pub async fn reset(&self, dry_run: bool) -> Result<ResetReport> {
1243 crate::maintenance::reset_runtime_data(self.framework, dry_run).await
1244 }
1245}
1246
1247// ──────────────────────────────────────────────────────────────────────────────
1248// MFA operations
1249// ──────────────────────────────────────────────────────────────────────────────
1250
1251/// Focused multi-factor authentication operations exposed via [`AuthFramework::mfa()`].
1252///
1253/// Covers TOTP, SMS, email challenges, backup codes, and MFA completion
1254/// flows.
1255///
1256/// # Example
1257///
1258/// ```rust,no_run
1259/// # async fn example(auth: &auth_framework::AuthFramework) -> auth_framework::Result<()> {
1260/// let mfa = auth.mfa();
1261///
1262/// // Set up TOTP for a user
1263/// let secret = mfa.generate_totp_secret("user_123").await?;
1264/// let qr_url = mfa.generate_totp_qr_url("user_123", "MyApp", &secret).await?;
1265///
1266/// // Verify a code supplied by the user
1267/// let valid = mfa.verify_totp("user_123", "123456").await?;
1268/// # Ok(())
1269/// # }
1270/// ```
1271pub struct MfaOperations<'a> {
1272 pub(crate) framework: &'a AuthFramework,
1273}
1274
1275impl MfaOperations<'_> {
1276 /// Complete a pending MFA challenge with the provided code.
1277 pub async fn complete(&self, challenge: MfaChallenge, code: &str) -> Result<AuthToken> {
1278 self.framework.complete_mfa(challenge, code).await
1279 }
1280
1281 /// Complete a pending MFA challenge by its ID.
1282 pub async fn complete_by_id(&self, challenge_id: &str, code: &str) -> Result<AuthToken> {
1283 self.framework.complete_mfa_by_id(challenge_id, code).await
1284 }
1285
1286 /// Initiate an SMS-based MFA challenge for a user.
1287 pub async fn initiate_sms(&self, user_id: &str) -> Result<String> {
1288 self.framework.initiate_sms_challenge(user_id).await
1289 }
1290
1291 /// Verify an SMS challenge code.
1292 pub async fn verify_sms(&self, challenge_id: &str, code: &str) -> Result<bool> {
1293 self.framework.verify_sms_code(challenge_id, code).await
1294 }
1295
1296 /// Initiate an email-based MFA challenge for a user.
1297 pub async fn initiate_email(&self, user_id: &str) -> Result<String> {
1298 self.framework.initiate_email_challenge(user_id).await
1299 }
1300
1301 /// Register a phone number for SMS MFA.
1302 pub async fn register_phone(&self, user_id: &str, phone_number: &str) -> Result<()> {
1303 self.framework
1304 .register_phone_number(user_id, phone_number)
1305 .await
1306 }
1307
1308 /// Register an email address for email MFA.
1309 pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
1310 self.framework.register_email(user_id, email).await
1311 }
1312
1313 /// Generate a TOTP secret for a user.
1314 pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
1315 self.framework.generate_totp_secret(user_id).await
1316 }
1317
1318 /// Generate a TOTP QR code provisioning URL.
1319 pub async fn generate_totp_qr_url(
1320 &self,
1321 user_id: &str,
1322 app_name: &str,
1323 secret: &str,
1324 ) -> Result<String> {
1325 self.framework
1326 .generate_totp_qr_code(user_id, app_name, secret)
1327 .await
1328 }
1329
1330 /// Generate the current TOTP code for a secret.
1331 pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
1332 self.framework.generate_totp_code(secret).await
1333 }
1334
1335 /// Verify a TOTP code for a user.
1336 pub async fn verify_totp(&self, user_id: &str, code: &str) -> Result<bool> {
1337 self.framework.verify_totp_code(user_id, code).await
1338 }
1339
1340 /// Generate backup codes for a user.
1341 pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
1342 self.framework.generate_backup_codes(user_id, count).await
1343 }
1344}
1345
1346// ──────────────────────────────────────────────────────────────────────────────
1347// Monitoring operations
1348// ──────────────────────────────────────────────────────────────────────────────
1349
1350/// Focused monitoring and health operations exposed via [`AuthFramework::monitoring()`].
1351///
1352/// Health-checks, performance and security metrics, Prometheus export, and
1353/// rate-limit inspection.
1354///
1355/// # Example
1356///
1357/// ```rust,no_run
1358/// # async fn example(auth: &auth_framework::AuthFramework) -> auth_framework::Result<()> {
1359/// let mon = auth.monitoring();
1360///
1361/// let health = mon.health_check().await?;
1362/// let stats = mon.stats().await?;
1363/// let prom = mon.prometheus_metrics().await;
1364/// # Ok(())
1365/// # }
1366/// ```
1367pub struct MonitoringOperations<'a> {
1368 pub(crate) framework: &'a AuthFramework,
1369}
1370
1371impl MonitoringOperations<'_> {
1372 /// Perform a comprehensive health check across all subsystems.
1373 ///
1374 /// Returns a map of subsystem name → health result (e.g. `"storage"`,
1375 /// `"token_manager"`, `"rate_limiter"`).
1376 pub async fn health_check(
1377 &self,
1378 ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
1379 self.framework.health_check().await
1380 }
1381
1382 /// Get current performance metrics.
1383 ///
1384 /// Returns a map of metric name → counter value (e.g.
1385 /// `"auth_requests"`, `"auth_successes"`, `"auth_failures"`).
1386 pub async fn performance_metrics(&self) -> std::collections::HashMap<String, u64> {
1387 self.framework.get_performance_metrics().await
1388 }
1389
1390 /// Get aggregated security metrics.
1391 ///
1392 /// Returns a map of metric name → counter value (e.g.
1393 /// `"brute_force_blocked"`, `"rate_limited_requests"`).
1394 pub async fn security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
1395 self.framework.get_security_metrics().await
1396 }
1397
1398 /// Export metrics in Prometheus text format.
1399 pub async fn prometheus_metrics(&self) -> String {
1400 self.framework.export_prometheus_metrics().await
1401 }
1402
1403 /// Get authentication statistics.
1404 pub async fn stats(&self) -> Result<AuthStats> {
1405 self.framework.get_stats().await
1406 }
1407
1408 /// Check whether an IP address is within the configured rate limit.
1409 pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
1410 self.framework.check_ip_rate_limit(ip).await
1411 }
1412
1413 /// Access the underlying monitoring manager for advanced usage.
1414 pub fn manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
1415 self.framework.monitoring_manager()
1416 }
1417}
1418
1419// ──────────────────────────────────────────────────────────────────────────────
1420// Audit operations
1421// ──────────────────────────────────────────────────────────────────────────────
1422
1423/// Focused audit log operations exposed via [`AuthFramework::audit()`].
1424///
1425/// Query permission audit logs, view permission metrics, and retrieve
1426/// comprehensive security audit statistics.
1427///
1428/// # Example
1429///
1430/// ```rust,no_run
1431/// # async fn example(auth: &auth_framework::AuthFramework) -> auth_framework::Result<()> {
1432/// let audit = auth.audit();
1433///
1434/// // Retrieve recent permission log entries for a specific user
1435/// let logs = audit.permission_logs(Some("user_123"), None, None, Some(50)).await?;
1436///
1437/// // Get security audit statistics
1438/// let stats = audit.security_stats().await?;
1439/// # Ok(())
1440/// # }
1441/// ```
1442pub struct AuditOperations<'a> {
1443 pub(crate) framework: &'a AuthFramework,
1444}
1445
1446impl AuditOperations<'_> {
1447 /// Query permission-related audit log entries using an [`AuditLogQuery`].
1448 ///
1449 /// # Example
1450 ///
1451 /// ```rust,ignore
1452 /// let logs = auth.audit()
1453 /// .query_permission_logs(
1454 /// AuditLogQuery::new()
1455 /// .user("user_123")
1456 /// .action("read")
1457 /// .limit(50)
1458 /// )
1459 /// .await?;
1460 /// ```
1461 pub async fn query_permission_logs(&self, query: AuditLogQuery) -> Result<Vec<String>> {
1462 self.framework
1463 .get_permission_audit_logs(
1464 query.user_id.as_deref(),
1465 query.action.as_deref(),
1466 query.resource.as_deref(),
1467 query.limit,
1468 )
1469 .await
1470 }
1471
1472 /// Query permission-related audit log entries with optional filters.
1473 ///
1474 /// Prefer [`query_permission_logs`](Self::query_permission_logs) with an
1475 /// [`AuditLogQuery`] for better readability when using multiple filters.
1476 pub async fn permission_logs(
1477 &self,
1478 user_id: Option<&str>,
1479 action: Option<&str>,
1480 resource: Option<&str>,
1481 limit: Option<usize>,
1482 ) -> Result<Vec<String>> {
1483 self.framework
1484 .get_permission_audit_logs(user_id, action, resource, limit)
1485 .await
1486 }
1487
1488 /// Get aggregated permission metrics (role counts, active sessions, checks per hour).
1489 pub async fn permission_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
1490 self.framework.get_permission_metrics().await
1491 }
1492
1493 /// Get comprehensive security audit statistics.
1494 pub async fn security_stats(&self) -> Result<SecurityAuditStats> {
1495 self.framework.get_security_audit_stats().await
1496 }
1497}
1498// ──────────────────────────────────────────────────────────────────────────────
1499// Admin operations
1500// ──────────────────────────────────────────────────────────────────────────────
1501
1502/// Focused advanced administration operations exposed from [`AuthFramework::admin`].
1503///
1504/// These operations go beyond the everyday [`AuthorizationOperations`] surface and cover
1505/// ABAC policy management, permission delegation, role inheritance, resource registration,
1506/// and attribute-based access control.
1507pub struct AdminOperations<'a> {
1508 pub(crate) framework: &'a AuthFramework,
1509}
1510
1511impl AdminOperations<'_> {
1512 /// Define a parent–child role inheritance relationship.
1513 pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
1514 self.framework
1515 .set_role_inheritance(child_role, parent_role)
1516 .await
1517 }
1518
1519 /// Create an ABAC policy.
1520 pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
1521 self.framework.create_abac_policy(name, description).await
1522 }
1523
1524 /// Map a user attribute used in ABAC policy evaluation.
1525 pub async fn map_user_attribute(
1526 &self,
1527 user_id: &str,
1528 attribute: &str,
1529 value: &str,
1530 ) -> Result<()> {
1531 self.framework
1532 .map_user_attribute(user_id, attribute, value)
1533 .await
1534 }
1535
1536 /// Set multiple user attributes in one call.
1537 ///
1538 /// This is a convenience wrapper around [`map_user_attribute`](Self::map_user_attribute)
1539 /// for setting several ABAC attributes at once.
1540 ///
1541 /// # Example
1542 ///
1543 /// ```rust,no_run
1544 /// # use auth_framework::prelude::*;
1545 /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
1546 /// auth.admin().set_user_attributes("user-1", &[
1547 /// ("department", "engineering"),
1548 /// ("clearance", "top-secret"),
1549 /// ("location", "us-west-2"),
1550 /// ]).await?;
1551 /// # Ok(())
1552 /// # }
1553 /// ```
1554 pub async fn set_user_attributes(
1555 &self,
1556 user_id: &str,
1557 attributes: &[(&str, &str)],
1558 ) -> Result<()> {
1559 for &(attribute, value) in attributes {
1560 self.framework
1561 .map_user_attribute(user_id, attribute, value)
1562 .await?;
1563 }
1564 Ok(())
1565 }
1566
1567 /// Get a user attribute value.
1568 pub async fn get_user_attribute(
1569 &self,
1570 user_id: &str,
1571 attribute: &str,
1572 ) -> Result<Option<String>> {
1573 self.framework.get_user_attribute(user_id, attribute).await
1574 }
1575
1576 /// Check a permission using dynamic ABAC context evaluation.
1577 ///
1578 /// Prefer [`check_dynamic_permission_with_context`](Self::check_dynamic_permission_with_context)
1579 /// with a [`PermissionContext`] for a more readable API.
1580 pub async fn check_dynamic_permission(
1581 &self,
1582 user_id: &str,
1583 action: &str,
1584 resource: &str,
1585 context: std::collections::HashMap<String, String>,
1586 ) -> Result<bool> {
1587 self.framework
1588 .check_dynamic_permission(user_id, action, resource, context)
1589 .await
1590 }
1591
1592 /// Check a permission using dynamic ABAC context evaluation with a
1593 /// [`PermissionContext`].
1594 ///
1595 /// # Example
1596 ///
1597 /// ```rust,ignore
1598 /// use auth_framework::auth_operations::PermissionContext;
1599 ///
1600 /// let ctx = PermissionContext::new()
1601 /// .with_attribute("ip_location", "office")
1602 /// .with_attribute("device_type", "trusted");
1603 ///
1604 /// let allowed = auth.admin()
1605 /// .check_dynamic_permission_with_context("user_123", "read", "docs", ctx)
1606 /// .await?;
1607 /// ```
1608 pub async fn check_dynamic_permission_with_context(
1609 &self,
1610 user_id: &str,
1611 action: &str,
1612 resource: &str,
1613 context: PermissionContext,
1614 ) -> Result<bool> {
1615 self.framework
1616 .check_dynamic_permission(user_id, action, resource, context.into_attributes())
1617 .await
1618 }
1619
1620 /// Register a resource in the permission system.
1621 pub async fn create_resource(&self, resource: &str) -> Result<()> {
1622 self.framework.create_resource(resource).await
1623 }
1624
1625 /// Delegate a permission from one user to another using a [`DelegationRequest`].
1626 ///
1627 /// # Example
1628 ///
1629 /// ```rust,ignore
1630 /// auth.admin()
1631 /// .delegate(
1632 /// DelegationRequest::new("admin_1", "user_2", "write", "reports")
1633 /// .duration(Duration::from_secs(3600))
1634 /// )
1635 /// .await?;
1636 /// ```
1637 pub async fn delegate(&self, req: DelegationRequest) -> Result<()> {
1638 self.framework
1639 .delegate_permission(
1640 &req.delegator_id,
1641 &req.delegatee_id,
1642 &req.action,
1643 &req.resource,
1644 req.duration,
1645 )
1646 .await
1647 }
1648
1649 /// Delegate a permission from one user to another for a limited duration.
1650 ///
1651 /// Prefer [`delegate`](Self::delegate) with a [`DelegationRequest`] for
1652 /// better readability.
1653 pub async fn delegate_permission(
1654 &self,
1655 delegator_id: &str,
1656 delegatee_id: &str,
1657 action: &str,
1658 resource: &str,
1659 duration: Duration,
1660 ) -> Result<()> {
1661 self.framework
1662 .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
1663 .await
1664 }
1665
1666 /// List currently active permission delegations for a user.
1667 pub async fn active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
1668 self.framework.get_active_delegations(user_id).await
1669 }
1670}
1671#[cfg(test)]
1672mod tests {
1673 use super::*;
1674 use crate::config::AuthConfig;
1675
1676 async fn make_fw() -> AuthFramework {
1677 let config = AuthConfig::new().secret("test_ops_secret_key_32bytes_long!".to_string());
1678 let mut fw = AuthFramework::new(config);
1679 fw.initialize().await.unwrap();
1680 fw
1681 }
1682
1683 // ── UserOperations ──────────────────────────────────────────────────
1684
1685 #[tokio::test]
1686 async fn test_user_ops_register_and_get() {
1687 let fw = make_fw().await;
1688 let uid = fw
1689 .users()
1690 .register("ops_user1", "ops1@test.com", "StrongP@ss1!")
1691 .await
1692 .unwrap();
1693 let info = fw.users().get(&uid).await.unwrap();
1694 assert_eq!(info.username, "ops_user1");
1695 }
1696
1697 #[tokio::test]
1698 async fn test_user_ops_list_empty() {
1699 let fw = make_fw().await;
1700 let list = fw
1701 .users()
1702 .list_with_query(UserListQuery::new().limit(10))
1703 .await
1704 .unwrap();
1705 assert!(list.is_empty());
1706 }
1707
1708 #[tokio::test]
1709 async fn test_user_ops_exists_by_username() {
1710 let fw = make_fw().await;
1711 fw.users()
1712 .register("exists_u", "exists@test.com", "StrongP@ss1!")
1713 .await
1714 .unwrap();
1715 assert!(fw.users().exists_by_username("exists_u").await.unwrap());
1716 assert!(!fw.users().exists_by_username("nope_u").await.unwrap());
1717 }
1718
1719 #[tokio::test]
1720 async fn test_user_ops_exists_by_email() {
1721 let fw = make_fw().await;
1722 fw.users()
1723 .register("email_u", "email_exists@test.com", "StrongP@ss1!")
1724 .await
1725 .unwrap();
1726 assert!(
1727 fw.users()
1728 .exists_by_email("email_exists@test.com")
1729 .await
1730 .unwrap()
1731 );
1732 assert!(!fw.users().exists_by_email("no@test.com").await.unwrap());
1733 }
1734
1735 #[tokio::test]
1736 async fn test_user_ops_profile() {
1737 let fw = make_fw().await;
1738 let uid = fw
1739 .users()
1740 .register("profile_u", "prof@test.com", "StrongP@ss1!")
1741 .await
1742 .unwrap();
1743 let profile = fw.users().profile(&uid).await.unwrap();
1744 assert_eq!(profile.display_name().unwrap_or_default(), "profile_u");
1745 }
1746
1747 #[tokio::test]
1748 async fn test_user_ops_update_password_and_verify() {
1749 let fw = make_fw().await;
1750 let uid = fw
1751 .users()
1752 .register("pw_user", "pw@test.com", "StrongP@ss1!")
1753 .await
1754 .unwrap();
1755 fw.users()
1756 .update_password("pw_user", "NewStr0ng!Pass")
1757 .await
1758 .unwrap();
1759 assert!(
1760 fw.users()
1761 .verify_password(&uid, "NewStr0ng!Pass")
1762 .await
1763 .unwrap()
1764 );
1765 }
1766
1767 #[tokio::test]
1768 async fn test_user_ops_update_email() {
1769 let fw = make_fw().await;
1770 let uid = fw
1771 .users()
1772 .register("email_upd_u", "old@test.com", "StrongP@ss1!")
1773 .await
1774 .unwrap();
1775 fw.users().update_email(&uid, "new@test.com").await.unwrap();
1776 assert!(fw.users().exists_by_email("new@test.com").await.unwrap());
1777 }
1778
1779 #[tokio::test]
1780 async fn test_user_ops_set_active() {
1781 let fw = make_fw().await;
1782 let uid = fw
1783 .users()
1784 .register("act_u", "act@test.com", "StrongP@ss1!")
1785 .await
1786 .unwrap();
1787 fw.users()
1788 .set_status(&uid, UserStatus::Inactive)
1789 .await
1790 .unwrap();
1791 let info = fw.users().get(&uid).await.unwrap();
1792 assert!(!info.active);
1793 }
1794
1795 #[tokio::test]
1796 async fn test_user_ops_delete() {
1797 let fw = make_fw().await;
1798 fw.users()
1799 .register("del_u", "del@test.com", "StrongP@ss1!")
1800 .await
1801 .unwrap();
1802 fw.users().delete("del_u").await.unwrap();
1803 assert!(!fw.users().exists_by_username("del_u").await.unwrap());
1804 }
1805
1806 #[tokio::test]
1807 async fn test_user_ops_username() {
1808 let fw = make_fw().await;
1809 let uid = fw
1810 .users()
1811 .register("name_u", "name@test.com", "StrongP@ss1!")
1812 .await
1813 .unwrap();
1814 let name = fw.users().username(&uid).await.unwrap();
1815 assert_eq!(name, "name_u");
1816 }
1817
1818 // ── SessionOperations ───────────────────────────────────────────────
1819
1820 #[tokio::test]
1821 async fn test_session_ops_create_get_delete() {
1822 let fw = make_fw().await;
1823 let uid = fw
1824 .users()
1825 .register("sess_u", "sess@test.com", "StrongP@ss1!")
1826 .await
1827 .unwrap();
1828 let sid = fw
1829 .sessions()
1830 .create(&uid, Duration::from_secs(3600), None, None)
1831 .await
1832 .unwrap();
1833 let sess = fw.sessions().get(&sid).await.unwrap();
1834 assert!(sess.is_some());
1835 fw.sessions().delete(&sid).await.unwrap();
1836 assert!(fw.sessions().get(&sid).await.unwrap().is_none());
1837 }
1838
1839 #[tokio::test]
1840 async fn test_session_ops_list_for_user() {
1841 let fw = make_fw().await;
1842 let uid = fw
1843 .users()
1844 .register("sl_u", "sl@test.com", "StrongP@ss1!")
1845 .await
1846 .unwrap();
1847 fw.sessions()
1848 .create(&uid, Duration::from_secs(3600), None, None)
1849 .await
1850 .unwrap();
1851 let list = fw.sessions().list_for_user(&uid).await.unwrap();
1852 assert_eq!(list.len(), 1);
1853 }
1854
1855 #[tokio::test]
1856 async fn test_session_ops_cleanup_expired() {
1857 let fw = make_fw().await;
1858 // Should not error even with no sessions
1859 fw.sessions().cleanup_expired().await.unwrap();
1860 }
1861
1862 // ── TokenOperations ─────────────────────────────────────────────────
1863
1864 #[tokio::test]
1865 async fn test_token_ops_create_validate_revoke() {
1866 let fw = make_fw().await;
1867 let uid = fw
1868 .users()
1869 .register("tok_u", "tok@test.com", "StrongP@ss1!")
1870 .await
1871 .unwrap();
1872 // Create API key instead of auth token—no auth method registration needed
1873 let key = fw.tokens().create_api_key(&uid, None).await.unwrap();
1874 let info = fw.tokens().validate_api_key(&key).await.unwrap();
1875 assert!(!info.id.is_empty());
1876 fw.tokens().revoke_api_key(&key).await.unwrap();
1877 }
1878
1879 #[tokio::test]
1880 async fn test_token_ops_api_key_lifecycle() {
1881 let fw = make_fw().await;
1882 let uid = fw
1883 .users()
1884 .register("apikey_u", "apikey@test.com", "StrongP@ss1!")
1885 .await
1886 .unwrap();
1887 let key = fw.tokens().create_api_key(&uid, None).await.unwrap();
1888 let info = fw.tokens().validate_api_key(&key).await.unwrap();
1889 // API key creates an internal user; just verify it resolves
1890 assert!(!info.id.is_empty());
1891 fw.tokens().revoke_api_key(&key).await.unwrap();
1892 assert!(fw.tokens().validate_api_key(&key).await.is_err());
1893 }
1894
1895 // ── AuthorizationOperations ─────────────────────────────────────────
1896
1897 #[tokio::test]
1898 async fn test_authz_ops_grant_and_check() {
1899 let fw = make_fw().await;
1900 let uid = fw
1901 .users()
1902 .register("authz_u", "authz@test.com", "StrongP@ss1!")
1903 .await
1904 .unwrap();
1905 fw.authorization()
1906 .grant(&uid, "read", "docs")
1907 .await
1908 .unwrap();
1909 // Verify via has_role / effective_permissions rather than via token (no auth method registered)
1910 let perms = fw
1911 .authorization()
1912 .effective_permissions(&uid)
1913 .await
1914 .unwrap();
1915 assert!(perms.iter().any(|p| p.contains("read")));
1916 }
1917
1918 #[tokio::test]
1919 async fn test_authz_ops_role_lifecycle() {
1920 let fw = make_fw().await;
1921 let uid = fw
1922 .users()
1923 .register("role_u", "role@test.com", "StrongP@ss1!")
1924 .await
1925 .unwrap();
1926 fw.authorization().assign_role(&uid, "admin").await.unwrap();
1927 assert!(fw.authorization().has_role(&uid, "admin").await.unwrap());
1928 let roles = fw.authorization().roles_for_user(&uid).await.unwrap();
1929 assert!(roles.contains("admin"));
1930 fw.authorization().remove_role(&uid, "admin").await.unwrap();
1931 assert!(!fw.authorization().has_role(&uid, "admin").await.unwrap());
1932 }
1933
1934 // ── MfaOperations ───────────────────────────────────────────────────
1935
1936 #[tokio::test]
1937 async fn test_mfa_ops_totp_lifecycle() {
1938 let fw = make_fw().await;
1939 let uid = fw
1940 .users()
1941 .register("mfa_u", "mfa@test.com", "StrongP@ss1!")
1942 .await
1943 .unwrap();
1944 let secret = fw.mfa().generate_totp_secret(&uid).await.unwrap();
1945 assert!(!secret.is_empty());
1946 let code = fw.mfa().generate_totp_code(&secret).await.unwrap();
1947 assert_eq!(code.len(), 6);
1948 assert!(fw.mfa().verify_totp(&uid, &code).await.unwrap());
1949 }
1950
1951 #[tokio::test]
1952 async fn test_mfa_ops_backup_codes() {
1953 let fw = make_fw().await;
1954 let uid = fw
1955 .users()
1956 .register("bc_u", "bc@test.com", "StrongP@ss1!")
1957 .await
1958 .unwrap();
1959 let codes = fw.mfa().generate_backup_codes(&uid, 5).await.unwrap();
1960 assert_eq!(codes.len(), 5);
1961 }
1962
1963 #[tokio::test]
1964 async fn test_mfa_ops_sms_lifecycle() {
1965 let fw = make_fw().await;
1966 let uid = fw
1967 .users()
1968 .register("smsop_u", "smsop@test.com", "StrongP@ss1!")
1969 .await
1970 .unwrap();
1971 fw.mfa().register_phone(&uid, "+12345678901").await.unwrap();
1972 let cid = fw.mfa().initiate_sms(&uid).await.unwrap();
1973 assert!(!cid.is_empty());
1974 }
1975
1976 #[tokio::test]
1977 async fn test_mfa_ops_email_lifecycle() {
1978 let fw = make_fw().await;
1979 let uid = fw
1980 .users()
1981 .register("emop_u", "emop@test.com", "StrongP@ss1!")
1982 .await
1983 .unwrap();
1984 fw.mfa()
1985 .register_email(&uid, "emop@test.com")
1986 .await
1987 .unwrap();
1988 let cid = fw.mfa().initiate_email(&uid).await.unwrap();
1989 assert!(!cid.is_empty());
1990 }
1991
1992 // ── MonitoringOperations ────────────────────────────────────────────
1993
1994 #[tokio::test]
1995 async fn test_monitoring_ops_health_check() {
1996 let fw = make_fw().await;
1997 let health = fw.monitoring().health_check().await.unwrap();
1998 assert!(!health.is_empty());
1999 }
2000
2001 #[tokio::test]
2002 async fn test_monitoring_ops_performance_metrics() {
2003 let fw = make_fw().await;
2004 let _metrics = fw.monitoring().performance_metrics().await;
2005 }
2006
2007 #[tokio::test]
2008 async fn test_monitoring_ops_stats() {
2009 let fw = make_fw().await;
2010 let stats = fw.monitoring().stats().await.unwrap();
2011 assert_eq!(stats.active_sessions, 0);
2012 }
2013
2014 #[tokio::test]
2015 async fn test_monitoring_ops_prometheus() {
2016 let fw = make_fw().await;
2017 let prom = fw.monitoring().prometheus_metrics().await;
2018 // Just verify it returns valid-looking metrics text
2019 assert!(!prom.is_empty());
2020 }
2021
2022 // ── AdminOperations ─────────────────────────────────────────────────
2023
2024 #[tokio::test]
2025 async fn test_admin_ops_role_inheritance() {
2026 let fw = make_fw().await;
2027 // Default roles include "admin" and "user" — use those
2028 fw.admin()
2029 .set_role_inheritance("user", "admin")
2030 .await
2031 .unwrap();
2032 }
2033
2034 #[tokio::test]
2035 async fn test_admin_ops_abac_policy() {
2036 let fw = make_fw().await;
2037 fw.admin()
2038 .create_abac_policy("ip_allow", "IP allowlist policy")
2039 .await
2040 .unwrap();
2041 }
2042
2043 #[tokio::test]
2044 async fn test_admin_ops_user_attributes() {
2045 let fw = make_fw().await;
2046 let uid = fw
2047 .users()
2048 .register("attr_u", "attr@test.com", "StrongP@ss1!")
2049 .await
2050 .unwrap();
2051 fw.admin()
2052 .map_user_attribute(&uid, "department", "engineering")
2053 .await
2054 .unwrap();
2055 let val = fw
2056 .admin()
2057 .get_user_attribute(&uid, "department")
2058 .await
2059 .unwrap();
2060 assert_eq!(val.as_deref(), Some("engineering"));
2061 }
2062
2063 #[tokio::test]
2064 async fn test_admin_ops_delegation() {
2065 let fw = make_fw().await;
2066 let uid1 = fw
2067 .users()
2068 .register("del_from", "delf@test.com", "StrongP@ss1!")
2069 .await
2070 .unwrap();
2071 let uid2 = fw
2072 .users()
2073 .register("del_to", "delt@test.com", "StrongP@ss1!")
2074 .await
2075 .unwrap();
2076 fw.authorization()
2077 .grant(&uid1, "write", "report")
2078 .await
2079 .unwrap();
2080 fw.admin()
2081 .delegate_permission(&uid1, &uid2, "write", "report", Duration::from_secs(3600))
2082 .await
2083 .unwrap();
2084 }
2085
2086 // ── MaintenanceOperations ───────────────────────────────────────────
2087
2088 #[tokio::test]
2089 async fn test_maintenance_ops_backup_dry_run() {
2090 let fw = make_fw().await;
2091 let report = fw
2092 .maintenance()
2093 .backup_to_file("test_backup.json", true)
2094 .await
2095 .unwrap();
2096 assert!(report.dry_run);
2097 }
2098
2099 #[tokio::test]
2100 async fn test_maintenance_ops_reset_dry_run() {
2101 let fw = make_fw().await;
2102 let report = fw.maintenance().reset(true).await.unwrap();
2103 assert!(report.dry_run);
2104 }
2105
2106 // ── AuditOperations ─────────────────────────────────────────────────
2107
2108 #[tokio::test]
2109 async fn test_audit_ops_permission_logs() {
2110 let fw = make_fw().await;
2111 let logs = fw
2112 .audit()
2113 .permission_logs(None, None, None, Some(10))
2114 .await
2115 .unwrap();
2116 assert!(logs.is_empty()); // no activity yet
2117 }
2118
2119 #[tokio::test]
2120 async fn test_audit_ops_permission_metrics() {
2121 let fw = make_fw().await;
2122 let metrics = fw.audit().permission_metrics().await.unwrap();
2123 assert!(!metrics.is_empty());
2124 }
2125
2126 #[tokio::test]
2127 async fn test_audit_ops_security_stats() {
2128 let fw = make_fw().await;
2129 let stats = fw.audit().security_stats().await.unwrap();
2130 assert_eq!(stats.failed_logins_24h, 0);
2131 }
2132}