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    /// 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 the recorded audit events: logins, permission checks and, from the OAuth2
1448    /// endpoints, token introspection and revocation requests.
1449    ///
1450    /// Fails if the configured audit storage cannot be read back (for example
1451    /// `AuditStorage::Tracing`, which is write-only).
1452    pub async fn query_events(
1453        &self,
1454        query: &crate::audit::AuditQuery,
1455    ) -> Result<Vec<crate::audit::AuditEvent>> {
1456        self.framework.query_audit_events(query).await
1457    }
1458
1459    /// Query permission-related audit log entries using an [`AuditLogQuery`].
1460    ///
1461    /// # Example
1462    ///
1463    /// ```rust,ignore
1464    /// let logs = auth.audit()
1465    ///     .query_permission_logs(
1466    ///         AuditLogQuery::new()
1467    ///             .user("user_123")
1468    ///             .action("read")
1469    ///             .limit(50)
1470    ///     )
1471    ///     .await?;
1472    /// ```
1473    pub async fn query_permission_logs(&self, query: AuditLogQuery) -> Result<Vec<String>> {
1474        self.framework
1475            .get_permission_audit_logs(
1476                query.user_id.as_deref(),
1477                query.action.as_deref(),
1478                query.resource.as_deref(),
1479                query.limit,
1480            )
1481            .await
1482    }
1483
1484    /// Query permission-related audit log entries with optional filters.
1485    ///
1486    /// Prefer [`query_permission_logs`](Self::query_permission_logs) with an
1487    /// [`AuditLogQuery`] for better readability when using multiple filters.
1488    pub async fn permission_logs(
1489        &self,
1490        user_id: Option<&str>,
1491        action: Option<&str>,
1492        resource: Option<&str>,
1493        limit: Option<usize>,
1494    ) -> Result<Vec<String>> {
1495        self.framework
1496            .get_permission_audit_logs(user_id, action, resource, limit)
1497            .await
1498    }
1499
1500    /// Get aggregated permission metrics (role counts, active sessions, checks per hour).
1501    pub async fn permission_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
1502        self.framework.get_permission_metrics().await
1503    }
1504
1505    /// Get comprehensive security audit statistics.
1506    pub async fn security_stats(&self) -> Result<SecurityAuditStats> {
1507        self.framework.get_security_audit_stats().await
1508    }
1509}
1510// ──────────────────────────────────────────────────────────────────────────────
1511// Admin operations
1512// ──────────────────────────────────────────────────────────────────────────────
1513
1514/// Focused advanced administration operations exposed from [`AuthFramework::admin`].
1515///
1516/// These operations go beyond the everyday [`AuthorizationOperations`] surface and cover
1517/// ABAC policy management, permission delegation, role inheritance, resource registration,
1518/// and attribute-based access control.
1519pub struct AdminOperations<'a> {
1520    pub(crate) framework: &'a AuthFramework,
1521}
1522
1523impl AdminOperations<'_> {
1524    /// Define a parent–child role inheritance relationship.
1525    pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
1526        self.framework
1527            .set_role_inheritance(child_role, parent_role)
1528            .await
1529    }
1530
1531    /// Create an ABAC policy.
1532    pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
1533        self.framework.create_abac_policy(name, description).await
1534    }
1535
1536    /// Map a user attribute used in ABAC policy evaluation.
1537    pub async fn map_user_attribute(
1538        &self,
1539        user_id: &str,
1540        attribute: &str,
1541        value: &str,
1542    ) -> Result<()> {
1543        self.framework
1544            .map_user_attribute(user_id, attribute, value)
1545            .await
1546    }
1547
1548    /// Set multiple user attributes in one call.
1549    ///
1550    /// This is a convenience wrapper around [`map_user_attribute`](Self::map_user_attribute)
1551    /// for setting several ABAC attributes at once.
1552    ///
1553    /// # Example
1554    ///
1555    /// ```rust,no_run
1556    /// # use auth_framework::prelude::*;
1557    /// # async fn example(auth: &AuthFramework) -> Result<(), AuthError> {
1558    /// auth.admin().set_user_attributes("user-1", &[
1559    ///     ("department", "engineering"),
1560    ///     ("clearance", "top-secret"),
1561    ///     ("location", "us-west-2"),
1562    /// ]).await?;
1563    /// # Ok(())
1564    /// # }
1565    /// ```
1566    pub async fn set_user_attributes(
1567        &self,
1568        user_id: &str,
1569        attributes: &[(&str, &str)],
1570    ) -> Result<()> {
1571        for &(attribute, value) in attributes {
1572            self.framework
1573                .map_user_attribute(user_id, attribute, value)
1574                .await?;
1575        }
1576        Ok(())
1577    }
1578
1579    /// Get a user attribute value.
1580    pub async fn get_user_attribute(
1581        &self,
1582        user_id: &str,
1583        attribute: &str,
1584    ) -> Result<Option<String>> {
1585        self.framework.get_user_attribute(user_id, attribute).await
1586    }
1587
1588    /// Check a permission using dynamic ABAC context evaluation.
1589    ///
1590    /// Prefer [`check_dynamic_permission_with_context`](Self::check_dynamic_permission_with_context)
1591    /// with a [`PermissionContext`] for a more readable API.
1592    pub async fn check_dynamic_permission(
1593        &self,
1594        user_id: &str,
1595        action: &str,
1596        resource: &str,
1597        context: std::collections::HashMap<String, String>,
1598    ) -> Result<bool> {
1599        self.framework
1600            .check_dynamic_permission(user_id, action, resource, context)
1601            .await
1602    }
1603
1604    /// Check a permission using dynamic ABAC context evaluation with a
1605    /// [`PermissionContext`].
1606    ///
1607    /// # Example
1608    ///
1609    /// ```rust,ignore
1610    /// use auth_framework::auth_operations::PermissionContext;
1611    ///
1612    /// let ctx = PermissionContext::new()
1613    ///     .with_attribute("ip_location", "office")
1614    ///     .with_attribute("device_type", "trusted");
1615    ///
1616    /// let allowed = auth.admin()
1617    ///     .check_dynamic_permission_with_context("user_123", "read", "docs", ctx)
1618    ///     .await?;
1619    /// ```
1620    pub async fn check_dynamic_permission_with_context(
1621        &self,
1622        user_id: &str,
1623        action: &str,
1624        resource: &str,
1625        context: PermissionContext,
1626    ) -> Result<bool> {
1627        self.framework
1628            .check_dynamic_permission(user_id, action, resource, context.into_attributes())
1629            .await
1630    }
1631
1632    /// Register a resource in the permission system.
1633    pub async fn create_resource(&self, resource: &str) -> Result<()> {
1634        self.framework.create_resource(resource).await
1635    }
1636
1637    /// Delegate a permission from one user to another using a [`DelegationRequest`].
1638    ///
1639    /// # Example
1640    ///
1641    /// ```rust,ignore
1642    /// auth.admin()
1643    ///     .delegate(
1644    ///         DelegationRequest::new("admin_1", "user_2", "write", "reports")
1645    ///             .duration(Duration::from_secs(3600))
1646    ///     )
1647    ///     .await?;
1648    /// ```
1649    pub async fn delegate(&self, req: DelegationRequest) -> Result<()> {
1650        self.framework
1651            .delegate_permission(
1652                &req.delegator_id,
1653                &req.delegatee_id,
1654                &req.action,
1655                &req.resource,
1656                req.duration,
1657            )
1658            .await
1659    }
1660
1661    /// Delegate a permission from one user to another for a limited duration.
1662    ///
1663    /// Prefer [`delegate`](Self::delegate) with a [`DelegationRequest`] for
1664    /// better readability.
1665    pub async fn delegate_permission(
1666        &self,
1667        delegator_id: &str,
1668        delegatee_id: &str,
1669        action: &str,
1670        resource: &str,
1671        duration: Duration,
1672    ) -> Result<()> {
1673        self.framework
1674            .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
1675            .await
1676    }
1677
1678    /// List currently active permission delegations for a user.
1679    pub async fn active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
1680        self.framework.get_active_delegations(user_id).await
1681    }
1682}
1683#[cfg(test)]
1684mod tests {
1685    use super::*;
1686    use crate::config::AuthConfig;
1687
1688    async fn make_fw() -> AuthFramework {
1689        let config = AuthConfig::new().secret("test_ops_secret_key_32bytes_long!".to_string());
1690        let mut fw = AuthFramework::new(config);
1691        fw.initialize().await.unwrap();
1692        fw
1693    }
1694
1695    // ── UserOperations ──────────────────────────────────────────────────
1696
1697    #[tokio::test]
1698    async fn test_user_ops_register_and_get() {
1699        let fw = make_fw().await;
1700        let uid = fw
1701            .users()
1702            .register("ops_user1", "ops1@test.com", "StrongP@ss1!")
1703            .await
1704            .unwrap();
1705        let info = fw.users().get(&uid).await.unwrap();
1706        assert_eq!(info.username, "ops_user1");
1707    }
1708
1709    #[tokio::test]
1710    async fn test_user_ops_list_empty() {
1711        let fw = make_fw().await;
1712        let list = fw
1713            .users()
1714            .list_with_query(UserListQuery::new().limit(10))
1715            .await
1716            .unwrap();
1717        assert!(list.is_empty());
1718    }
1719
1720    #[tokio::test]
1721    async fn test_user_ops_exists_by_username() {
1722        let fw = make_fw().await;
1723        fw.users()
1724            .register("exists_u", "exists@test.com", "StrongP@ss1!")
1725            .await
1726            .unwrap();
1727        assert!(fw.users().exists_by_username("exists_u").await.unwrap());
1728        assert!(!fw.users().exists_by_username("nope_u").await.unwrap());
1729    }
1730
1731    #[tokio::test]
1732    async fn test_user_ops_exists_by_email() {
1733        let fw = make_fw().await;
1734        fw.users()
1735            .register("email_u", "email_exists@test.com", "StrongP@ss1!")
1736            .await
1737            .unwrap();
1738        assert!(
1739            fw.users()
1740                .exists_by_email("email_exists@test.com")
1741                .await
1742                .unwrap()
1743        );
1744        assert!(!fw.users().exists_by_email("no@test.com").await.unwrap());
1745    }
1746
1747    #[tokio::test]
1748    async fn test_user_ops_profile() {
1749        let fw = make_fw().await;
1750        let uid = fw
1751            .users()
1752            .register("profile_u", "prof@test.com", "StrongP@ss1!")
1753            .await
1754            .unwrap();
1755        let profile = fw.users().profile(&uid).await.unwrap();
1756        assert_eq!(profile.display_name().unwrap_or_default(), "profile_u");
1757    }
1758
1759    #[tokio::test]
1760    async fn test_user_ops_update_password_and_verify() {
1761        let fw = make_fw().await;
1762        let uid = fw
1763            .users()
1764            .register("pw_user", "pw@test.com", "StrongP@ss1!")
1765            .await
1766            .unwrap();
1767        fw.users()
1768            .update_password("pw_user", "NewStr0ng!Pass")
1769            .await
1770            .unwrap();
1771        assert!(
1772            fw.users()
1773                .verify_password(&uid, "NewStr0ng!Pass")
1774                .await
1775                .unwrap()
1776        );
1777    }
1778
1779    #[tokio::test]
1780    async fn test_user_ops_update_email() {
1781        let fw = make_fw().await;
1782        let uid = fw
1783            .users()
1784            .register("email_upd_u", "old@test.com", "StrongP@ss1!")
1785            .await
1786            .unwrap();
1787        fw.users().update_email(&uid, "new@test.com").await.unwrap();
1788        assert!(fw.users().exists_by_email("new@test.com").await.unwrap());
1789    }
1790
1791    #[tokio::test]
1792    async fn test_user_ops_set_active() {
1793        let fw = make_fw().await;
1794        let uid = fw
1795            .users()
1796            .register("act_u", "act@test.com", "StrongP@ss1!")
1797            .await
1798            .unwrap();
1799        fw.users()
1800            .set_status(&uid, UserStatus::Inactive)
1801            .await
1802            .unwrap();
1803        let info = fw.users().get(&uid).await.unwrap();
1804        assert!(!info.active);
1805    }
1806
1807    #[tokio::test]
1808    async fn test_user_ops_delete() {
1809        let fw = make_fw().await;
1810        fw.users()
1811            .register("del_u", "del@test.com", "StrongP@ss1!")
1812            .await
1813            .unwrap();
1814        fw.users().delete("del_u").await.unwrap();
1815        assert!(!fw.users().exists_by_username("del_u").await.unwrap());
1816    }
1817
1818    #[tokio::test]
1819    async fn test_user_ops_username() {
1820        let fw = make_fw().await;
1821        let uid = fw
1822            .users()
1823            .register("name_u", "name@test.com", "StrongP@ss1!")
1824            .await
1825            .unwrap();
1826        let name = fw.users().username(&uid).await.unwrap();
1827        assert_eq!(name, "name_u");
1828    }
1829
1830    // ── SessionOperations ───────────────────────────────────────────────
1831
1832    #[tokio::test]
1833    async fn test_session_ops_create_get_delete() {
1834        let fw = make_fw().await;
1835        let uid = fw
1836            .users()
1837            .register("sess_u", "sess@test.com", "StrongP@ss1!")
1838            .await
1839            .unwrap();
1840        let sid = fw
1841            .sessions()
1842            .create(&uid, Duration::from_secs(3600), None, None)
1843            .await
1844            .unwrap();
1845        let sess = fw.sessions().get(&sid).await.unwrap();
1846        assert!(sess.is_some());
1847        fw.sessions().delete(&sid).await.unwrap();
1848        assert!(fw.sessions().get(&sid).await.unwrap().is_none());
1849    }
1850
1851    #[tokio::test]
1852    async fn test_session_ops_list_for_user() {
1853        let fw = make_fw().await;
1854        let uid = fw
1855            .users()
1856            .register("sl_u", "sl@test.com", "StrongP@ss1!")
1857            .await
1858            .unwrap();
1859        fw.sessions()
1860            .create(&uid, Duration::from_secs(3600), None, None)
1861            .await
1862            .unwrap();
1863        let list = fw.sessions().list_for_user(&uid).await.unwrap();
1864        assert_eq!(list.len(), 1);
1865    }
1866
1867    #[tokio::test]
1868    async fn test_session_ops_cleanup_expired() {
1869        let fw = make_fw().await;
1870        // Should not error even with no sessions
1871        fw.sessions().cleanup_expired().await.unwrap();
1872    }
1873
1874    // ── TokenOperations ─────────────────────────────────────────────────
1875
1876    #[tokio::test]
1877    async fn test_token_ops_create_validate_revoke() {
1878        let fw = make_fw().await;
1879        let uid = fw
1880            .users()
1881            .register("tok_u", "tok@test.com", "StrongP@ss1!")
1882            .await
1883            .unwrap();
1884        // Create API key instead of auth token—no auth method registration needed
1885        let key = fw.tokens().create_api_key(&uid, None).await.unwrap();
1886        let info = fw.tokens().validate_api_key(&key).await.unwrap();
1887        assert!(!info.id.is_empty());
1888        fw.tokens().revoke_api_key(&key).await.unwrap();
1889    }
1890
1891    #[tokio::test]
1892    async fn test_token_ops_api_key_lifecycle() {
1893        let fw = make_fw().await;
1894        let uid = fw
1895            .users()
1896            .register("apikey_u", "apikey@test.com", "StrongP@ss1!")
1897            .await
1898            .unwrap();
1899        let key = fw.tokens().create_api_key(&uid, None).await.unwrap();
1900        let info = fw.tokens().validate_api_key(&key).await.unwrap();
1901        // API key creates an internal user; just verify it resolves
1902        assert!(!info.id.is_empty());
1903        fw.tokens().revoke_api_key(&key).await.unwrap();
1904        assert!(fw.tokens().validate_api_key(&key).await.is_err());
1905    }
1906
1907    // ── AuthorizationOperations ─────────────────────────────────────────
1908
1909    #[tokio::test]
1910    async fn test_authz_ops_grant_and_check() {
1911        let fw = make_fw().await;
1912        let uid = fw
1913            .users()
1914            .register("authz_u", "authz@test.com", "StrongP@ss1!")
1915            .await
1916            .unwrap();
1917        fw.authorization()
1918            .grant(&uid, "read", "docs")
1919            .await
1920            .unwrap();
1921        // Verify via has_role / effective_permissions rather than via token (no auth method registered)
1922        let perms = fw
1923            .authorization()
1924            .effective_permissions(&uid)
1925            .await
1926            .unwrap();
1927        assert!(perms.iter().any(|p| p.contains("read")));
1928    }
1929
1930    #[tokio::test]
1931    async fn test_authz_ops_role_lifecycle() {
1932        let fw = make_fw().await;
1933        let uid = fw
1934            .users()
1935            .register("role_u", "role@test.com", "StrongP@ss1!")
1936            .await
1937            .unwrap();
1938        fw.authorization().assign_role(&uid, "admin").await.unwrap();
1939        assert!(fw.authorization().has_role(&uid, "admin").await.unwrap());
1940        let roles = fw.authorization().roles_for_user(&uid).await.unwrap();
1941        assert!(roles.contains("admin"));
1942        fw.authorization().remove_role(&uid, "admin").await.unwrap();
1943        assert!(!fw.authorization().has_role(&uid, "admin").await.unwrap());
1944    }
1945
1946    // ── MfaOperations ───────────────────────────────────────────────────
1947
1948    #[tokio::test]
1949    async fn test_mfa_ops_totp_lifecycle() {
1950        let fw = make_fw().await;
1951        let uid = fw
1952            .users()
1953            .register("mfa_u", "mfa@test.com", "StrongP@ss1!")
1954            .await
1955            .unwrap();
1956        let secret = fw.mfa().generate_totp_secret(&uid).await.unwrap();
1957        assert!(!secret.is_empty());
1958        let code = fw.mfa().generate_totp_code(&secret).await.unwrap();
1959        assert_eq!(code.len(), 6);
1960        assert!(fw.mfa().verify_totp(&uid, &code).await.unwrap());
1961    }
1962
1963    #[tokio::test]
1964    async fn test_mfa_ops_backup_codes() {
1965        let fw = make_fw().await;
1966        let uid = fw
1967            .users()
1968            .register("bc_u", "bc@test.com", "StrongP@ss1!")
1969            .await
1970            .unwrap();
1971        let codes = fw.mfa().generate_backup_codes(&uid, 5).await.unwrap();
1972        assert_eq!(codes.len(), 5);
1973    }
1974
1975    #[tokio::test]
1976    async fn test_mfa_ops_sms_lifecycle() {
1977        let fw = make_fw().await;
1978        let uid = fw
1979            .users()
1980            .register("smsop_u", "smsop@test.com", "StrongP@ss1!")
1981            .await
1982            .unwrap();
1983        fw.mfa().register_phone(&uid, "+12345678901").await.unwrap();
1984        let cid = fw.mfa().initiate_sms(&uid).await.unwrap();
1985        assert!(!cid.is_empty());
1986    }
1987
1988    #[tokio::test]
1989    async fn test_mfa_ops_email_lifecycle() {
1990        let fw = make_fw().await;
1991        let uid = fw
1992            .users()
1993            .register("emop_u", "emop@test.com", "StrongP@ss1!")
1994            .await
1995            .unwrap();
1996        fw.mfa()
1997            .register_email(&uid, "emop@test.com")
1998            .await
1999            .unwrap();
2000        let cid = fw.mfa().initiate_email(&uid).await.unwrap();
2001        assert!(!cid.is_empty());
2002    }
2003
2004    // ── MonitoringOperations ────────────────────────────────────────────
2005
2006    #[tokio::test]
2007    async fn test_monitoring_ops_health_check() {
2008        let fw = make_fw().await;
2009        let health = fw.monitoring().health_check().await.unwrap();
2010        assert!(!health.is_empty());
2011    }
2012
2013    #[tokio::test]
2014    async fn test_monitoring_ops_performance_metrics() {
2015        let fw = make_fw().await;
2016        let _metrics = fw.monitoring().performance_metrics().await;
2017    }
2018
2019    #[tokio::test]
2020    async fn test_monitoring_ops_stats() {
2021        let fw = make_fw().await;
2022        let stats = fw.monitoring().stats().await.unwrap();
2023        assert_eq!(stats.active_sessions, 0);
2024    }
2025
2026    #[tokio::test]
2027    async fn test_monitoring_ops_prometheus() {
2028        let fw = make_fw().await;
2029        let prom = fw.monitoring().prometheus_metrics().await;
2030        // Just verify it returns valid-looking metrics text
2031        assert!(!prom.is_empty());
2032    }
2033
2034    // ── AdminOperations ─────────────────────────────────────────────────
2035
2036    #[tokio::test]
2037    async fn test_admin_ops_role_inheritance() {
2038        let fw = make_fw().await;
2039        // Default roles include "admin" and "user" — use those
2040        fw.admin()
2041            .set_role_inheritance("user", "admin")
2042            .await
2043            .unwrap();
2044    }
2045
2046    #[tokio::test]
2047    async fn test_admin_ops_abac_policy() {
2048        let fw = make_fw().await;
2049        fw.admin()
2050            .create_abac_policy("ip_allow", "IP allowlist policy")
2051            .await
2052            .unwrap();
2053    }
2054
2055    #[tokio::test]
2056    async fn test_admin_ops_user_attributes() {
2057        let fw = make_fw().await;
2058        let uid = fw
2059            .users()
2060            .register("attr_u", "attr@test.com", "StrongP@ss1!")
2061            .await
2062            .unwrap();
2063        fw.admin()
2064            .map_user_attribute(&uid, "department", "engineering")
2065            .await
2066            .unwrap();
2067        let val = fw
2068            .admin()
2069            .get_user_attribute(&uid, "department")
2070            .await
2071            .unwrap();
2072        assert_eq!(val.as_deref(), Some("engineering"));
2073    }
2074
2075    #[tokio::test]
2076    async fn test_admin_ops_delegation() {
2077        let fw = make_fw().await;
2078        let uid1 = fw
2079            .users()
2080            .register("del_from", "delf@test.com", "StrongP@ss1!")
2081            .await
2082            .unwrap();
2083        let uid2 = fw
2084            .users()
2085            .register("del_to", "delt@test.com", "StrongP@ss1!")
2086            .await
2087            .unwrap();
2088        fw.authorization()
2089            .grant(&uid1, "write", "report")
2090            .await
2091            .unwrap();
2092        fw.admin()
2093            .delegate_permission(&uid1, &uid2, "write", "report", Duration::from_secs(3600))
2094            .await
2095            .unwrap();
2096    }
2097
2098    // ── MaintenanceOperations ───────────────────────────────────────────
2099
2100    #[tokio::test]
2101    async fn test_maintenance_ops_backup_dry_run() {
2102        let fw = make_fw().await;
2103        let report = fw
2104            .maintenance()
2105            .backup_to_file("test_backup.json", true)
2106            .await
2107            .unwrap();
2108        assert!(report.dry_run);
2109    }
2110
2111    #[tokio::test]
2112    async fn test_maintenance_ops_reset_dry_run() {
2113        let fw = make_fw().await;
2114        let report = fw.maintenance().reset(true).await.unwrap();
2115        assert!(report.dry_run);
2116    }
2117
2118    // ── AuditOperations ─────────────────────────────────────────────────
2119
2120    #[tokio::test]
2121    async fn test_audit_ops_permission_logs() {
2122        let fw = make_fw().await;
2123        let logs = fw
2124            .audit()
2125            .permission_logs(None, None, None, Some(10))
2126            .await
2127            .unwrap();
2128        assert!(logs.is_empty()); // no activity yet
2129    }
2130
2131    #[tokio::test]
2132    async fn test_audit_ops_permission_metrics() {
2133        let fw = make_fw().await;
2134        let metrics = fw.audit().permission_metrics().await.unwrap();
2135        assert!(!metrics.is_empty());
2136    }
2137
2138    #[tokio::test]
2139    async fn test_audit_ops_security_stats() {
2140        let fw = make_fw().await;
2141        let stats = fw.audit().security_stats().await.unwrap();
2142        assert_eq!(stats.failed_logins_24h, 0);
2143    }
2144}