garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
Documentation
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Dbnexus Repository 实现。
//!
//! 基于 dbnexus DbPool + sea-orm Statement 参数化查询。
//! 通过 [`make_statement`] 实现 backend-agnostic:传入 `?` 占位符的 SQL,
//! PostgreSQL 后端运行时自动转换为 `$1`, `$2`, ...
//!
//! ## 设计要点
//!
//! - **参数化查询**:所有 WHERE 条件用 `?` 占位符,防 SQL 注入。
//! - **多租户过滤**:有 tenant_id 的表自动注入 `WHERE tenant_id = ?`;`app_permission` 表无 tenant_id(全局表)。
//! - **find_by_\*** 不存在返回 `Ok(None)`;**create** 返回调用方生成的 UUID,不依赖自增 ID;**delete** 幂等,不存在返回 `Ok(())`。
//! - **bool 字段**:SQLite 用 INTEGER 0/1 存储,Row struct 用 bool,读取时 i64→bool 转换;**时间字段**:TEXT 与 `CURRENT_TIMESTAMP` 默认生成同格式,读取为 String。

use crate::error::{GarrisonError, GarrisonResult};
use dbnexus::sea_orm::{QueryResult, Value};
use dbnexus::DbPool;

// 子模块声明(impl 块拆分到独立文件,遵循 mod.rs 加固规则)

mod auth_method_repo;
mod login_log_repo;
mod password_history_repo;
mod permission_repo;
mod role_permission_repo;
mod role_repo;
mod session_repo;
mod user_device_repo;
mod user_ext_repo;
mod user_identifier_repo;
mod user_repo;
mod user_role_repo;
mod webauthn_credential_repo;

// 内部辅助函数

fn v_str(s: &str) -> Value {
    Value::String(Some(s.to_string()))
}

/// 构造可选字符串 Value 参数(None → SQL NULL)。
fn v_opt_str(s: &Option<String>) -> Value {
    Value::String(s.clone())
}

fn v_i64(n: i64) -> Value {
    Value::BigInt(Some(n))
}

fn v_bool(b: bool) -> Value {
    Value::BigInt(Some(if b { 1 } else { 0 }))
}

/// 生成与 SQL `CURRENT_TIMESTAMP` 同格式的当前时间串(`YYYY-MM-DD HH:MM:SS`)。
///
/// 供 UPDATE 语句以参数绑定刷新 `updated_at` 列(TEXT/VARCHAR),三方言
/// (SQLite / PostgreSQL / MySQL)通用,且与 DEFAULT CURRENT_TIMESTAMP 既有值格式一致。
pub(crate) fn now_timestamp() -> String {
    chrono::Utc::now().format("%Y-%m-%d %H:%M:%S").to_string()
}

/// 读取 bool 列(SQLite INTEGER 0/1 → bool)。
///
/// 列缺失 / 类型不符时返回 `GarrisonError::Dao`,**不再静默吞错为 `false`**:
/// schema 漂移(列改名/缺列)时直接显性报错,而非把缺列误读为 `false`
/// 掩盖数据完整性问题。
fn read_bool(row: &QueryResult, col: &str) -> GarrisonResult<bool> {
    row.try_get::<i64>("", col)
        .map(|v| v != 0)
        .map_err(|e| GarrisonError::Dao(format!("dao-repo-read-bool::{}::{}", col, e)))
}

// Repository struct 定义(impl 见各 _repo.rs 子模块)

/// SQLite 用户表 Repository 实现。
pub struct DbnexusUserRepository {
    pool: DbPool,
}

/// SQLite 角色表 Repository 实现。
pub struct DbnexusRoleRepository {
    pool: DbPool,
}

/// SQLite 权限表 Repository 实现(全局表,无 tenant_id)。
pub struct DbnexusPermissionRepository {
    pool: DbPool,
}

/// SQLite 用户-角色关联表 Repository 实现。
pub struct DbnexusUserRoleRepository {
    pool: DbPool,
}

/// SQLite 角色-权限关联表 Repository 实现。
pub struct DbnexusRolePermissionRepository {
    pool: DbPool,
}

/// SQLite 认证方式表 Repository 实现。
pub struct DbnexusAuthMethodRepository {
    pool: DbPool,
}

/// SQLite 会话表 Repository 实现。
pub struct DbnexusSessionRepository {
    pool: DbPool,
}

/// SQLite 登录日志表 Repository 实现。
pub struct DbnexusLoginLogRepository {
    pool: DbPool,
}

/// SQLite 用户扩展字段表 Repository 实现。
pub struct DbnexusUserExtRepository {
    pool: DbPool,
}

/// SQLite 登录标识表 Repository 实现。
pub struct DbnexusUserIdentifierRepository {
    pool: DbPool,
}

/// SQLite 用户设备表 Repository 实现。
///
/// UA 解析当前用简单字符串启发式(提取 Browser/OS 关键字);
/// 完整 `ua-parser` regex 集需启用 `ua-parser-precompiled` feature(设计决策延后)。
pub struct DbnexusUserDeviceRepository {
    pool: DbPool,
}

/// SQLite WebAuthn 凭据表 Repository 实现(app_webauthn_credential)。
pub struct DbnexusWebauthnCredentialRepository {
    pool: DbPool,
}

/// SQLite 密码历史表 Repository 实现(app_password_history)。
pub struct DbnexusPasswordHistoryRepository {
    pool: DbPool,
}

// 测试辅助模块(共享给各 _repo.rs 子模块的 mod tests 使用)

/// 共享测试辅助:初始化内存 SQLite + 执行迁移。
#[cfg(all(test, feature = "db-sqlite"))]
pub(crate) mod test_support {
    use crate::dao::{init_dbnexus, GarrisonMigration};
    use dbnexus::DbPool;
    use std::path::PathBuf;

    /// 定位项目根目录的 migrations/sqlite/ 目录。
    pub fn project_migrations_dir() -> PathBuf {
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        PathBuf::from(manifest_dir)
            .join("migrations")
            .join("sqlite")
    }

    /// 创建并初始化 SQLite 数据库(迁移 + 返回 pool)。
    ///
    /// 默认用唯一临时文件库:内存库在连接池多连接下跨连接不可见(迁移建表与业务
    /// 查询可能落不同连接,偶发 "no such table")。设 `GARRISON_TEST_SQLITE_MEMORY=1`
    /// 回退命名内存库 + shared cache——CI 的 beta/llvm-cov 面文件库触发
    /// SQLITE_READONLY(机制未明、稳定复现),这两面历史上对内存库无跨连接问题。
    pub async fn setup_db() -> DbPool {
        if std::env::var("GARRISON_TEST_SQLITE_MEMORY").as_deref() == Ok("1") {
            // 命名内存库 + shared cache:池内全部连接共享同一库。
            // UUID 命名隔离并发的不同测试二进制(lib / integration)。
            let url = format!(
                "sqlite:file:garrison_test_mem_{}?mode=memory&cache=shared",
                uuid::Uuid::new_v4()
            );
            let pool = init_dbnexus(&url).await.expect("init_dbnexus 应成功");
            let migration =
                GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
            let applied = migration.migrate_core().await.expect("migrate_core 应成功");
            assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
            return pool;
        }
        // 预创建 0 字节文件(sqlite 视为空库):不用 `?mode=rwc` query——
        // 老 sqlx(依赖图早期按低 MSRV 解析选出的版本)会把 query
        // 并入路径解析导致只读打开(attempt to write a readonly database)。
        // nosemgrep: rust.lang.security.temp-dir.temp-dir —— 测试专用临时库文件,UUID v4 随机命名防预测,非安全敏感操作
        let db_path = std::env::temp_dir()
            .join(format!("garrison_test_{}.db", uuid::Uuid::new_v4()))
            .to_string_lossy()
            .replace('\\', "/");
        std::fs::File::create(&db_path).expect("创建测试库文件应成功");
        let url = format!("sqlite://{db_path}");
        let pool = init_dbnexus(&url).await.expect("init_dbnexus 应成功");
        let migration = GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
        let applied = migration.migrate_core().await.expect("migrate_core 应成功");
        assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
        pool
    }
}

#[cfg(all(test, feature = "db-sqlite"))]
mod tests {
    use super::*;
    use crate::dao::repository::*;
    use crate::dao::{init_dbnexus, GarrisonMigration};
    use std::path::PathBuf;

    /// 定位项目根目录的 migrations/sqlite/ 目录。
    fn project_migrations_dir() -> PathBuf {
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        PathBuf::from(manifest_dir)
            .join("migrations")
            .join("sqlite")
    }

    /// 创建并初始化 SQLite 数据库(迁移 + 返回 pool)。
    /// 唯一临时文件库;`GARRISON_TEST_SQLITE_MEMORY=1` 时回退命名内存库
    /// + shared cache(原因见上方 `setup_db` 文档)。
    async fn setup_db() -> DbPool {
        if std::env::var("GARRISON_TEST_SQLITE_MEMORY").as_deref() == Ok("1") {
            // 命名内存库 + shared cache,原因同上方 `setup_db` 注释
            let url = format!(
                "sqlite:file:garrison_test_mem_{}?mode=memory&cache=shared",
                uuid::Uuid::new_v4()
            );
            let pool = init_dbnexus(&url).await.expect("init_dbnexus 应成功");
            let migration =
                GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
            let applied = migration.migrate_core().await.expect("migrate_core 应成功");
            assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
            return pool;
        }
        // 预创建 0 字节文件,URL 不带 query:原因同上方 setup_db 注释
        // nosemgrep: rust.lang.security.temp-dir.temp-dir —— 测试专用临时库文件,UUID v4 随机命名防预测,非安全敏感操作
        let db_path = std::env::temp_dir()
            .join(format!("garrison_test_{}.db", uuid::Uuid::new_v4()))
            .to_string_lossy()
            .replace('\\', "/");
        std::fs::File::create(&db_path).expect("创建测试库文件应成功");
        let url = format!("sqlite://{db_path}");
        let pool = init_dbnexus(&url).await.expect("init_dbnexus 应成功");
        let migration = GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
        let applied = migration.migrate_core().await.expect("migrate_core 应成功");
        assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
        pool
    }

    /// Repository SQL 强制 tenant_id 过滤:跨租户查询返回 None、list 按 tenant 隔离。
    ///
    /// 过滤不门控 `tenant-isolation` feature,始终生效——不过滤会导致跨租户数据泄露(安全优先)。
    #[tokio::test(flavor = "multi_thread")]
    async fn repository_filters_by_tenant_id_when_tenant_isolation_enabled() {
        let pool = setup_db().await;
        let repo = DbnexusUserRepository::new(pool);

        let user_42 = repo
            .create(
                42,
                NewUser {
                    username: "tenant-42-user".to_string(),
                    password_hash: "$argon2id$m=8,t=1,p=1$x".to_string(),
                    status: "active".to_string(),
                },
            )
            .await
            .expect("create tenant 42 用户应成功");

        let user_1 = repo
            .create(
                1,
                NewUser {
                    username: "tenant-1-user".to_string(),
                    password_hash: "$argon2id$m=8,t=1,p=1$x".to_string(),
                    status: "active".to_string(),
                },
            )
            .await
            .expect("create tenant 1 用户应成功");

        let cross = repo.find_by_id(42, &user_1).await.unwrap();
        assert!(
            cross.is_none(),
            "tenant 42 不应查到 tenant 1 的用户(SQL 过滤生效)"
        );

        let cross = repo.find_by_id(1, &user_42).await.unwrap();
        assert!(
            cross.is_none(),
            "tenant 1 不应查到 tenant 42 的用户(SQL 过滤生效)"
        );

        let cross = repo.find_by_username(42, "tenant-1-user").await.unwrap();
        assert!(
            cross.is_none(),
            "tenant 42 不应查到 tenant 1 的 username(SQL 过滤生效)"
        );

        // list 按 tenant 隔离
        let list_42 = repo.list(42, 0, 100).await.unwrap();
        let list_1 = repo.list(1, 0, 100).await.unwrap();
        let ids_42: Vec<_> = list_42.iter().map(|u| u.id.clone()).collect();
        let ids_1: Vec<_> = list_1.iter().map(|u| u.id.clone()).collect();
        assert!(
            ids_42.contains(&user_42) && !ids_42.contains(&user_1),
            "tenant 42 list 应仅含本租户用户"
        );
        assert!(
            ids_1.contains(&user_1) && !ids_1.contains(&user_42),
            "tenant 1 list 应仅含本租户用户"
        );

        let row_42 = repo.find_by_id(42, &user_42).await.unwrap().unwrap();
        assert_eq!(row_42.tenant_id, 42, "返回行 tenant_id 应为 42");
    }

    /// create 内部生成合法 UUID v4(parse_str 成功 + version == Random)。
    #[tokio::test(flavor = "multi_thread")]
    async fn create_generates_valid_uuid_v4() {
        let pool = setup_db().await;
        let repo = DbnexusUserRepository::new(pool);

        let id = repo
            .create(
                42,
                NewUser {
                    username: "uuid-test".to_string(),
                    password_hash: "$argon2id$m=8,t=1,p=1$x".to_string(),
                    status: "active".to_string(),
                },
            )
            .await
            .expect("create 应成功并返回 UUID v4");

        let parsed = uuid::Uuid::parse_str(&id).expect("返回的 id 应为合法 UUID");
        assert_eq!(
            parsed.get_version(),
            Some(uuid::Version::Random),
            "返回的 id 应为 UUID v4,实际: {}",
            id
        );
    }

    /// 同手机号二次注册 → Taken{by_user_id};数据库唯一约束兜底并发。
    #[tokio::test]
    async fn user_identifier_register_conflict_returns_taken() {
        let pool = setup_db().await;
        let repo = DbnexusUserIdentifierRepository::new(pool);

        let first = repo
            .register(0, "phone", "13800001234", "user-aaa")
            .await
            .unwrap();
        assert_eq!(first, RegisterOutcome::Registered);

        // 换 user_id 二次注册同一手机号:唯一约束拒绝 → 回查归属
        let second = repo
            .register(0, "phone", "13800001234", "user-bbb")
            .await
            .unwrap();
        assert_eq!(
            second,
            RegisterOutcome::Taken {
                by_user_id: "user-aaa".to_string()
            }
        );

        let owner = repo.find_owner("phone", "13800001234").await.unwrap();
        assert_eq!(owner.as_deref(), Some("user-aaa"));

        let none = repo.find_owner("phone", "13900000000").await.unwrap();
        assert!(none.is_none());
    }
}