garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! DbnexusRoleRepository 实现(app_role 表)。

use super::{now_timestamp, read_bool, v_bool, v_i64, v_opt_str, v_str, DbnexusRoleRepository};
use crate::dao::dao_session;
use crate::dao::repository::{make_statement, NewRole, RoleRepository, RoleRow};
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use dbnexus::sea_orm::{ConnectionTrait, QueryResult};
use dbnexus::DbPool;

impl DbnexusRoleRepository {
    /// 创建实例。
    pub fn new(pool: DbPool) -> Self {
        Self { pool }
    }
}

#[async_trait]
impl RoleRepository for DbnexusRoleRepository {
    async fn find_by_id(&self, tenant_id: i64, id: &str) -> GarrisonResult<Option<RoleRow>> {
        dao_session!(self.pool, "dao-app-role-find-by-id", session, conn);
        let sql =
            "SELECT id, code, name, description, tenant_id, is_system, created_at, updated_at \
                   FROM app_role WHERE tenant_id = ? AND id = ?";
        let stmt = make_statement(conn, sql, vec![v_i64(tenant_id), v_str(id)]);
        let row = conn
            .query_one_raw(stmt)
            .await
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-find-by-id-query::{}", e)))?;
        row.map(|r| parse_role_row(&r)).transpose()
    }

    async fn find_by_code(&self, tenant_id: i64, code: &str) -> GarrisonResult<Option<RoleRow>> {
        dao_session!(self.pool, "dao-app-role-find-by-code", session, conn);
        let sql =
            "SELECT id, code, name, description, tenant_id, is_system, created_at, updated_at \
                   FROM app_role WHERE tenant_id = ? AND code = ?";
        let stmt = make_statement(conn, sql, vec![v_i64(tenant_id), v_str(code)]);
        let row = conn
            .query_one_raw(stmt)
            .await
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-find-by-code-query::{}", e)))?;
        row.map(|r| parse_role_row(&r)).transpose()
    }

    async fn create(&self, tenant_id: i64, role: NewRole) -> GarrisonResult<String> {
        let id = uuid::Uuid::new_v4().to_string();
        dao_session!(self.pool, "dao-app-role-create", session, conn);
        let sql = "INSERT INTO app_role (id, code, name, description, tenant_id, is_system) \
                   VALUES (?, ?, ?, ?, ?, ?)";
        let stmt = make_statement(
            conn,
            sql,
            vec![
                v_str(&id),
                v_str(&role.code),
                v_str(&role.name),
                v_opt_str(&role.description),
                v_i64(tenant_id),
                v_bool(role.is_system),
            ],
        );
        conn.execute_raw(stmt)
            .await
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-create-insert::{}", e)))?;
        Ok(id)
    }

    async fn update(
        &self,
        tenant_id: i64,
        id: &str,
        code: Option<String>,
        name: Option<String>,
        description: Option<String>,
    ) -> GarrisonResult<()> {
        let mut sets = Vec::new();
        let mut params = Vec::new();
        if let Some(code) = code {
            sets.push("code = ?");
            params.push(v_str(&code));
        }
        if let Some(name) = name {
            sets.push("name = ?");
            params.push(v_str(&name));
        }
        if let Some(description) = description {
            sets.push("description = ?");
            params.push(v_str(&description));
        }
        if sets.is_empty() {
            return Ok(());
        }
        // updated_at 随每次成功 UPDATE 刷新(CURRENT_TIMESTAMP 同款格式,以字符串参数绑定写入 TEXT/VARCHAR,三方言通用)
        sets.push("updated_at = ?");
        params.push(v_str(&now_timestamp()));
        params.push(v_i64(tenant_id));
        params.push(v_str(id));
        let sql = format!(
            "UPDATE app_role SET {} WHERE tenant_id = ? AND id = ?",
            sets.join(", ")
        );
        dao_session!(self.pool, "dao-app-role-update", session, conn);
        let stmt = make_statement(conn, &sql, params);
        conn.execute_raw(stmt)
            .await
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-update-update::{}", e)))?;
        Ok(())
    }

    async fn delete(&self, tenant_id: i64, id: &str) -> GarrisonResult<()> {
        dao_session!(self.pool, "dao-app-role-delete", session, conn);
        let sql = "DELETE FROM app_role WHERE tenant_id = ? AND id = ?";
        let stmt = make_statement(conn, sql, vec![v_i64(tenant_id), v_str(id)]);
        conn.execute_raw(stmt)
            .await
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-delete-delete::{}", e)))?;
        Ok(())
    }

    async fn list(&self, tenant_id: i64, offset: i64, limit: i64) -> GarrisonResult<Vec<RoleRow>> {
        dao_session!(self.pool, "dao-app-role-list", session, conn);
        // ORDER BY id:LIMIT/OFFSET 分页需要稳定排序,否则并发变更下可能重行/漏行
        let sql =
            "SELECT id, code, name, description, tenant_id, is_system, created_at, updated_at \
                   FROM app_role WHERE tenant_id = ? ORDER BY id LIMIT ? OFFSET ?";
        let stmt = make_statement(
            conn,
            sql,
            vec![v_i64(tenant_id), v_i64(limit), v_i64(offset)],
        );
        let rows = conn
            .query_all_raw(stmt)
            .await
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-list-query::{}", e)))?;
        rows.iter().map(parse_role_row).collect()
    }
}

/// 解析 app_role 行。
fn parse_role_row(row: &QueryResult) -> GarrisonResult<RoleRow> {
    Ok(RoleRow {
        id: row
            .try_get("", "id")
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-row-parse-id::{}", e)))?,
        code: row
            .try_get("", "code")
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-row-parse-code::{}", e)))?,
        name: row
            .try_get("", "name")
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-row-parse-name::{}", e)))?,
        description: row.try_get("", "description").map_err(|e| {
            GarrisonError::Dao(format!("dao-app-role-row-parse-description::{}", e))
        })?,
        tenant_id: row
            .try_get("", "tenant_id")
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-row-parse-tenant-id::{}", e)))?,
        is_system: read_bool(row, "is_system")?,
        created_at: row
            .try_get("", "created_at")
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-row-parse-created-at::{}", e)))?,
        updated_at: row
            .try_get("", "updated_at")
            .map_err(|e| GarrisonError::Dao(format!("dao-app-role-row-parse-updated-at::{}", e)))?,
    })
}

#[cfg(all(test, feature = "db-sqlite"))]
mod tests {
    use super::*;
    use crate::dao::repository::sqlite::test_support::setup_db;

    /// create 插入角色后 find_by_id 应返回相同字段(含 is_system/description)。
    #[tokio::test(flavor = "multi_thread")]
    async fn create_and_find_by_id_roundtrip() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let id = repo
            .create(
                1,
                NewRole {
                    code: "admin".to_string(),
                    name: "管理员".to_string(),
                    description: Some("系统管理员".to_string()),
                    is_system: true,
                },
            )
            .await
            .expect("create 应成功");

        let row = repo
            .find_by_id(1, &id)
            .await
            .expect("find_by_id 应成功")
            .expect("角色应存在");
        assert_eq!(row.id, id);
        assert_eq!(row.code, "admin");
        assert_eq!(row.name, "管理员");
        assert_eq!(row.description.as_deref(), Some("系统管理员"));
        assert_eq!(row.tenant_id, 1);
        assert!(row.is_system, "is_system 应为 true");
    }

    /// find_by_id 查询不存在的 ID 应返回 None。
    #[tokio::test(flavor = "multi_thread")]
    async fn find_by_id_returns_none_for_nonexistent() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let result = repo
            .find_by_id(1, "nonexistent-uuid")
            .await
            .expect("find_by_id 应成功");
        assert!(result.is_none(), "不存在的 ID 应返回 None");
    }

    /// find_by_code 按 code 精确查询。
    #[tokio::test(flavor = "multi_thread")]
    async fn find_by_code_returns_role() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        repo.create(
            1,
            NewRole {
                code: "editor".to_string(),
                name: "编辑".to_string(),
                description: None,
                is_system: false,
            },
        )
        .await
        .expect("create 应成功");

        let row = repo
            .find_by_code(1, "editor")
            .await
            .expect("find_by_code 应成功")
            .expect("角色应存在");
        assert_eq!(row.code, "editor");
        assert_eq!(row.name, "编辑");
        assert!(row.description.is_none());
        assert!(!row.is_system);
    }

    /// find_by_code 查询不存在的 code 应返回 None。
    #[tokio::test(flavor = "multi_thread")]
    async fn find_by_code_returns_none_for_nonexistent() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let result = repo
            .find_by_code(1, "nonexistent-code")
            .await
            .expect("find_by_code 应成功");
        assert!(result.is_none(), "不存在的 code 应返回 None");
    }

    /// update 更新 code/name/description 后查询应反映新值;全 None 时不更新。
    #[tokio::test(flavor = "multi_thread")]
    async fn update_changes_fields_and_noop_when_all_none() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let id = repo
            .create(
                1,
                NewRole {
                    code: "old-code".to_string(),
                    name: "旧名".to_string(),
                    description: Some("旧描述".to_string()),
                    is_system: false,
                },
            )
            .await
            .expect("create 应成功");

        // 全 None 时应直接返回 Ok(()) 不执行 SQL
        repo.update(1, &id, None, None, None)
            .await
            .expect("全 None update 应为 no-op");

        // 更新所有字段
        repo.update(
            1,
            &id,
            Some("new-code".to_string()),
            Some("新名".to_string()),
            Some("新描述".to_string()),
        )
        .await
        .expect("update 应成功");

        let row = repo
            .find_by_id(1, &id)
            .await
            .expect("find_by_id 应成功")
            .expect("角色应存在");
        assert_eq!(row.code, "new-code");
        assert_eq!(row.name, "新名");
        assert_eq!(row.description.as_deref(), Some("新描述"));
    }

    /// update 仅更新部分字段(仅 name)。
    #[tokio::test(flavor = "multi_thread")]
    async fn update_partial_only_name() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let id = repo
            .create(
                1,
                NewRole {
                    code: "partial".to_string(),
                    name: "原名".to_string(),
                    description: Some("保留描述".to_string()),
                    is_system: false,
                },
            )
            .await
            .expect("create 应成功");

        repo.update(1, &id, None, Some("新名".to_string()), None)
            .await
            .expect("update 应成功");

        let row = repo
            .find_by_id(1, &id)
            .await
            .expect("find_by_id 应成功")
            .expect("角色应存在");
        assert_eq!(row.name, "新名");
        assert_eq!(row.code, "partial", "code 不应变");
        assert_eq!(
            row.description.as_deref(),
            Some("保留描述"),
            "description 不应变"
        );
    }

    /// update 应刷新 updated_at(不再保留 create 时的旧值)。
    #[tokio::test(flavor = "multi_thread")]
    async fn update_refreshes_updated_at() {
        use std::time::Duration;
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let id = repo
            .create(
                1,
                NewRole {
                    code: "ts-role".to_string(),
                    name: "旧名".to_string(),
                    description: None,
                    is_system: false,
                },
            )
            .await
            .expect("create 应成功");

        // created_at 与 updated_at 均为秒级时间戳,间隔 2s 保证可区分
        tokio::time::sleep(Duration::from_secs(2)).await;
        repo.update(1, &id, None, Some("新名".to_string()), None)
            .await
            .expect("update 应成功");

        let row = repo
            .find_by_id(1, &id)
            .await
            .expect("find_by_id 应成功")
            .expect("角色应存在");
        assert!(
            row.updated_at > row.created_at,
            "update 后 updated_at 应刷新({} 应晚于 {})",
            row.updated_at,
            row.created_at
        );
    }

    /// update 仅更新 description(含设为 None 的场景用空字符串替代)。
    #[tokio::test(flavor = "multi_thread")]
    async fn update_partial_only_description() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let id = repo
            .create(
                1,
                NewRole {
                    code: "desc-role".to_string(),
                    name: "名".to_string(),
                    description: None,
                    is_system: false,
                },
            )
            .await
            .expect("create 应成功");

        repo.update(1, &id, None, None, Some("新增描述".to_string()))
            .await
            .expect("update 应成功");

        let row = repo
            .find_by_id(1, &id)
            .await
            .expect("find_by_id 应成功")
            .expect("角色应存在");
        assert_eq!(row.description.as_deref(), Some("新增描述"));
    }

    /// delete 删除后 find_by_id 返回 None;重复删除不报错(幂等)。
    #[tokio::test(flavor = "multi_thread")]
    async fn delete_is_idempotent() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let id = repo
            .create(
                1,
                NewRole {
                    code: "temp-role".to_string(),
                    name: "临时".to_string(),
                    description: None,
                    is_system: false,
                },
            )
            .await
            .expect("create 应成功");

        repo.delete(1, &id).await.expect("首次 delete 应成功");
        let after = repo.find_by_id(1, &id).await.expect("find_by_id 应成功");
        assert!(after.is_none(), "删除后应查不到");

        // 幂等:再次删除
        repo.delete(1, &id).await.expect("幂等 delete 应成功");
    }

    /// list 分页查询:插入 3 条记录后 offset/limit 正确分页。
    #[tokio::test(flavor = "multi_thread")]
    async fn list_paginates_correctly() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        for i in 0..3 {
            repo.create(
                1,
                NewRole {
                    code: format!("role-{}", i),
                    name: format!("角色{}", i),
                    description: None,
                    is_system: false,
                },
            )
            .await
            .expect("create 应成功");
        }

        let all = repo.list(1, 0, 100).await.expect("list 应成功");
        assert_eq!(all.len(), 3, "应有 3 条记录");

        let page = repo.list(1, 1, 1).await.expect("list 分页应成功");
        assert_eq!(page.len(), 1, "分页应返回 1 条");

        let empty = repo.list(1, 100, 10).await.expect("list 超范围应成功");
        assert!(empty.is_empty(), "超出范围的 offset 应返回空");
    }

    /// list 按 tenant_id 隔离。
    #[tokio::test(flavor = "multi_thread")]
    async fn list_filters_by_tenant_id() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        repo.create(
            1,
            NewRole {
                code: "t1-role".to_string(),
                name: "租户1角色".to_string(),
                description: None,
                is_system: false,
            },
        )
        .await
        .expect("create tenant 1 应成功");

        repo.create(
            2,
            NewRole {
                code: "t2-role".to_string(),
                name: "租户2角色".to_string(),
                description: None,
                is_system: false,
            },
        )
        .await
        .expect("create tenant 2 应成功");

        let list_1 = repo.list(1, 0, 100).await.expect("list tenant 1 应成功");
        let list_2 = repo.list(2, 0, 100).await.expect("list tenant 2 应成功");
        assert_eq!(list_1.len(), 1, "tenant 1 应有 1 条");
        assert_eq!(list_2.len(), 1, "tenant 2 应有 1 条");
        assert_eq!(list_1[0].tenant_id, 1);
        assert_eq!(list_2[0].tenant_id, 2);
    }

    /// find_by_id 跨租户查询应返回 None。
    #[tokio::test(flavor = "multi_thread")]
    async fn find_by_id_cross_tenant_returns_none() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let id = repo
            .create(
                1,
                NewRole {
                    code: "cross-role".to_string(),
                    name: "跨租户".to_string(),
                    description: None,
                    is_system: false,
                },
            )
            .await
            .expect("create 应成功");

        let cross = repo.find_by_id(2, &id).await.expect("find_by_id 应成功");
        assert!(cross.is_none(), "跨租户查询应返回 None");
    }

    /// create 生成合法 UUID v4。
    #[tokio::test(flavor = "multi_thread")]
    async fn create_generates_valid_uuid_v4() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let id = repo
            .create(
                1,
                NewRole {
                    code: "uuid-role".to_string(),
                    name: "UUID测试".to_string(),
                    description: None,
                    is_system: false,
                },
            )
            .await
            .expect("create 应成功");

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

    /// find_by_code 跨租户查询应返回 None。
    #[tokio::test(flavor = "multi_thread")]
    async fn find_by_code_cross_tenant_returns_none() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        repo.create(
            1,
            NewRole {
                code: "cross-role".to_string(),
                name: "跨租户测试".to_string(),
                description: None,
                is_system: false,
            },
        )
        .await
        .expect("create 应成功");

        let cross = repo
            .find_by_code(2, "cross-role")
            .await
            .expect("find_by_code 应成功");
        assert!(cross.is_none(), "跨租户 find_by_code 应返回 None");
    }

    /// delete 跨租户不报错也不删除。
    #[tokio::test(flavor = "multi_thread")]
    async fn delete_cross_tenant_is_noop() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool.clone());

        let id = repo
            .create(
                1,
                NewRole {
                    code: "del-cross".to_string(),
                    name: "跨租户删".to_string(),
                    description: None,
                    is_system: false,
                },
            )
            .await
            .expect("create 应成功");

        repo.delete(2, &id).await.expect("跨租户 delete 应为 no-op");

        let still = repo.find_by_id(1, &id).await.expect("find 应成功");
        assert!(still.is_some(), "跨租户 delete 不应影响其他租户");
    }

    /// update 跨租户不报错也不更新。
    #[tokio::test(flavor = "multi_thread")]
    async fn update_cross_tenant_is_noop() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool.clone());

        let id = repo
            .create(
                1,
                NewRole {
                    code: "upd-cross".to_string(),
                    name: "原名".to_string(),
                    description: None,
                    is_system: false,
                },
            )
            .await
            .expect("create 应成功");

        repo.update(2, &id, Some("新名".to_string()), None, None)
            .await
            .expect("跨租户 update 应为 no-op");

        let still = repo.find_by_id(1, &id).await.expect("find 应成功").unwrap();
        assert_eq!(still.name, "原名", "跨租户 update 不应影响其他租户");
    }

    /// list 空租户返回空列表。
    #[tokio::test(flavor = "multi_thread")]
    async fn list_empty_tenant_returns_empty() {
        let pool = setup_db().await;
        let repo = DbnexusRoleRepository::new(pool);

        let result = repo.list(999, 0, 100).await.expect("list 应成功");
        assert!(result.is_empty(), "空租户 list 应返回空");
    }
}