Skip to main content

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    /// Validate an API key and return the associated user info.
1017    pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
1018        self.framework.validate_api_key(api_key).await
1019    }
1020
1021    /// Revoke an API key.
1022    pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
1023        self.framework.revoke_api_key(api_key).await
1024    }
1025}
1026
1027// ──────────────────────────────────────────────────────────────────────────────
1028// Authorization operations
1029// ──────────────────────────────────────────────────────────────────────────────
1030
1031/// Focused authorization operations exposed via [`AuthFramework::authorization()`].
1032///
1033/// Provides role-based access control (RBAC), direct permission grants, and
1034/// effective-permission queries.
1035///
1036/// # Example
1037///
1038/// ```rust,no_run
1039/// # async fn example(auth: &auth_framework::AuthFramework) -> auth_framework::Result<()> {
1040/// use auth_framework::permissions::{Permission, Role};
1041/// use auth_framework::tokens::AuthToken;
1042///
1043/// let authz = auth.authorization();
1044/// let token = AuthToken::builder("token_123", "user_123", "access_token").build();
1045///
1046/// // Create a role and assign it to a user
1047/// let mut editor = Role::new("editor");
1048/// editor.add_permission(Permission::new("articles", "edit"));
1049/// authz.create_role(editor).await?;
1050/// authz.assign_role("user_123", "editor").await?;
1051///
1052/// // Check permission via token
1053/// let allowed = authz.check(&token, "edit", "articles").await?;
1054/// # Ok(())
1055/// # }
1056/// ```
1057pub struct AuthorizationOperations<'a> {
1058    pub(crate) framework: &'a AuthFramework,
1059}
1060
1061impl AuthorizationOperations<'_> {
1062    /// Check whether a token grants access to an action on a resource.
1063    pub async fn check(&self, token: &AuthToken, action: &str, resource: &str) -> Result<bool> {
1064        self.framework
1065            .check_permission(token, action, resource)
1066            .await
1067    }
1068
1069    /// Grant a direct permission to a user.
1070    pub async fn grant(&self, user_id: &str, action: &str, resource: &str) -> Result<()> {
1071        self.framework
1072            .grant_permission(user_id, action, resource)
1073            .await
1074    }
1075
1076    /// Revoke a direct permission from a user.
1077    pub async fn revoke(&self, user_id: &str, action: &str, resource: &str) -> Result<()> {
1078        self.framework
1079            .revoke_permission(user_id, action, resource)
1080            .await
1081    }
1082
1083    /// Create a role.
1084    pub async fn create_role(&self, role: Role) -> Result<()> {
1085        self.framework.create_role(role).await
1086    }
1087
1088    /// List all defined roles.
1089    pub async fn list_roles(&self) -> Vec<Role> {
1090        self.framework.list_roles().await
1091    }
1092
1093    /// Fetch a role definition by name.
1094    pub async fn role(&self, role_name: &str) -> Result<Role> {
1095        self.framework.get_role(role_name).await
1096    }
1097
1098    /// Add a permission to an existing role.
1099    pub async fn add_role_permission(
1100        &self,
1101        role_name: &str,
1102        permission: crate::permissions::Permission,
1103    ) -> Result<()> {
1104        self.framework
1105            .add_role_permission(role_name, permission)
1106            .await
1107    }
1108
1109    /// Assign a role to a user.
1110    pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
1111        self.framework.assign_role(user_id, role_name).await
1112    }
1113
1114    /// Remove a role from a user.
1115    pub async fn remove_role(&self, user_id: &str, role_name: &str) -> Result<()> {
1116        self.framework.remove_role(user_id, role_name).await
1117    }
1118
1119    /// Check whether a user currently has a role.
1120    pub async fn has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
1121        self.framework.user_has_role(user_id, role_name).await
1122    }
1123
1124    /// List effective permissions for a user.
1125    pub async fn effective_permissions(&self, user_id: &str) -> Result<crate::types::Permissions> {
1126        self.framework
1127            .get_effective_permissions(user_id)
1128            .await
1129            .map(crate::types::Permissions)
1130    }
1131
1132    /// List the currently assigned runtime roles for a user.
1133    pub async fn roles_for_user(&self, user_id: &str) -> Result<crate::types::Roles> {
1134        self.framework
1135            .list_user_roles(user_id)
1136            .await
1137            .map(crate::types::Roles)
1138    }
1139}
1140
1141/// Focused maintenance operations exposed via [`AuthFramework::maintenance()`].
1142///
1143/// Backup, restore, and reset authentication state in the configured storage
1144/// backend. All operations support an [`ExecutionMode`] parameter that
1145/// controls whether changes are applied or merely previewed.
1146///
1147/// # Example
1148///
1149/// ```rust,no_run
1150/// # use auth_framework::auth_operations::ExecutionMode;
1151/// # async fn example(auth: &auth_framework::AuthFramework) -> auth_framework::Result<()> {
1152/// let maint = auth.maintenance();
1153///
1154/// // Preview a backup without writing to disk
1155/// let preview = maint.backup("/tmp/auth_backup.json", ExecutionMode::DryRun).await?;
1156/// println!("Would export {} records", preview.manifest.user_count);
1157///
1158/// // Perform the real backup
1159/// let report = maint.backup("/tmp/auth_backup.json", ExecutionMode::Execute).await?;
1160/// # Ok(())
1161/// # }
1162/// ```
1163pub struct MaintenanceOperations<'a> {
1164    pub(crate) framework: &'a AuthFramework,
1165}
1166
1167impl MaintenanceOperations<'_> {
1168    /// Export a logical snapshot to disk.
1169    ///
1170    /// Uses [`ExecutionMode`] for clarity at call sites.
1171    pub async fn backup(&self, output_path: &str, mode: ExecutionMode) -> Result<BackupReport> {
1172        crate::maintenance::backup_to_file(self.framework, output_path, mode.is_dry_run()).await
1173    }
1174
1175    /// Export a logical snapshot to disk (legacy API).
1176    ///
1177    /// Prefer [`backup`](Self::backup) with an [`ExecutionMode`] for
1178    /// self-documenting call sites.
1179    pub async fn backup_to_file(&self, output_path: &str, dry_run: bool) -> Result<BackupReport> {
1180        crate::maintenance::backup_to_file(self.framework, output_path, dry_run).await
1181    }
1182
1183    /// Restore a logical snapshot from disk.
1184    ///
1185    /// Uses [`ExecutionMode`] for clarity at call sites.
1186    pub async fn restore(&self, backup_path: &str, mode: ExecutionMode) -> Result<RestoreReport> {
1187        crate::maintenance::restore_from_file(self.framework, backup_path, mode.is_dry_run()).await
1188    }
1189
1190    /// Restore a logical snapshot from disk (legacy API).
1191    ///
1192    /// Prefer [`restore`](Self::restore) with an [`ExecutionMode`] for
1193    /// self-documenting call sites.
1194    pub async fn restore_from_file(
1195        &self,
1196        backup_path: &str,
1197        dry_run: bool,
1198    ) -> Result<RestoreReport> {
1199        crate::maintenance::restore_from_file(self.framework, backup_path, dry_run).await
1200    }
1201
1202    /// Reset logical authentication state in the configured backend.
1203    ///
1204    /// Uses [`ExecutionMode`] for clarity at call sites.
1205    pub async fn reset_with_mode(&self, mode: ExecutionMode) -> Result<ResetReport> {
1206        crate::maintenance::reset_runtime_data(self.framework, mode.is_dry_run()).await
1207    }
1208
1209    /// Reset logical authentication state in the configured backend (legacy API).
1210    ///
1211    /// Prefer [`reset_with_mode`](Self::reset_with_mode) with an
1212    /// [`ExecutionMode`] for self-documenting call sites.
1213    pub async fn reset(&self, dry_run: bool) -> Result<ResetReport> {
1214        crate::maintenance::reset_runtime_data(self.framework, dry_run).await
1215    }
1216}
1217
1218// ──────────────────────────────────────────────────────────────────────────────
1219// MFA operations
1220// ──────────────────────────────────────────────────────────────────────────────
1221
1222/// Focused multi-factor authentication operations exposed via [`AuthFramework::mfa()`].
1223///
1224/// Covers TOTP, SMS, email challenges, backup codes, and MFA completion
1225/// flows.
1226///
1227/// # Example
1228///
1229/// ```rust,no_run
1230/// # async fn example(auth: &auth_framework::AuthFramework) -> auth_framework::Result<()> {
1231/// let mfa = auth.mfa();
1232///
1233/// // Set up TOTP for a user
1234/// let secret = mfa.generate_totp_secret("user_123").await?;
1235/// let qr_url = mfa.generate_totp_qr_url("user_123", "MyApp", &secret).await?;
1236///
1237/// // Verify a code supplied by the user
1238/// let valid = mfa.verify_totp("user_123", "123456").await?;
1239/// # Ok(())
1240/// # }
1241/// ```
1242pub struct MfaOperations<'a> {
1243    pub(crate) framework: &'a AuthFramework,
1244}
1245
1246impl MfaOperations<'_> {
1247    /// Complete a pending MFA challenge with the provided code.
1248    pub async fn complete(&self, challenge: MfaChallenge, code: &str) -> Result<AuthToken> {
1249        self.framework.complete_mfa(challenge, code).await
1250    }
1251
1252    /// Complete a pending MFA challenge by its ID.
1253    pub async fn complete_by_id(&self, challenge_id: &str, code: &str) -> Result<AuthToken> {
1254        self.framework.complete_mfa_by_id(challenge_id, code).await
1255    }
1256
1257    /// Initiate an SMS-based MFA challenge for a user.
1258    pub async fn initiate_sms(&self, user_id: &str) -> Result<String> {
1259        self.framework.initiate_sms_challenge(user_id).await
1260    }
1261
1262    /// Verify an SMS challenge code.
1263    pub async fn verify_sms(&self, challenge_id: &str, code: &str) -> Result<bool> {
1264        self.framework.verify_sms_code(challenge_id, code).await
1265    }
1266
1267    /// Initiate an email-based MFA challenge for a user.
1268    pub async fn initiate_email(&self, user_id: &str) -> Result<String> {
1269        self.framework.initiate_email_challenge(user_id).await
1270    }
1271
1272    /// Register a phone number for SMS MFA.
1273    pub async fn register_phone(&self, user_id: &str, phone_number: &str) -> Result<()> {
1274        self.framework
1275            .register_phone_number(user_id, phone_number)
1276            .await
1277    }
1278
1279    /// Register an email address for email MFA.
1280    pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
1281        self.framework.register_email(user_id, email).await
1282    }
1283
1284    /// Generate a TOTP secret for a user.
1285    pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
1286        self.framework.generate_totp_secret(user_id).await
1287    }
1288
1289    /// Generate a TOTP QR code provisioning URL.
1290    pub async fn generate_totp_qr_url(
1291        &self,
1292        user_id: &str,
1293        app_name: &str,
1294        secret: &str,
1295    ) -> Result<String> {
1296        self.framework
1297            .generate_totp_qr_code(user_id, app_name, secret)
1298            .await
1299    }
1300
1301    /// Generate the current TOTP code for a secret.
1302    pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
1303        self.framework.generate_totp_code(secret).await
1304    }
1305
1306    /// Verify a TOTP code for a user.
1307    pub async fn verify_totp(&self, user_id: &str, code: &str) -> Result<bool> {
1308        self.framework.verify_totp_code(user_id, code).await
1309    }
1310
1311    /// Generate backup codes for a user.
1312    pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
1313        self.framework.generate_backup_codes(user_id, count).await
1314    }
1315}
1316
1317// ──────────────────────────────────────────────────────────────────────────────
1318// Monitoring operations
1319// ──────────────────────────────────────────────────────────────────────────────
1320
1321/// Focused monitoring and health operations exposed via [`AuthFramework::monitoring()`].
1322///
1323/// Health-checks, performance and security metrics, Prometheus export, and
1324/// rate-limit inspection.
1325///
1326/// # Example
1327///
1328/// ```rust,no_run
1329/// # async fn example(auth: &auth_framework::AuthFramework) -> auth_framework::Result<()> {
1330/// let mon = auth.monitoring();
1331///
1332/// let health = mon.health_check().await?;
1333/// let stats  = mon.stats().await?;
1334/// let prom   = mon.prometheus_metrics().await;
1335/// # Ok(())
1336/// # }
1337/// ```
1338pub struct MonitoringOperations<'a> {
1339    pub(crate) framework: &'a AuthFramework,
1340}
1341
1342impl MonitoringOperations<'_> {
1343    /// Perform a comprehensive health check across all subsystems.
1344    ///
1345    /// Returns a map of subsystem name → health result (e.g. `"storage"`,
1346    /// `"token_manager"`, `"rate_limiter"`).
1347    pub async fn health_check(
1348        &self,
1349    ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
1350        self.framework.health_check().await
1351    }
1352
1353    /// Get current performance metrics.
1354    ///
1355    /// Returns a map of metric name → counter value (e.g.
1356    /// `"auth_requests"`, `"auth_successes"`, `"auth_failures"`).
1357    pub async fn performance_metrics(&self) -> std::collections::HashMap<String, u64> {
1358        self.framework.get_performance_metrics().await
1359    }
1360
1361    /// Get aggregated security metrics.
1362    ///
1363    /// Returns a map of metric name → counter value (e.g.
1364    /// `"brute_force_blocked"`, `"rate_limited_requests"`).
1365    pub async fn security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
1366        self.framework.get_security_metrics().await
1367    }
1368
1369    /// Export metrics in Prometheus text format.
1370    pub async fn prometheus_metrics(&self) -> String {
1371        self.framework.export_prometheus_metrics().await
1372    }
1373
1374    /// Get authentication statistics.
1375    pub async fn stats(&self) -> Result<AuthStats> {
1376        self.framework.get_stats().await
1377    }
1378
1379    /// Check whether an IP address is within the configured rate limit.
1380    pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
1381        self.framework.check_ip_rate_limit(ip).await
1382    }
1383
1384    /// Access the underlying monitoring manager for advanced usage.
1385    pub fn manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
1386        self.framework.monitoring_manager()
1387    }
1388}
1389
1390// ──────────────────────────────────────────────────────────────────────────────
1391// Audit operations
1392// ──────────────────────────────────────────────────────────────────────────────
1393
1394/// Focused audit log operations exposed via [`AuthFramework::audit()`].
1395///
1396/// Query permission audit logs, view permission metrics, and retrieve
1397/// comprehensive security audit statistics.
1398///
1399/// # Example
1400///
1401/// ```rust,no_run
1402/// # async fn example(auth: &auth_framework::AuthFramework) -> auth_framework::Result<()> {
1403/// let audit = auth.audit();
1404///
1405/// // Retrieve recent permission log entries for a specific user
1406/// let logs = audit.permission_logs(Some("user_123"), None, None, Some(50)).await?;
1407///
1408/// // Get security audit statistics
1409/// let stats = audit.security_stats().await?;
1410/// # Ok(())
1411/// # }
1412/// ```
1413pub struct AuditOperations<'a> {
1414    pub(crate) framework: &'a AuthFramework,
1415}
1416
1417impl AuditOperations<'_> {
1418    /// Query permission-related audit log entries using an [`AuditLogQuery`].
1419    ///
1420    /// # Example
1421    ///
1422    /// ```rust,ignore
1423    /// let logs = auth.audit()
1424    ///     .query_permission_logs(
1425    ///         AuditLogQuery::new()
1426    ///             .user("user_123")
1427    ///             .action("read")
1428    ///             .limit(50)
1429    ///     )
1430    ///     .await?;
1431    /// ```
1432    pub async fn query_permission_logs(&self, query: AuditLogQuery) -> Result<Vec<String>> {
1433        self.framework
1434            .get_permission_audit_logs(
1435                query.user_id.as_deref(),
1436                query.action.as_deref(),
1437                query.resource.as_deref(),
1438                query.limit,
1439            )
1440            .await
1441    }
1442
1443    /// Query permission-related audit log entries with optional filters.
1444    ///
1445    /// Prefer [`query_permission_logs`](Self::query_permission_logs) with an
1446    /// [`AuditLogQuery`] for better readability when using multiple filters.
1447    pub async fn permission_logs(
1448        &self,
1449        user_id: Option<&str>,
1450        action: Option<&str>,
1451        resource: Option<&str>,
1452        limit: Option<usize>,
1453    ) -> Result<Vec<String>> {
1454        self.framework
1455            .get_permission_audit_logs(user_id, action, resource, limit)
1456            .await
1457    }
1458
1459    /// Get aggregated permission metrics (role counts, active sessions, checks per hour).
1460    pub async fn permission_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
1461        self.framework.get_permission_metrics().await
1462    }
1463
1464    /// Get comprehensive security audit statistics.
1465    pub async fn security_stats(&self) -> Result<SecurityAuditStats> {
1466        self.framework.get_security_audit_stats().await
1467    }
1468}
1469// ──────────────────────────────────────────────────────────────────────────────
1470// Admin operations
1471// ──────────────────────────────────────────────────────────────────────────────
1472
1473/// Focused advanced administration operations exposed from [`AuthFramework::admin`].
1474///
1475/// These operations go beyond the everyday [`AuthorizationOperations`] surface and cover
1476/// ABAC policy management, permission delegation, role inheritance, resource registration,
1477/// and attribute-based access control.
1478pub struct AdminOperations<'a> {
1479    pub(crate) framework: &'a AuthFramework,
1480}
1481
1482impl AdminOperations<'_> {
1483    /// Define a parent–child role inheritance relationship.
1484    pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
1485        self.framework
1486            .set_role_inheritance(child_role, parent_role)
1487            .await
1488    }
1489
1490    /// Create an ABAC policy.
1491    pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
1492        self.framework.create_abac_policy(name, description).await
1493    }
1494
1495    /// Map a user attribute used in ABAC policy evaluation.
1496    pub async fn map_user_attribute(
1497        &self,
1498        user_id: &str,
1499        attribute: &str,
1500        value: &str,
1501    ) -> Result<()> {
1502        self.framework
1503            .map_user_attribute(user_id, attribute, value)
1504            .await
1505    }
1506
1507    /// Set multiple user attributes in one call.
1508    ///
1509    /// This is a convenience wrapper around [`map_user_attribute`](Self::map_user_attribute)
1510    /// for setting several ABAC attributes at once.
1511    ///
1512    /// # Example
1513    ///
1514    /// ```rust,no_run
1515    /// # use auth_framework::prelude::*;
1516    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
1517    /// auth.admin().set_user_attributes("user-1", &[
1518    ///     ("department", "engineering"),
1519    ///     ("clearance", "top-secret"),
1520    ///     ("location", "us-west-2"),
1521    /// ]).await?;
1522    /// # Ok(())
1523    /// # }
1524    /// ```
1525    pub async fn set_user_attributes(
1526        &self,
1527        user_id: &str,
1528        attributes: &[(&str, &str)],
1529    ) -> Result<()> {
1530        for &(attribute, value) in attributes {
1531            self.framework
1532                .map_user_attribute(user_id, attribute, value)
1533                .await?;
1534        }
1535        Ok(())
1536    }
1537
1538    /// Get a user attribute value.
1539    pub async fn get_user_attribute(
1540        &self,
1541        user_id: &str,
1542        attribute: &str,
1543    ) -> Result<Option<String>> {
1544        self.framework.get_user_attribute(user_id, attribute).await
1545    }
1546
1547    /// Check a permission using dynamic ABAC context evaluation.
1548    ///
1549    /// Prefer [`check_dynamic_permission_with_context`](Self::check_dynamic_permission_with_context)
1550    /// with a [`PermissionContext`] for a more readable API.
1551    pub async fn check_dynamic_permission(
1552        &self,
1553        user_id: &str,
1554        action: &str,
1555        resource: &str,
1556        context: std::collections::HashMap<String, String>,
1557    ) -> Result<bool> {
1558        self.framework
1559            .check_dynamic_permission(user_id, action, resource, context)
1560            .await
1561    }
1562
1563    /// Check a permission using dynamic ABAC context evaluation with a
1564    /// [`PermissionContext`].
1565    ///
1566    /// # Example
1567    ///
1568    /// ```rust,ignore
1569    /// use auth_framework::auth_operations::PermissionContext;
1570    ///
1571    /// let ctx = PermissionContext::new()
1572    ///     .with_attribute("ip_location", "office")
1573    ///     .with_attribute("device_type", "trusted");
1574    ///
1575    /// let allowed = auth.admin()
1576    ///     .check_dynamic_permission_with_context("user_123", "read", "docs", ctx)
1577    ///     .await?;
1578    /// ```
1579    pub async fn check_dynamic_permission_with_context(
1580        &self,
1581        user_id: &str,
1582        action: &str,
1583        resource: &str,
1584        context: PermissionContext,
1585    ) -> Result<bool> {
1586        self.framework
1587            .check_dynamic_permission(user_id, action, resource, context.into_attributes())
1588            .await
1589    }
1590
1591    /// Register a resource in the permission system.
1592    pub async fn create_resource(&self, resource: &str) -> Result<()> {
1593        self.framework.create_resource(resource).await
1594    }
1595
1596    /// Delegate a permission from one user to another using a [`DelegationRequest`].
1597    ///
1598    /// # Example
1599    ///
1600    /// ```rust,ignore
1601    /// auth.admin()
1602    ///     .delegate(
1603    ///         DelegationRequest::new("admin_1", "user_2", "write", "reports")
1604    ///             .duration(Duration::from_secs(3600))
1605    ///     )
1606    ///     .await?;
1607    /// ```
1608    pub async fn delegate(&self, req: DelegationRequest) -> Result<()> {
1609        self.framework
1610            .delegate_permission(
1611                &req.delegator_id,
1612                &req.delegatee_id,
1613                &req.action,
1614                &req.resource,
1615                req.duration,
1616            )
1617            .await
1618    }
1619
1620    /// Delegate a permission from one user to another for a limited duration.
1621    ///
1622    /// Prefer [`delegate`](Self::delegate) with a [`DelegationRequest`] for
1623    /// better readability.
1624    pub async fn delegate_permission(
1625        &self,
1626        delegator_id: &str,
1627        delegatee_id: &str,
1628        action: &str,
1629        resource: &str,
1630        duration: Duration,
1631    ) -> Result<()> {
1632        self.framework
1633            .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
1634            .await
1635    }
1636
1637    /// List currently active permission delegations for a user.
1638    pub async fn active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
1639        self.framework.get_active_delegations(user_id).await
1640    }
1641}
1642#[cfg(test)]
1643mod tests {
1644    use super::*;
1645    use crate::config::AuthConfig;
1646
1647    async fn make_fw() -> AuthFramework {
1648        let config = AuthConfig::new().secret("test_ops_secret_key_32bytes_long!".to_string());
1649        let mut fw = AuthFramework::new(config);
1650        fw.initialize().await.unwrap();
1651        fw
1652    }
1653
1654    // ── UserOperations ──────────────────────────────────────────────────
1655
1656    #[tokio::test]
1657    async fn test_user_ops_register_and_get() {
1658        let fw = make_fw().await;
1659        let uid = fw
1660            .users()
1661            .register("ops_user1", "ops1@test.com", "StrongP@ss1!")
1662            .await
1663            .unwrap();
1664        let info = fw.users().get(&uid).await.unwrap();
1665        assert_eq!(info.username, "ops_user1");
1666    }
1667
1668    #[tokio::test]
1669    async fn test_user_ops_list_empty() {
1670        let fw = make_fw().await;
1671        let list = fw
1672            .users()
1673            .list_with_query(UserListQuery::new().limit(10))
1674            .await
1675            .unwrap();
1676        assert!(list.is_empty());
1677    }
1678
1679    #[tokio::test]
1680    async fn test_user_ops_exists_by_username() {
1681        let fw = make_fw().await;
1682        fw.users()
1683            .register("exists_u", "exists@test.com", "StrongP@ss1!")
1684            .await
1685            .unwrap();
1686        assert!(fw.users().exists_by_username("exists_u").await.unwrap());
1687        assert!(!fw.users().exists_by_username("nope_u").await.unwrap());
1688    }
1689
1690    #[tokio::test]
1691    async fn test_user_ops_exists_by_email() {
1692        let fw = make_fw().await;
1693        fw.users()
1694            .register("email_u", "email_exists@test.com", "StrongP@ss1!")
1695            .await
1696            .unwrap();
1697        assert!(
1698            fw.users()
1699                .exists_by_email("email_exists@test.com")
1700                .await
1701                .unwrap()
1702        );
1703        assert!(!fw.users().exists_by_email("no@test.com").await.unwrap());
1704    }
1705
1706    #[tokio::test]
1707    async fn test_user_ops_profile() {
1708        let fw = make_fw().await;
1709        let uid = fw
1710            .users()
1711            .register("profile_u", "prof@test.com", "StrongP@ss1!")
1712            .await
1713            .unwrap();
1714        let profile = fw.users().profile(&uid).await.unwrap();
1715        assert_eq!(profile.display_name().unwrap_or_default(), "profile_u");
1716    }
1717
1718    #[tokio::test]
1719    async fn test_user_ops_update_password_and_verify() {
1720        let fw = make_fw().await;
1721        let uid = fw
1722            .users()
1723            .register("pw_user", "pw@test.com", "StrongP@ss1!")
1724            .await
1725            .unwrap();
1726        fw.users()
1727            .update_password("pw_user", "NewStr0ng!Pass")
1728            .await
1729            .unwrap();
1730        assert!(
1731            fw.users()
1732                .verify_password(&uid, "NewStr0ng!Pass")
1733                .await
1734                .unwrap()
1735        );
1736    }
1737
1738    #[tokio::test]
1739    async fn test_user_ops_update_email() {
1740        let fw = make_fw().await;
1741        let uid = fw
1742            .users()
1743            .register("email_upd_u", "old@test.com", "StrongP@ss1!")
1744            .await
1745            .unwrap();
1746        fw.users().update_email(&uid, "new@test.com").await.unwrap();
1747        assert!(fw.users().exists_by_email("new@test.com").await.unwrap());
1748    }
1749
1750    #[tokio::test]
1751    async fn test_user_ops_set_active() {
1752        let fw = make_fw().await;
1753        let uid = fw
1754            .users()
1755            .register("act_u", "act@test.com", "StrongP@ss1!")
1756            .await
1757            .unwrap();
1758        fw.users()
1759            .set_status(&uid, UserStatus::Inactive)
1760            .await
1761            .unwrap();
1762        let info = fw.users().get(&uid).await.unwrap();
1763        assert!(!info.active);
1764    }
1765
1766    #[tokio::test]
1767    async fn test_user_ops_delete() {
1768        let fw = make_fw().await;
1769        fw.users()
1770            .register("del_u", "del@test.com", "StrongP@ss1!")
1771            .await
1772            .unwrap();
1773        fw.users().delete("del_u").await.unwrap();
1774        assert!(!fw.users().exists_by_username("del_u").await.unwrap());
1775    }
1776
1777    #[tokio::test]
1778    async fn test_user_ops_username() {
1779        let fw = make_fw().await;
1780        let uid = fw
1781            .users()
1782            .register("name_u", "name@test.com", "StrongP@ss1!")
1783            .await
1784            .unwrap();
1785        let name = fw.users().username(&uid).await.unwrap();
1786        assert_eq!(name, "name_u");
1787    }
1788
1789    // ── SessionOperations ───────────────────────────────────────────────
1790
1791    #[tokio::test]
1792    async fn test_session_ops_create_get_delete() {
1793        let fw = make_fw().await;
1794        let uid = fw
1795            .users()
1796            .register("sess_u", "sess@test.com", "StrongP@ss1!")
1797            .await
1798            .unwrap();
1799        let sid = fw
1800            .sessions()
1801            .create(&uid, Duration::from_secs(3600), None, None)
1802            .await
1803            .unwrap();
1804        let sess = fw.sessions().get(&sid).await.unwrap();
1805        assert!(sess.is_some());
1806        fw.sessions().delete(&sid).await.unwrap();
1807        assert!(fw.sessions().get(&sid).await.unwrap().is_none());
1808    }
1809
1810    #[tokio::test]
1811    async fn test_session_ops_list_for_user() {
1812        let fw = make_fw().await;
1813        let uid = fw
1814            .users()
1815            .register("sl_u", "sl@test.com", "StrongP@ss1!")
1816            .await
1817            .unwrap();
1818        fw.sessions()
1819            .create(&uid, Duration::from_secs(3600), None, None)
1820            .await
1821            .unwrap();
1822        let list = fw.sessions().list_for_user(&uid).await.unwrap();
1823        assert_eq!(list.len(), 1);
1824    }
1825
1826    #[tokio::test]
1827    async fn test_session_ops_cleanup_expired() {
1828        let fw = make_fw().await;
1829        // Should not error even with no sessions
1830        fw.sessions().cleanup_expired().await.unwrap();
1831    }
1832
1833    // ── TokenOperations ─────────────────────────────────────────────────
1834
1835    #[tokio::test]
1836    async fn test_token_ops_create_validate_revoke() {
1837        let fw = make_fw().await;
1838        let uid = fw
1839            .users()
1840            .register("tok_u", "tok@test.com", "StrongP@ss1!")
1841            .await
1842            .unwrap();
1843        // Create API key instead of auth token—no auth method registration needed
1844        let key = fw.tokens().create_api_key(&uid, None).await.unwrap();
1845        let info = fw.tokens().validate_api_key(&key).await.unwrap();
1846        assert!(!info.id.is_empty());
1847        fw.tokens().revoke_api_key(&key).await.unwrap();
1848    }
1849
1850    #[tokio::test]
1851    async fn test_token_ops_api_key_lifecycle() {
1852        let fw = make_fw().await;
1853        let uid = fw
1854            .users()
1855            .register("apikey_u", "apikey@test.com", "StrongP@ss1!")
1856            .await
1857            .unwrap();
1858        let key = fw.tokens().create_api_key(&uid, None).await.unwrap();
1859        let info = fw.tokens().validate_api_key(&key).await.unwrap();
1860        // API key creates an internal user; just verify it resolves
1861        assert!(!info.id.is_empty());
1862        fw.tokens().revoke_api_key(&key).await.unwrap();
1863        assert!(fw.tokens().validate_api_key(&key).await.is_err());
1864    }
1865
1866    // ── AuthorizationOperations ─────────────────────────────────────────
1867
1868    #[tokio::test]
1869    async fn test_authz_ops_grant_and_check() {
1870        let fw = make_fw().await;
1871        let uid = fw
1872            .users()
1873            .register("authz_u", "authz@test.com", "StrongP@ss1!")
1874            .await
1875            .unwrap();
1876        fw.authorization()
1877            .grant(&uid, "read", "docs")
1878            .await
1879            .unwrap();
1880        // Verify via has_role / effective_permissions rather than via token (no auth method registered)
1881        let perms = fw
1882            .authorization()
1883            .effective_permissions(&uid)
1884            .await
1885            .unwrap();
1886        assert!(perms.iter().any(|p| p.contains("read")));
1887    }
1888
1889    #[tokio::test]
1890    async fn test_authz_ops_role_lifecycle() {
1891        let fw = make_fw().await;
1892        let uid = fw
1893            .users()
1894            .register("role_u", "role@test.com", "StrongP@ss1!")
1895            .await
1896            .unwrap();
1897        fw.authorization().assign_role(&uid, "admin").await.unwrap();
1898        assert!(fw.authorization().has_role(&uid, "admin").await.unwrap());
1899        let roles = fw.authorization().roles_for_user(&uid).await.unwrap();
1900        assert!(roles.contains("admin"));
1901        fw.authorization().remove_role(&uid, "admin").await.unwrap();
1902        assert!(!fw.authorization().has_role(&uid, "admin").await.unwrap());
1903    }
1904
1905    // ── MfaOperations ───────────────────────────────────────────────────
1906
1907    #[tokio::test]
1908    async fn test_mfa_ops_totp_lifecycle() {
1909        let fw = make_fw().await;
1910        let uid = fw
1911            .users()
1912            .register("mfa_u", "mfa@test.com", "StrongP@ss1!")
1913            .await
1914            .unwrap();
1915        let secret = fw.mfa().generate_totp_secret(&uid).await.unwrap();
1916        assert!(!secret.is_empty());
1917        let code = fw.mfa().generate_totp_code(&secret).await.unwrap();
1918        assert_eq!(code.len(), 6);
1919        assert!(fw.mfa().verify_totp(&uid, &code).await.unwrap());
1920    }
1921
1922    #[tokio::test]
1923    async fn test_mfa_ops_backup_codes() {
1924        let fw = make_fw().await;
1925        let uid = fw
1926            .users()
1927            .register("bc_u", "bc@test.com", "StrongP@ss1!")
1928            .await
1929            .unwrap();
1930        let codes = fw.mfa().generate_backup_codes(&uid, 5).await.unwrap();
1931        assert_eq!(codes.len(), 5);
1932    }
1933
1934    #[tokio::test]
1935    async fn test_mfa_ops_sms_lifecycle() {
1936        let fw = make_fw().await;
1937        let uid = fw
1938            .users()
1939            .register("smsop_u", "smsop@test.com", "StrongP@ss1!")
1940            .await
1941            .unwrap();
1942        fw.mfa().register_phone(&uid, "+12345678901").await.unwrap();
1943        let cid = fw.mfa().initiate_sms(&uid).await.unwrap();
1944        assert!(!cid.is_empty());
1945    }
1946
1947    #[tokio::test]
1948    async fn test_mfa_ops_email_lifecycle() {
1949        let fw = make_fw().await;
1950        let uid = fw
1951            .users()
1952            .register("emop_u", "emop@test.com", "StrongP@ss1!")
1953            .await
1954            .unwrap();
1955        fw.mfa()
1956            .register_email(&uid, "emop@test.com")
1957            .await
1958            .unwrap();
1959        let cid = fw.mfa().initiate_email(&uid).await.unwrap();
1960        assert!(!cid.is_empty());
1961    }
1962
1963    // ── MonitoringOperations ────────────────────────────────────────────
1964
1965    #[tokio::test]
1966    async fn test_monitoring_ops_health_check() {
1967        let fw = make_fw().await;
1968        let health = fw.monitoring().health_check().await.unwrap();
1969        assert!(!health.is_empty());
1970    }
1971
1972    #[tokio::test]
1973    async fn test_monitoring_ops_performance_metrics() {
1974        let fw = make_fw().await;
1975        let _metrics = fw.monitoring().performance_metrics().await;
1976    }
1977
1978    #[tokio::test]
1979    async fn test_monitoring_ops_stats() {
1980        let fw = make_fw().await;
1981        let stats = fw.monitoring().stats().await.unwrap();
1982        assert_eq!(stats.active_sessions, 0);
1983    }
1984
1985    #[tokio::test]
1986    async fn test_monitoring_ops_prometheus() {
1987        let fw = make_fw().await;
1988        let prom = fw.monitoring().prometheus_metrics().await;
1989        // Just verify it returns valid-looking metrics text
1990        assert!(!prom.is_empty());
1991    }
1992
1993    // ── AdminOperations ─────────────────────────────────────────────────
1994
1995    #[tokio::test]
1996    async fn test_admin_ops_role_inheritance() {
1997        let fw = make_fw().await;
1998        // Default roles include "admin" and "user" — use those
1999        fw.admin()
2000            .set_role_inheritance("user", "admin")
2001            .await
2002            .unwrap();
2003    }
2004
2005    #[tokio::test]
2006    async fn test_admin_ops_abac_policy() {
2007        let fw = make_fw().await;
2008        fw.admin()
2009            .create_abac_policy("ip_allow", "IP allowlist policy")
2010            .await
2011            .unwrap();
2012    }
2013
2014    #[tokio::test]
2015    async fn test_admin_ops_user_attributes() {
2016        let fw = make_fw().await;
2017        let uid = fw
2018            .users()
2019            .register("attr_u", "attr@test.com", "StrongP@ss1!")
2020            .await
2021            .unwrap();
2022        fw.admin()
2023            .map_user_attribute(&uid, "department", "engineering")
2024            .await
2025            .unwrap();
2026        let val = fw
2027            .admin()
2028            .get_user_attribute(&uid, "department")
2029            .await
2030            .unwrap();
2031        assert_eq!(val.as_deref(), Some("engineering"));
2032    }
2033
2034    #[tokio::test]
2035    async fn test_admin_ops_delegation() {
2036        let fw = make_fw().await;
2037        let uid1 = fw
2038            .users()
2039            .register("del_from", "delf@test.com", "StrongP@ss1!")
2040            .await
2041            .unwrap();
2042        let uid2 = fw
2043            .users()
2044            .register("del_to", "delt@test.com", "StrongP@ss1!")
2045            .await
2046            .unwrap();
2047        fw.authorization()
2048            .grant(&uid1, "write", "report")
2049            .await
2050            .unwrap();
2051        fw.admin()
2052            .delegate_permission(&uid1, &uid2, "write", "report", Duration::from_secs(3600))
2053            .await
2054            .unwrap();
2055    }
2056
2057    // ── MaintenanceOperations ───────────────────────────────────────────
2058
2059    #[tokio::test]
2060    async fn test_maintenance_ops_backup_dry_run() {
2061        let fw = make_fw().await;
2062        let report = fw
2063            .maintenance()
2064            .backup_to_file("test_backup.json", true)
2065            .await
2066            .unwrap();
2067        assert!(report.dry_run);
2068    }
2069
2070    #[tokio::test]
2071    async fn test_maintenance_ops_reset_dry_run() {
2072        let fw = make_fw().await;
2073        let report = fw.maintenance().reset(true).await.unwrap();
2074        assert!(report.dry_run);
2075    }
2076
2077    // ── AuditOperations ─────────────────────────────────────────────────
2078
2079    #[tokio::test]
2080    async fn test_audit_ops_permission_logs() {
2081        let fw = make_fw().await;
2082        let logs = fw
2083            .audit()
2084            .permission_logs(None, None, None, Some(10))
2085            .await
2086            .unwrap();
2087        assert!(logs.is_empty()); // no activity yet
2088    }
2089
2090    #[tokio::test]
2091    async fn test_audit_ops_permission_metrics() {
2092        let fw = make_fw().await;
2093        let metrics = fw.audit().permission_metrics().await.unwrap();
2094        assert!(!metrics.is_empty());
2095    }
2096
2097    #[tokio::test]
2098    async fn test_audit_ops_security_stats() {
2099        let fw = make_fw().await;
2100        let stats = fw.audit().security_stats().await.unwrap();
2101        assert_eq!(stats.failed_logins_24h, 0);
2102    }
2103}