use async_trait::async_trait;
use dbnexus::DbPool;
use garrison::context::tenant::current_tenant_id_or_error;
#[cfg(feature = "db-mysql")]
use garrison::dao::repository::mysql::{
DbnexusMysqlPermissionRepository as PermissionRepositoryImpl,
DbnexusMysqlRolePermissionRepository as RolePermissionRepositoryImpl,
DbnexusMysqlRoleRepository as RoleRepositoryImpl,
DbnexusMysqlUserRoleRepository as UserRoleRepositoryImpl,
};
#[cfg(feature = "db-postgres")]
use garrison::dao::repository::postgres::{
DbnexusPostgresPermissionRepository as PermissionRepositoryImpl,
DbnexusPostgresRolePermissionRepository as RolePermissionRepositoryImpl,
DbnexusPostgresRoleRepository as RoleRepositoryImpl,
DbnexusPostgresUserRoleRepository as UserRoleRepositoryImpl,
};
#[cfg(feature = "db-sqlite")]
use garrison::dao::repository::sqlite::{
DbnexusPermissionRepository as PermissionRepositoryImpl,
DbnexusRolePermissionRepository as RolePermissionRepositoryImpl,
DbnexusRoleRepository as RoleRepositoryImpl,
DbnexusUserRoleRepository as UserRoleRepositoryImpl,
};
use garrison::dao::repository::{
PermissionRepository, RolePermissionRepository, RoleRepository, UserRoleRepository, UserRoleRow,
};
use garrison::prelude::{GarrisonInterface, GarrisonResult};
use std::collections::HashSet;
pub struct CrawlrsGarrisonInterface {
pool: DbPool,
}
impl CrawlrsGarrisonInterface {
pub fn new(pool: DbPool) -> Self {
Self { pool }
}
async fn load_permission_ids(
pool: DbPool,
tenant_id: i64,
user_roles: &[UserRoleRow],
) -> GarrisonResult<HashSet<String>> {
let role_perm_repo = RolePermissionRepositoryImpl::new(pool);
let mut permission_ids: HashSet<String> = HashSet::with_capacity(user_roles.len());
for ur in user_roles {
let role_perms = role_perm_repo
.find_by_role_id(tenant_id, &ur.role_id)
.await?;
for rp in role_perms {
permission_ids.insert(rp.permission_id);
}
}
Ok(permission_ids)
}
async fn load_permission_codes(
pool: DbPool,
permission_ids: HashSet<String>,
) -> GarrisonResult<Vec<String>> {
let perm_repo = PermissionRepositoryImpl::new(pool);
let mut perms: Vec<String> = Vec::with_capacity(permission_ids.len());
for pid in permission_ids {
let perm = perm_repo.find_by_id(&pid).await?;
if let Some(row) = perm {
perms.push(row.code);
}
}
Ok(perms)
}
}
#[async_trait]
impl GarrisonInterface for CrawlrsGarrisonInterface {
async fn get_permission_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
let tenant_id = current_tenant_id_or_error()?;
let pool = self.pool.clone();
let user_role_repo = UserRoleRepositoryImpl::new(pool.clone());
let user_roles = user_role_repo.find_by_user_id(tenant_id, login_id).await?;
if user_roles.is_empty() {
return Ok(Vec::new());
}
let permission_ids =
Self::load_permission_ids(pool.clone(), tenant_id, &user_roles).await?;
if permission_ids.is_empty() {
return Ok(Vec::new());
}
Self::load_permission_codes(pool, permission_ids).await
}
async fn get_role_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
let tenant_id = current_tenant_id_or_error()?;
let pool = self.pool.clone();
let user_role_repo = UserRoleRepositoryImpl::new(pool.clone());
let user_roles = user_role_repo.find_by_user_id(tenant_id, login_id).await?;
if user_roles.is_empty() {
return Ok(Vec::new());
}
let role_repo = RoleRepositoryImpl::new(pool);
let mut roles: Vec<String> = Vec::with_capacity(user_roles.len());
for ur in &user_roles {
let role = role_repo.find_by_id(tenant_id, &ur.role_id).await?;
if let Some(row) = role {
roles.push(row.code);
}
}
Ok(roles)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::test_helpers::{create_test_db_pool, skip_if_no_test_db};
use garrison::context::tenant::{TenantContext, TenantSource, TENANT};
async fn with_default_tenant<F, R>(f: F) -> R
where
F: std::future::Future<Output = R>,
{
let ctx = TenantContext {
tenant_id: 0,
resolved_from: TenantSource::Header,
};
TENANT.scope(ctx, f).await
}
#[test]
fn test_interface_construct_does_not_panic() {
if skip_if_no_test_db() {
return;
}
let pool = create_test_db_pool();
let _interface = CrawlrsGarrisonInterface::new((*pool).clone());
}
#[tokio::test]
async fn test_get_role_list_fails_without_tenant_context() {
if skip_if_no_test_db() {
return;
}
let pool = create_test_db_pool();
let interface = CrawlrsGarrisonInterface::new((*pool).clone());
let result = interface.get_role_list("any_login_id").await;
assert!(
result.is_err(),
"get_role_list must fail-closed when no tenant context is set"
);
}
#[tokio::test]
async fn test_get_permission_list_fails_without_tenant_context() {
if skip_if_no_test_db() {
return;
}
let pool = create_test_db_pool();
let interface = CrawlrsGarrisonInterface::new((*pool).clone());
let result = interface.get_permission_list("any_login_id").await;
assert!(
result.is_err(),
"get_permission_list must fail-closed when no tenant context is set"
);
}
#[tokio::test]
async fn test_admin_role_returns_crawlrs_admin_permission() {
if skip_if_no_test_db() {
return;
}
let pool = create_test_db_pool();
let interface = CrawlrsGarrisonInterface::new((*pool).clone());
let session = pool.get_session("admin").await.expect("db session");
let conn = session.connection().expect("db connection");
use dbnexus::database::ConnectionTrait;
let has_rbac = conn
.query_one_raw(dbnexus::sea_orm::Statement::from_string(
dbnexus::sea_orm::DbBackend::Postgres,
"SELECT 1 FROM app_permission LIMIT 1".to_string(),
))
.await
.is_ok();
if !has_rbac {
eprintln!(
"[skip] garrison RBAC schema missing (app_permission) — 预置 garrison migrations 后重跑"
);
return;
}
let result =
with_default_tenant(async { interface.get_permission_list("test-admin").await }).await;
match result {
Ok(perms) => {
assert!(
perms.iter().any(|p| p == "crawlrs:admin"),
"admin role should include crawlrs:admin permission, got: {:?}",
perms
);
}
Err(e) => {
panic!(
"get_permission_list failed (expected garrison migrations + admin test data): error kind = {:?}",
std::mem::discriminant(&e)
);
}
}
}
}