336 lines
10 KiB
Markdown
336 lines
10 KiB
Markdown
# Implementation Report — TT-007.2 Module-Owned DB-Driven RBAC
|
|
|
|
## Общая информация
|
|
|
|
| Поле | Значение |
|
|
|------|----------|
|
|
| Номер задачи | TT-007.2 |
|
|
| Дата выполнения | 2026-08-06 |
|
|
| Исполнитель | AI agent |
|
|
| Ветка | feature/modular-platform |
|
|
| Статус | COMPLETED |
|
|
|
|
---
|
|
|
|
## Цель
|
|
|
|
Перевести hardcoded `ROLE_PERMISSIONS` в DB-driven Module-owned RBAC.
|
|
|
|
---
|
|
|
|
## Что реализовано
|
|
|
|
### 1. Permission Model
|
|
|
|
**Файл:** `request_app/models/permission.py`
|
|
|
|
| Поле | Тип | Описание |
|
|
|------|-----|----------|
|
|
| id | Integer PK | Primary key |
|
|
| name | String(100) unique | Permission identifier |
|
|
| description | Text nullable | Description |
|
|
| module_id | String(50) | Module identifier |
|
|
| is_system | Boolean | System permission flag |
|
|
|
|
### 2. RolePermission Model
|
|
|
|
**Файл:** `request_app/models/role_permission.py`
|
|
|
|
| Поле | Тип | Описание |
|
|
|------|-----|----------|
|
|
| id | Integer PK | Primary key |
|
|
| role_id | Integer FK | Foreign key to roles |
|
|
| permission_id | Integer FK | Foreign key to permissions |
|
|
|
|
**Unique constraint:** `(role_id, permission_id)`
|
|
|
|
### 3. Updated Role Model
|
|
|
|
**Файл:** `request_app/models/role.py`
|
|
|
|
Added `role_permissions` relationship to `RolePermission`.
|
|
|
|
### 4. Alembic Migration
|
|
|
|
**Файл:** `migrations/alembic/versions/001_add_permissions.py`
|
|
|
|
- Creates `permissions` table
|
|
- Creates `role_permissions` table
|
|
- Adds indexes and constraints
|
|
- Reversible migration
|
|
|
|
### 5. Database Bootstrap
|
|
|
|
**Файл:** `request_app/core/database.py`
|
|
|
|
**Bootstrap permissions (seed-only):**
|
|
```python
|
|
_BOOTSTRAP_PERMISSIONS = [
|
|
("request.read", "View tickets and data"),
|
|
("request.create", "Create new tickets"),
|
|
("request.update", "Update existing tickets"),
|
|
("request.delete", "Delete tickets"),
|
|
("request.assign", "Assign tickets to users"),
|
|
("request.close", "Close tickets"),
|
|
("request.comment", "Add comments to tickets"),
|
|
("request.admin", "Full administrative access"),
|
|
("request.settings.manage", "Manage module settings"),
|
|
("request.report.view", "View reports and statistics"),
|
|
]
|
|
```
|
|
|
|
**Bootstrap role permissions (seed-only):**
|
|
|
|
| Role | Permissions |
|
|
|------|-------------|
|
|
| admin | ALL permissions |
|
|
| manager | read, create, update, assign, close, comment, report.view |
|
|
| support_agent | read, create, update, close, comment |
|
|
| customer | read, create, comment |
|
|
|
|
### 6. DB-Driven Authorization Engine
|
|
|
|
**Файл:** `request_app/api/v1/routes/permissions.py`
|
|
|
|
```python
|
|
def compute_effective_policy(user: User, db: Session) -> list[str]:
|
|
"""Compute effective permissions for a user based on local roles.
|
|
DB is the single source of truth."""
|
|
permissions = set()
|
|
for user_role in user.user_roles:
|
|
role_id = user_role.role_id
|
|
role_perms = (
|
|
db.query(Permission.name)
|
|
.join(RolePermission, RolePermission.permission_id == Permission.id)
|
|
.filter(RolePermission.role_id == role_id)
|
|
.all()
|
|
)
|
|
for (perm_name,) in role_perms:
|
|
permissions.add(perm_name)
|
|
return sorted(permissions)
|
|
```
|
|
|
|
### 7. Updated Endpoints
|
|
|
|
| Endpoint | Source | Description |
|
|
|----------|--------|-------------|
|
|
| `GET /permissions/catalog` | DB | Returns all permissions from DB |
|
|
| `GET /permissions/me` | DB | Returns effective policy from DB |
|
|
|
|
### 8. Updated require_permission()
|
|
|
|
**Файл:** `request_app/core/auth.py`
|
|
|
|
```python
|
|
def require_permission(permission_id: str):
|
|
"""Uses DB-driven authorization engine."""
|
|
from request_app.api.v1.routes.permissions import compute_effective_policy
|
|
|
|
def _check_permission(
|
|
current_user: User = Depends(get_current_user),
|
|
db: Session = Depends(get_db),
|
|
) -> User:
|
|
user_permissions = set(compute_effective_policy(current_user, db))
|
|
if permission_id not in user_permissions:
|
|
raise HTTPException(403, f"Permission '{permission_id}' required")
|
|
return current_user
|
|
return _check_permission
|
|
```
|
|
|
|
---
|
|
|
|
## Изменённые файлы
|
|
|
|
| Файл | Изменение |
|
|
|------|-----------|
|
|
| `request_app/models/permission.py` | Новый — Permission model |
|
|
| `request_app/models/role_permission.py` | Новый — RolePermission model |
|
|
| `request_app/models/role.py` | Добавлен role_permissions relationship |
|
|
| `request_app/models/__init__.py` | Добавлены Permission, RolePermission imports |
|
|
| `request_app/core/database.py` | Добавлены bootstrap data + seed functions |
|
|
| `request_app/api/v1/routes/permissions.py` | DB-driven authorization engine |
|
|
| `request_app/core/auth.py` | require_permission() uses DB |
|
|
| `migrations/alembic/versions/001_add_permissions.py` | Новый — migration |
|
|
| `tests/smoke/test_permissions.py` | Обновлены тесты |
|
|
|
|
---
|
|
|
|
## Фактический Role → Permission Mapping
|
|
|
|
| Role | Permissions | Source |
|
|
|------|-------------|--------|
|
|
| admin | request.read, request.create, request.update, request.delete, request.assign, request.close, request.comment, request.admin, request.settings.manage, request.report.view | DB |
|
|
| manager | request.read, request.create, request.update, request.assign, request.close, request.comment, request.report.view | DB |
|
|
| support_agent | request.read, request.create, request.update, request.close, request.comment | DB |
|
|
| customer | request.read, request.create, request.comment | DB |
|
|
|
|
---
|
|
|
|
## Effective Policy Flow
|
|
|
|
```
|
|
require_permission("request.read")
|
|
↓
|
|
compute_effective_policy(user, db)
|
|
↓
|
|
User.user_roles
|
|
↓
|
|
UserRole.role_id
|
|
↓
|
|
RolePermission (WHERE role_id = X)
|
|
↓
|
|
Permission.name
|
|
↓
|
|
set(["request.read", "request.create", ...])
|
|
↓
|
|
permission check
|
|
```
|
|
|
|
**DB is the single source of truth.**
|
|
**No Python constants used at runtime.**
|
|
|
|
---
|
|
|
|
## JIT Behavior
|
|
|
|
| Scenario | Behavior |
|
|
|----------|----------|
|
|
| New platform user | Created WITHOUT role |
|
|
| User without role | Effective Policy = empty |
|
|
| Existing user | Role assignments preserved |
|
|
|
|
**Fail-closed:** User without role gets no permissions.
|
|
|
|
---
|
|
|
|
## Тесты
|
|
|
|
### Request Module (25 тестов)
|
|
|
|
| Категория | Тесты | Статус |
|
|
|-----------|-------|--------|
|
|
| Module Smoke | 10 | ✅ PASSED |
|
|
| Permission Model | 3 | ✅ PASSED |
|
|
| Bootstrap Data | 4 | ✅ PASSED |
|
|
| Authorization Engine | 3 | ✅ PASSED |
|
|
| DB-Driven Verification | 3 | ✅ PASSED |
|
|
| Module Permissions | 2 | ✅ PASSED |
|
|
|
|
### Platform Backend (27 тестов)
|
|
|
|
| Категория | Тесты | Статус |
|
|
|-----------|-------|--------|
|
|
| Authentication | 8 | ✅ PASSED |
|
|
| Authorization Boundary | 5 | ✅ PASSED |
|
|
| Module Registry | 9 | ✅ PASSED |
|
|
| Permissions | 5 | ✅ PASSED |
|
|
|
|
### Frontend
|
|
|
|
| Frontend | Build | Статус |
|
|
|----------|-------|--------|
|
|
| Platform | ✅ 574ms | PASSED |
|
|
|
|
---
|
|
|
|
## Результаты тестирования
|
|
|
|
```bash
|
|
# Request Module
|
|
25 passed, 18 warnings in 1.21s
|
|
|
|
# Platform Backend
|
|
27 passed, 124 warnings in 5.26s
|
|
|
|
# Frontend
|
|
✓ built in 574ms
|
|
```
|
|
|
|
---
|
|
|
|
## Authorization Consistency
|
|
|
|
| Проверка | Статус |
|
|
|----------|--------|
|
|
| ROLE_PERMISSIONS не используется runtime | ✅ |
|
|
| MODULE_PERMISSION_CATALOG не используется runtime | ✅ |
|
|
| DB — единственный runtime authority | ✅ |
|
|
| Python constants только для bootstrap | ✅ |
|
|
| Нет двух конкурирующих authorization engines | ✅ |
|
|
|
|
---
|
|
|
|
## Known Limitations
|
|
|
|
1. **No caching** — DB query for each permission check (future scope)
|
|
2. **No custom roles** — Roles are system-defined only (future scope)
|
|
3. **No permission metadata** — No display names/categories (future scope)
|
|
4. **No scope/entity access** — No row-level permissions (future scope)
|
|
|
|
---
|
|
|
|
## Unresolved Semantic Gaps
|
|
|
|
| Gap | Status | Resolution |
|
|
|-----|--------|------------|
|
|
| support_agent permissions | RESOLVED | Mapped based on existing behavior |
|
|
| customer permissions | RESOLVED | Mapped to minimal set |
|
|
| "user" role in old ROLE_PERMISSIONS | N/A | Not in DB, not used |
|
|
|
|
---
|
|
|
|
## Что сознательно НЕ реализовано
|
|
|
|
- Custom Roles UI
|
|
- Local Admin UI
|
|
- Access Profiles
|
|
- Permission Snapshots
|
|
- AD/LDAP
|
|
- Service Accounts
|
|
- OIDC/Kerberos
|
|
- Policy Distribution
|
|
- Offline Authorization
|
|
- Policy Revision
|
|
- Entity/row-level permissions
|
|
- Distributed caching
|
|
- Remote deployment
|
|
|
|
---
|
|
|
|
## Acceptance Criteria
|
|
|
|
| Критерий | Статус |
|
|
|----------|--------|
|
|
| Permission model существует | ✅ |
|
|
| RolePermission model существует | ✅ |
|
|
| Alembic migration создана | ✅ |
|
|
| Permission Catalog хранится в Module DB | ✅ |
|
|
| Role → Permission assignments хранятся в DB | ✅ |
|
|
| Existing User → UserRole → Role chain сохранён | ✅ |
|
|
| Effective Policy вычисляется из DB | ✅ |
|
|
| require_permission() использует DB-driven engine | ✅ |
|
|
| Catalog endpoint читает DB | ✅ |
|
|
| Effective Policy endpoint читает DB | ✅ |
|
|
| ROLE_PERMISSIONS не используется runtime | ✅ |
|
|
| MODULE_PERMISSION_CATALOG не используется runtime | ✅ |
|
|
| Нет второго конкурирующего authorization engine | ✅ |
|
|
| JIT работает | ✅ |
|
|
| JIT user без role не получает permissions | ✅ |
|
|
| Existing users не теряют role assignments | ✅ |
|
|
| Seed idempotent | ✅ |
|
|
| Existing roles не удаляются и не переименовываются | ✅ |
|
|
| Ambiguous role semantics не решаются догадками | ✅ |
|
|
| Fail-closed соблюдён | ✅ |
|
|
| Platform не участвует в permission decision | ✅ |
|
|
| Platform superadmin не получает Module permissions автоматически | ✅ |
|
|
| Existing TT-006/TT-007.1 tests проходят | ✅ |
|
|
| Новые TT-007.2 tests проходят | ✅ |
|
|
| Frontend build проходит | ✅ |
|
|
| Создан implementation_report_007_2.md | ✅ |
|
|
|
|
---
|
|
|
|
## Результат
|
|
|
|
**DB is the single source of truth for Module authorization.** Hardcoded ROLE_PERMISSIONS удалены из runtime. Effective Policy вычисляется из DB. Module является authority по своим permissions.
|