runique 2.2.0

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! User session, admin authentication, and authentication traits.
use crate::admin::permissions::{Groupe, Permission, pull_groupes_db};
use crate::auth::guard::{cache_permissions, evict_permissions, get_permissions};
use crate::auth::user_trait::RuniqueUser;
use crate::context::RequestExtensions;
use crate::middleware::session::session_db::RuniqueSessionStore;
use crate::utils::config::TraceResult;
use crate::utils::constante::{
    admin_key::admin_context::permission::GROUPES,
    session_key::session::{
        SESSION_ACTIVE_KEY, SESSION_USER_ID_KEY, SESSION_USER_IS_STAFF_KEY,
        SESSION_USER_IS_SUPERUSER_KEY, SESSION_USER_USERNAME_KEY,
    },
};
use crate::utils::pk::Pk;
use axum::{extract::Request, middleware::Next, response::Response};
use sea_orm::DatabaseConnection;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
use tower_sessions::Session;

/// Défaut si le builder n'a jamais fixé de durée (24h), pour que `login` ne casse
/// jamais même appelé hors d'un build complet (test, usage bibliothèque).
const DEFAULT_AUTH_SESSION_TTL_SECS: i64 = 86_400;

/// Durée de vie d'une session authentifiée (cookie ET ligne DB), en secondes.
/// Posée **une fois** au build depuis `MiddlewareStaging.session_duration`
/// (builder `.with_session_duration(...)`). Source unique → cookie, ligne
/// `eihwaz_sessions` et rafraîchissement par requête ne peuvent plus diverger.
static AUTH_SESSION_TTL_SECS: std::sync::OnceLock<i64> = std::sync::OnceLock::new();

/// Appelé une fois au build. Idempotent. Un second appel avec une valeur
/// **différente** (deux apps dans le même process) est **loggé**, jamais avalé.
pub fn set_auth_session_ttl_secs(secs: i64) {
    match AUTH_SESSION_TTL_SECS.get() {
        None => {
            if AUTH_SESSION_TTL_SECS.set(secs).is_err() {
                tracing::warn!("auth session TTL set raced at build — keeping the first value");
            }
        }
        Some(&existing) if existing != secs => {
            tracing::warn!(
                existing,
                attempted = secs,
                "auth session TTL already set to a different value (multi-app in one process?) — keeping the first"
            );
        }
        Some(_) => {}
    }
}

/// Résolution pure du TTL (testable sans toucher au global).
fn resolve_ttl_secs(configured: Option<i64>) -> i64 {
    configured.unwrap_or(DEFAULT_AUTH_SESSION_TTL_SECS)
}

/// TTL effectif des sessions authentifiées (builder, sinon défaut).
fn auth_session_ttl_secs() -> i64 {
    resolve_ttl_secs(AUTH_SESSION_TTL_SECS.get().copied())
}

#[cfg(test)]
mod ttl_tests {
    use super::{DEFAULT_AUTH_SESSION_TTL_SECS, resolve_ttl_secs};

    #[test]
    fn ttl_uses_builder_value_else_default() {
        // Builder a fixé une durée → on l'utilise telle quelle (cookie + DB alignés).
        assert_eq!(resolve_ttl_secs(Some(172_800)), 172_800);
        // Builder absent → défaut explicite 24h, jamais 0/panique.
        assert_eq!(resolve_ttl_secs(None), DEFAULT_AUTH_SESSION_TTL_SECS);
        assert_eq!(DEFAULT_AUTH_SESSION_TTL_SECS, 86_400);
    }
}

// ═══════════════════════════════════════════════════════════════
// AdminAuth — trait + result
// ═══════════════════════════════════════════════════════════════

/// Data returned after a successful admin authentication
#[derive(Debug, Clone)]
pub struct AdminLoginResult {
    pub user_id: Pk,
    pub username: String,
    pub is_staff: bool,
    pub is_superuser: bool,
}

/// Trait to implement for plugging in admin login verification
///
/// Returns `None` if:
/// - The user does not exist
/// - The password is incorrect
/// - The account is inactive
/// - The user does not have admin rights
///
/// ## Quick implementation with `DefaultAdminAuth`:
/// ```rust,ignore
/// use runique::auth::DefaultAdminAuth;
///
/// .with_admin(|a| a.auth(DefaultAdminAuth::<users::Entity>::new()))
/// ```
#[async_trait::async_trait]
pub trait AdminAuth: Send + Sync + 'static {
    async fn authenticate(
        &self,
        username: &str,
        password: &str,
        db: &DatabaseConnection,
    ) -> Option<AdminLoginResult>;
}

// ═══════════════════════════════════════════════════════════════
// UserEntity — DB trait
// ═══════════════════════════════════════════════════════════════

/// Database-side trait: how to retrieve a user by username.
///
/// ```rust,ignore
/// impl UserEntity for users::Entity {
///     type Model = users::Model;
///
///     async fn find_by_username(
///         db: &DatabaseConnection,
///         username: &str,
///     ) -> Option<Self::Model> {
///         users::Entity::find()
///             .filter(users::Column::Username.eq(username))
///             .one(db)
///             .await
///             .ok()
///             .flatten()
///     }
/// }
/// ```
#[async_trait::async_trait]
pub trait UserEntity: Send + Sync + 'static {
    /// The model returned by the query (must implement `RuniqueUser`)
    type Model: RuniqueUser;

    /// Searches for a user by id in the database
    async fn find_by_id(db: &DatabaseConnection, id: crate::utils::pk::Pk) -> Option<Self::Model>;
    /// Searches for a user by username in the database
    async fn find_by_username(db: &DatabaseConnection, username: &str) -> Option<Self::Model>;
    /// Searches for a user by email in the database
    async fn find_by_email(db: &DatabaseConnection, email: &str) -> Option<Self::Model>;

    /// Updates the password of a user identified by their email.
    ///
    /// `new_hash` is already hashed (Prisme forms automatically hash password fields).
    async fn update_password(
        db: &DatabaseConnection,
        email: &str,
        new_hash: &str,
    ) -> Result<(), sea_orm::DbErr>;

    /// Updates the password of a user identified by their **primary key**.
    ///
    /// Preferred in flows where the id comes from a secret (e.g. a reset token):
    /// the mutation never depends on an attacker-controlled email/URL field
    /// (IDOR-safe). The default resolves the user by id then delegates to
    /// [`update_password`]; override for a single-query path.
    async fn update_password_by_id(
        db: &DatabaseConnection,
        id: crate::utils::pk::Pk,
        new_hash: &str,
    ) -> Result<(), sea_orm::DbErr> {
        let user = Self::find_by_id(db, id)
            .await
            .ok_or_else(|| sea_orm::DbErr::RecordNotFound("User not found".into()))?;
        Self::update_password(db, user.email(), new_hash).await
    }
}

// ═══════════════════════════════════════════════════════════════
// DefaultAdminAuth<E>
// ═══════════════════════════════════════════════════════════════

/// Generic adapter that transforms any entity implementing `UserEntity` into `AdminAuth`.
pub struct DefaultAdminAuth<E: UserEntity>(PhantomData<E>);

impl<E: UserEntity> DefaultAdminAuth<E> {
    /// Creates a new `DefaultAdminAuth` for the given entity type.
    pub fn new() -> Self {
        Self(PhantomData)
    }
}

impl<E: UserEntity> Default for DefaultAdminAuth<E> {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait::async_trait]
impl<E: UserEntity> AdminAuth for DefaultAdminAuth<E> {
    async fn authenticate(
        &self,
        username: &str,
        password: &str,
        db: &DatabaseConnection,
    ) -> Option<AdminLoginResult> {
        // 1. Retrieve the user from the DB
        let user_opt = E::find_by_username(db, username).await;

        // 2. Always verify password — prevents user enumeration via timing differences.
        // If the user is not found, verify against a dummy hash to burn the same time.
        let hash = user_opt
            .as_ref()
            .map(|u| u.password_hash())
            .unwrap_or(crate::utils::password::dummy_hash());
        let password_ok = crate::utils::password::verify(password, hash);

        // 3. Short-circuit only after verify has run
        let user = user_opt?;

        if !user.can_access_admin() || !password_ok {
            return None;
        }

        // 4. Everything is fine — return the session info
        Some(AdminLoginResult {
            user_id: user.user_id(),
            username: user.username().to_string(),
            is_staff: user.is_staff(),
            is_superuser: user.is_superuser(),
        })
    }
}

// ═══════════════════════════════════════════════════════════════
// CurrentUser
// ═══════════════════════════════════════════════════════════════

/// Authenticated user injected into request extensions.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CurrentUser {
    pub id: Pk,
    pub username: String,
    /// Access to the admin panel (read / limited operations)
    pub is_staff: bool,
    /// Full access — bypasses all admin restrictions
    pub is_superuser: bool,
    /// User groups (each group contains its permissions)
    pub groupes: Vec<Groupe>,
}

impl CurrentUser {
    /// Returns the aggregated permission for a single resource (logical OR across all groups).
    /// Returns `None` if the user has no entry for that resource.
    #[must_use]
    pub fn permission_for(&self, resource_key: &str) -> Option<Permission> {
        self.permissions_effectives()
            .into_iter()
            .find(|p| p.resource_key == resource_key)
    }

    /// Returns the effective CRUD permissions (logical OR across all groups, all resources).
    pub fn permissions_effectives(&self) -> Vec<Permission> {
        let mut agg: std::collections::HashMap<String, Permission> =
            std::collections::HashMap::new();
        for groupe in &self.groupes {
            for perm in &groupe.permissions {
                agg.entry(perm.resource_key.clone())
                    .or_insert_with(|| Permission::zeroed(perm.resource_key.clone()))
                    .merge_from(perm);
            }
        }
        agg.into_values().collect()
    }

    /// Checks if the user has a strict global permission (can be refined).
    #[must_use]
    pub fn can_access_resource(&self, resource_key: &str) -> bool {
        self.is_superuser
            || self
                .permission_for(resource_key)
                .is_some_and(|p| p.can_read)
    }

    /// Checks if the user can access the admin panel.
    #[must_use]
    pub fn can_access_admin(&self) -> bool {
        self.is_staff || self.is_superuser
    }
}

// ═══════════════════════════════════════════════════════════════
// Session helpers
// ═══════════════════════════════════════════════════════════════

async fn session_bool(session: &Session, key: &str) -> bool {
    session
        .get::<bool>(key)
        .await
        .ok()
        .flatten()
        .unwrap_or(false)
}

/// Checks if the user is authenticated.
pub async fn is_authenticated(session: &Session) -> bool {
    session
        .get::<Pk>(SESSION_USER_ID_KEY)
        .await
        .ok()
        .flatten()
        .is_some()
}

/// Checks if the user is authenticated and has admin access.
pub async fn is_admin_authenticated(session: &Session) -> bool {
    is_authenticated(session).await
        && (session_bool(session, SESSION_USER_IS_STAFF_KEY).await
            || session_bool(session, SESSION_USER_IS_SUPERUSER_KEY).await)
}

/// Retrieves the ID of the logged-in user.
pub async fn get_user_id(session: &Session) -> Option<Pk> {
    session.get::<Pk>(SESSION_USER_ID_KEY).await.ok().flatten()
}

/// Retrieves the username of the logged-in user.
pub async fn get_username(session: &Session) -> Option<String> {
    session
        .get::<String>(SESSION_USER_USERNAME_KEY)
        .await
        .ok()
        .flatten()
}

// ═══════════════════════════════════════════════════════════════
// Unified Login
// ═══════════════════════════════════════════════════════════════

/// Logs in a user — loads their rights and groups from the DB.
///
/// If `db_store` is provided, persists the session in DB (multi-device).
/// If `exclusive` is `true`, invalidates other sessions for the user.
///
/// ```rust,ignore
/// login(&session, &db, user.id, &user.username, user.is_staff, user.is_superuser, None, false).await?;
/// ```
#[allow(clippy::too_many_arguments)]
pub async fn login(
    session: &Session,
    db: &DatabaseConnection,
    user_id: Pk,
    username: &str,
    is_staff: bool,
    is_superuser: bool,
    db_store: Option<&RuniqueSessionStore>,
    exclusive: bool,
) -> Result<(), tower_sessions::session::Error> {
    // If another session is already active, perform a clean logout before login
    let existing_id: Option<_> = session.get::<Pk>(SESSION_USER_ID_KEY).await.ok().flatten();
    let is_privilege_elevation = existing_id != Some(user_id);
    if let Some(existing) = existing_id
        && existing != user_id
    {
        logout(session, db_store).await.trace(
            crate::utils::runique_log::get_log()
                .session
                .as_ref()
                .and_then(|s| s.store),
            "pre-login logout of previous session",
        );
    }

    // Rotate the session ID on any privilege elevation (anonymous → auth, or user switch).
    // Prevents session fixation: an attacker who planted a session ID cannot reuse it after login.
    if is_privilege_elevation {
        session.cycle_id().await.trace_or(
            crate::utils::runique_log::get_log()
                .session
                .as_ref()
                .and_then(|s| s.store),
            tracing::Level::WARN,
            "cycle session id (session fixation protection)",
        );
    }

    let groupes = pull_groupes_db(db, user_id).await;

    // Memory cache — single access point for load_user_middleware and point 6 (internal)
    cache_permissions(user_id, groupes.clone());

    if let Some(level) = crate::utils::runique_log::get_log()
        .auth
        .as_ref()
        .and_then(|a| a.login)
    {
        crate::runique_log!(
            level,
            user_id = %user_id,
            username = %username,
            is_superuser,
            exclusive,
            db_persist = db_store.is_some(),
            "login"
        );
    }
    session.insert(SESSION_USER_ID_KEY, user_id).await?;
    session
        .insert(SESSION_USER_USERNAME_KEY, username.to_string())
        .await?;
    session.insert(SESSION_USER_IS_STAFF_KEY, is_staff).await?;
    session
        .insert(SESSION_USER_IS_SUPERUSER_KEY, is_superuser)
        .await?;

    // Promote the session TTL to the authenticated duration on the login request
    // itself, so the first persisted row already carries the long expiry instead of
    // the 5-min anonymous window. The ttl-upgrade middleware only kicks in from the
    // next request; without this, a restart in that first window logs the user out.
    let ttl_secs = auth_session_ttl_secs();
    session.set_expiry(Some(tower_sessions::Expiry::OnInactivity(
        tower_sessions::cookie::time::Duration::seconds(ttl_secs),
    )));

    // DB persistence
    if let Some(store) = db_store {
        // cycle_id() (session fixation protection) invalide l'ID courant et diffère la
        // régénération du nouvel ID au prochain save(). Sans ce save() explicite,
        // session.id() == None ici → cookie_id vide → collision sur la contrainte unique
        // eihwaz_sessions_cookie_id_key dès le 2ᵉ login.
        session.save().await?;

        let Some(cookie_id) = session.id().map(|id| id.to_string()) else {
            crate::runique_log!(
                tracing::Level::WARN,
                user_id = %user_id,
                "session id unavailable after save — skipping DB persistence"
            );
            return Ok(());
        };
        let session_id = uuid::Uuid::new_v4().to_string();
        let expires_at = chrono::Utc::now()
            .naive_utc()
            .checked_add_signed(chrono::Duration::seconds(ttl_secs))
            .unwrap_or_else(|| chrono::Utc::now().naive_utc());

        store
            .create(&cookie_id, user_id, &session_id, expires_at)
            .await
            .trace_or(
                crate::utils::runique_log::get_log()
                    .session
                    .as_ref()
                    .and_then(|s| s.store),
                tracing::Level::WARN,
                "persist session to DB",
            );

        if exclusive {
            store
                .invalidate_other_sessions(user_id, &cookie_id)
                .await
                .trace_or(
                    crate::utils::runique_log::get_log()
                        .session
                        .as_ref()
                        .and_then(|s| s.exclusive_login),
                    tracing::Level::WARN,
                    "invalidate other sessions (exclusive login)",
                );
        }
    }

    Ok(())
}

/// Logs in a user starting only from their `user_id` — loads data from the DB.
///
/// Generic shortcut for any authentication flow (registration, OAuth, magic link...)
/// that already has the user identifier without needing to re-send the fields.
///
/// Returns `Ok(())` without creating a session if the account is inactive (`is_active = false`).
///
/// Uses [`BuiltinUserEntity`] for searching. For a custom model, use [`login`] directly.
pub async fn auth_login(
    session: &Session,
    db: &DatabaseConnection,
    user_id: Pk,
) -> Result<(), tower_sessions::session::Error> {
    let Some(user) = crate::auth::user::BuiltinUserEntity::find_by_id(db, user_id).await else {
        return Ok(());
    };
    if !user.is_active() {
        return Ok(());
    }
    let store = RuniqueSessionStore::new(std::sync::Arc::new(db.clone()));
    login(
        session,
        db,
        user.user_id(),
        user.username(),
        user.is_staff(),
        user.is_superuser(),
        Some(&store),
        false,
    )
    .await
}

/// Logs out a user — removes the memory session and the DB entry if provided.
pub async fn logout(
    session: &Session,
    db_store: Option<&RuniqueSessionStore>,
) -> Result<(), tower_sessions::session::Error> {
    // DB deletion before clearing the session (cookie_id still accessible)
    if let Some(store) = db_store
        && let Some(cookie_id) = session.id().map(|id| id.to_string())
    {
        store.delete(&cookie_id).await.trace(
            crate::utils::runique_log::get_log()
                .session
                .as_ref()
                .and_then(|s| s.store),
            "delete session from DB on logout",
        );
    }

    // Clear permission cache
    if let Some(user_id) = session.get::<Pk>(SESSION_USER_ID_KEY).await.ok().flatten() {
        evict_permissions(user_id);
    }

    session.remove::<Pk>(SESSION_USER_ID_KEY).await?;
    session.remove::<String>(SESSION_USER_USERNAME_KEY).await?;
    session.remove::<bool>(SESSION_USER_IS_STAFF_KEY).await?;
    session
        .remove::<bool>(SESSION_USER_IS_SUPERUSER_KEY)
        .await?;
    session.remove::<Vec<Groupe>>(GROUPES).await?;
    session.remove::<i64>(SESSION_ACTIVE_KEY).await?;
    session.delete().await
}

/// Protects an anonymous session from cleanup.
pub async fn protect_session(
    session: &Session,
    duration_secs: i64,
) -> Result<(), tower_sessions::session::Error> {
    let protect_until = chrono::Utc::now().timestamp().saturating_add(duration_secs);
    session.insert(SESSION_ACTIVE_KEY, protect_until).await
}

/// Removes manual protection from an anonymous session.
pub async fn unprotect_session(session: &Session) -> Result<(), tower_sessions::session::Error> {
    session.remove::<i64>(SESSION_ACTIVE_KEY).await?;
    Ok(())
}

// ═══════════════════════════════════════════════════════════════
// Axum Middlewares
// ═══════════════════════════════════════════════════════════════

/// Middleware: loads user info into the request extensions.
pub async fn load_user_middleware(
    axum::extract::State(db): axum::extract::State<crate::utils::aliases::ADb>,
    session: Session,
    mut request: Request,
    next: Next,
) -> Response {
    if let (Some(user_id), Some(username)) =
        (get_user_id(&session).await, get_username(&session).await)
    {
        let is_staff = session_bool(&session, SESSION_USER_IS_STAFF_KEY).await;
        let is_superuser = session_bool(&session, SESSION_USER_IS_SUPERUSER_KEY).await;

        // Groups from cache — DB reload if cache is empty (after clear_cache).
        // The reload is the moment a rights change becomes visible in this user's
        // context; trace it so that effect is observable (`auth.permissions`).
        let groupes = match get_permissions(user_id) {
            Some(cached) => cached.groupes.clone(),
            None => {
                let groupes = pull_groupes_db(&*db, user_id).await;
                if let Some(level) = crate::utils::runique_log::get_log()
                    .auth
                    .as_ref()
                    .and_then(|a| a.permissions)
                {
                    crate::runique_log!(
                        level,
                        user = %username,
                        groupes = groupes.len(),
                        "permission cache miss — reloaded from DB (context refreshed)"
                    );
                }
                cache_permissions(user_id, groupes.clone());
                groupes
            }
        };

        let current_user = CurrentUser {
            id: user_id,
            username,
            is_staff,
            is_superuser,
            groupes,
        };

        let extensions = RequestExtensions::new().with_current_user(current_user);
        extensions.inject_request(&mut request);
    } else if session.id().is_some() {
        session.delete().await.trace(
            crate::utils::runique_log::get_log()
                .session
                .as_ref()
                .and_then(|s| s.store),
            "delete anonymous session",
        );
    }

    next.run(request).await
}