--- name: rbac-permission-initialization-pattern description: Pattern for initializing RBAC permissions in business modules that use wildcard expansion, role ID matching, and path registration author: Hermes Agent tags: [rbac, permissions, init, multi-tenant, sage] --- # RBAC Permission Initialization Pattern ## Overview When deploying a business module with RBAC authentication, the permission initialization must handle several complex scenarios: path normalization, role wildcard expansion, CRUD file structure, and URL rewriting edge cases (WSS, index auto-match). **User preference**: Each business module owns its own `scripts/load_path.py` that registers its paths directly via Sage DB operations (mirroring Sage's `load_path.py` internals). This keeps permissions self-contained per module and runnable from any Sage environment. See `references/per-module-load-path.md` for the Python template pattern. The Sage-level `load_path.py` is the canonical declarative source of truth, but for per-module workflows, the module's own script is preferred. ## Role-Based Permission Analysis Methodology Before writing permission scripts, analyze each role's responsibilities and classify paths into tiers: **Step 1: Document role职责** ``` owner.superuser — 系统级: 机构类型/角色/权限管理, 添加业主管理员 *.admin — 机构级: 添加本机构人员, 分配人员角色 reseller.operator — 运营: 产品管理/供应商合同/定价/统一折扣/营销 reseller.sale — 销售: 客户管理/客户特殊折扣 reseller.accountant — 财务: 线下充值/对账结算 reseller.maintainer — 运维维护 customer.customer — 终端客户用户 logined — 所有已登录用户 ``` **Step 2: Analyze module business nature** - Ask: Is this a domain-specific business module (CRM, accounting) or a general tool service (AI agent, reasoning)? - General tool services → broader access (all logined users can use) - Domain-specific modules → restricted to relevant roles **Step 3: Classify into permission tiers** | Tier | Role set | Path types | |------|----------|-----------| | **Public** | `any` | 登录/注册/认证页面、静态资源(img/css) | | **Logined** | all 登录角色 | 用户自助服务(个人信息、API Key)、数据查看(列表+get)、用户自己的CRUD(通过user_id隔离) | | **Admin** | superuser + *.admin | 系统/机构配置管理、用户管理、机构管理 | | **Superuser** | `owner.superuser` only | 全局元数据(角色/权限/机构类型)、高危操作(技能部署) | **Step 4: Register CRUD paths comprehensively** - JSON CRUD `alias` → directory `{alias}/` with `index.ui`, `get_*.dspy`, `add_*.dspy`, `update_*.dspy`, `delete_*.dspy` - Custom `api/` directory may also contain CRUD endpoints — register both - Every CRUD directory needs TWO paths (see Pitfall 2) ## Key Principles ### 1. Wildcard Expansion (Filesystem Scanning) **Problem**: `rbac.check_roles_path()` does exact matching. Permission definitions must be registered as concrete URLs in the DB. **CRITICAL**: Scan ALL file types — `.ui`, `.dspy`, `.js`, `.css`. RBAC protects all static resources. **IMPORTANT: ahserver auto-serves `.css` and `.js` files** from module `wwwroot/` directories — they are injected into HTML responses without explicit ``/`