unis_hrms/tests/test_rbac_sync.py

134 lines
6.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""升级发版后的 RBAC 自动同步(新权限点 / 新菜单 / 超管补授权)+ 权限清单顺序。
对应线上事故:代码里加了「数据维护」菜单与 system:maintenance:* 权限点,
老库没这几行 → 菜单看不见、角色授权页也搜不到,只能手工跑播种脚本。
"""
from __future__ import annotations
import asyncio
from sqlalchemy import delete, func, select
from app.core.permissions import build_permissions, menu_catalogue_order
from app.db.session import SessionFactory
from app.models.rbac import Menu, Permission, Role, RolePermission, User, UserRole
API = "/api/v1"
NEW_CODES = ["system:maintenance:read", "system:maintenance:backup", "system:maintenance:purge"]
def test_start_up_sync_backfills_permissions_and_menus(client, admin):
"""删掉新权限点 + 菜单,再走一次启动同步,必须自动补齐(含超管补授权)。"""
async def scenario():
async with SessionFactory() as session:
await session.execute(delete(Permission).where(Permission.code.in_(NEW_CODES)))
await session.execute(delete(Menu).where(Menu.path == "/system/maintenance"))
await session.commit()
await asyncio.sleep(0)
async def resync():
from app.services.seed_rbac import sync_rbac
return await sync_rbac()
async def assert_backfilled(report):
assert report["new_permissions"] >= len(NEW_CODES), report
assert report["menus"] >= 1, report
# 超管的授权由「* 模板」+ 兜底补齐共同保证:同步后必须等于全部权限点
assert report["super_admin_grants"] >= 0, report
async with SessionFactory() as session:
codes = set((await session.execute(
select(Permission.code).where(Permission.code.in_(NEW_CODES)))).scalars().all())
assert set(NEW_CODES) <= codes
menu = (await session.execute(
select(Menu).where(Menu.path == "/system/maintenance"))).scalar_one_or_none()
assert menu is not None and menu.perm_code == "system:maintenance:read"
# 超管角色本身也被补齐(不只是靠 is_superuser 兜底)
role_id = (await session.execute(select(Role.id).where(Role.code == "super_admin"))).one()[0]
total = (await session.execute(select(func.count()).select_from(Permission))).scalar()
linked = (await session.execute(
select(func.count())
.select_from(RolePermission)
.join(Permission, Permission.id == RolePermission.permission_id)
.where(RolePermission.role_id == role_id)
)).scalar()
assert linked == total
async def drop_super_admin_links():
"""造出「新权限点没授权给超管」的现场,验证兜底补齐本身可用。"""
async with SessionFactory() as session:
role_id = (await session.execute(select(Role.id).where(Role.code == "super_admin"))).one()[0]
await session.execute(delete(RolePermission).where(RolePermission.role_id == role_id))
await session.commit()
async def grant_all():
from app.services.seed_rbac import grant_all_to_superuser_role
async with SessionFactory() as session:
n = await grant_all_to_superuser_role(session)
await session.commit()
return n
asyncio.run(scenario())
# 模拟重启:应用启动钩子会调用同一个 sync_rbac()
report = asyncio.run(resync())
asyncio.run(assert_backfilled(report))
asyncio.run(_cleanup())
asyncio.run(drop_super_admin_links())
assert asyncio.run(grant_all()) >= len(NEW_CODES)
# 菜单接口对超管可见;权限清单里能搜到新权限点(前端授权页据此渲染)
menus = client.get(f"{API}/auth/menus", params={"platform": "web"}, headers=admin).json()
system = next((m for m in menus if m["name"] == "系统管理"), None)
assert system and any(c["path"] == "/system/maintenance" for c in system["children"])
catalogue = client.get(f"{API}/system/permissions", headers=admin).json()
codes = {a["code"] for m in catalogue["modules"] for r in m["resources"] for a in r["actions"]}
assert set(NEW_CODES) <= codes
async def _cleanup():
"""把删掉的行补回来,避免影响同一会话里的其它用例(如维护页表计数)。"""
from app.services.seed_rbac import sync_rbac
await sync_rbac()
async with SessionFactory() as session:
admin_id = (await session.execute(select(User.id).where(User.username == "admin"))).one()[0]
role_id = (await session.execute(select(Role.id).where(Role.code == "super_admin"))).one()[0]
if not (await session.execute(
select(UserRole).where(UserRole.user_id == admin_id, UserRole.role_id == role_id)
)).scalar_one_or_none():
session.add(UserRole(user_id=admin_id, role_id=role_id))
await session.commit()
def test_permission_catalogue_follows_menu_order(client, admin):
"""角色授权页右侧树的顺序必须与主界面菜单一致(模块 + 模块内资源)。"""
body = client.get(f"{API}/system/permissions", headers=admin).json()
modules = body["modules"]
module_order, resource_order = menu_catalogue_order()
shown = [m["module"] for m in modules]
assert shown == [m for m in module_order if m in shown], shown
# 菜单里的主线模块必须成段出现:人事档案 → 招聘 → 薪资 → 福利 → 组织 → 系统
mainline = ["employee", "recruitment", "payroll", "benefits", "org", "system"]
assert [m for m in shown if m in mainline] == mainline, shown
for module in modules:
order = resource_order[module["module"]]
resources = [r["resource"] for r in module["resources"]]
assert resources == [r for r in order if r in resources], (module["module"], resources)
# 权限点顺序 = 声明顺序,read 永远在首位,前端不再出现「删除」排在「查看」上面
for resource in module["resources"]:
assert resource["actions"][0]["action"] == "read", resource["resource"]
def test_every_permission_is_listed(client, admin):
"""清单必须覆盖代码里声明的全部权限点:漏一条就等于「无法授权」。"""
body = client.get(f"{API}/system/permissions", headers=admin).json()
codes = {a["code"] for m in body["modules"] for r in m["resources"] for a in r["actions"]}
declared = {item.code for item in build_permissions()}
assert declared - codes == set()
assert body["total"] == len(codes)