"""Pure-unit tests for :mod:`app.domains.cmdb.role_classifier`. The classifier predicates feed four enforcement sites — the ``GET /scopes/:id/roles`` filter, the ``POST /grants/request`` / ``/grants/owner-add`` refusals, and the MCP ``request_grant`` tool — plus a frontend mirror in ``web/src/lib/rbac.ts``. A regression here silently re-opens (or re-closes) admin self-service. """ from __future__ import annotations from app.domains.cmdb.role_classifier import ( _ADMIN_NAME_ALLOWLIST, is_admin_role, is_billing_role, ) # ── is_admin_role: substring sieve ───────────────────────────── def test_is_admin_role_matches_substring_admin(): assert is_admin_role("Azure-User-Access-Administrator", None) is True assert is_admin_role("AdministratorAccess", None) is True assert is_admin_role("AdminAccess", None) is True def test_is_admin_role_matches_chinese_token(): assert is_admin_role(None, "运维管理员") is True assert is_admin_role("custom-role-007", "财务管理员") is True def test_is_admin_role_ignores_non_admin_names(): assert is_admin_role("ReadOnlyAccess", None) is False assert is_admin_role("Reader", "只读") is False assert is_admin_role(None, None) is False # ── is_admin_role: allowlist exemption ───────────────────────── def test_is_admin_role_allowlist_dbaas_prod_admin_role(): """``DBaaS-Prod-Admin-Role`` is bounded to the DBaaS-Prod sub-account (not tenant-wide) and is intentionally exposed to self-service. """ assert is_admin_role("DBaaS-Prod-Admin-Role", None) is False assert is_admin_role("dbaas-prod-admin-role", None) is False # case-insensitive assert is_admin_role(None, "DBaaS-Prod-Admin-Role") is False assert is_admin_role(" DBaaS-Prod-Admin-Role ", None) is False # trim def test_allowlist_is_exact_match_not_substring(): """A malicious sibling that merely *contains* an allowlisted name must NOT inherit the exemption — substring would re-open the gate. """ assert is_admin_role("DBaaS-Prod-Admin-Role-Plus", None) is True assert is_admin_role("DBaaS-Prod-Admin-Role-V2", None) is True assert is_admin_role(None, "Fake DBaaS-Prod-Admin-Role Override") is True def test_allowlist_entries_are_normalised(): """Every allowlist entry must be lowercase + trimmed so the lookup in :func:`_allowlisted` actually hits. """ for entry in _ADMIN_NAME_ALLOWLIST: assert entry == entry.strip().lower(), ( f"allowlist entry {entry!r} is not lowercase/trimmed; " "lookup will silently miss" ) # ── is_billing_role (untouched, smoke) ───────────────────────── def test_is_billing_role_untouched_by_allowlist(): assert is_billing_role("Cost Management Reader", None) is True assert is_billing_role(None, "AliyunBillingFullAccess") is True assert is_billing_role("ReadOnly", None) is False