628 lines
19 KiB
Markdown
628 lines
19 KiB
Markdown
# TT-007 Authorization Boundary Deep Inspection
|
||
|
||
## 1. Executive Summary
|
||
|
||
| Пункт | Значение |
|
||
|-------|----------|
|
||
| Дата | 2026-08-06 |
|
||
| Baseline | dev-doc/security_authorization_architecture.md |
|
||
| Предыдущая проверка | dev-doc/architecture_verification_007_security.md |
|
||
| Тип | READ-ONLY deep inspection |
|
||
| Код изменён | НЕТ |
|
||
|
||
**Главный вопрос:** Как перевести ownership module permissions из Platform в Module с минимальным изменением существующего кода?
|
||
|
||
**Ответ:** Текущая архитектура уже содержит大部分 необходимых компонентов. Минимальный migration path:
|
||
1. Module объявляет permission catalog через `permissions()`
|
||
2. Module вычисляет effective policy локально
|
||
3. Platform хранит только identity + module access profile
|
||
4. `/auth/me` возвращает identity + module access, а не permissions
|
||
|
||
---
|
||
|
||
## 2. Current Authorization Flow
|
||
|
||
### 2.1 Login Flow
|
||
|
||
```
|
||
User → POST /auth/login (email, password)
|
||
→ auth.py:113-132 login()
|
||
→ verify_password(email, password)
|
||
→ create_access_token(data={sub: user_id, email: email})
|
||
→ _build_user_response(user)
|
||
→ return {access_token, user}
|
||
```
|
||
|
||
**Файл:** `platform/backend/app/api/v1/auth.py:113-132`
|
||
|
||
### 2.2 /auth/me Flow
|
||
|
||
```
|
||
GET /auth/me
|
||
→ get_current_user(token)
|
||
→ decode_token(token) → user_id
|
||
→ db.query(User).get(user_id)
|
||
→ _build_user_response(user)
|
||
→ return user + permissions
|
||
```
|
||
|
||
**Файл:** `platform/backend/app/api/v1/auth.py:72-80`
|
||
|
||
### 2.3 Permission Computation
|
||
|
||
```
|
||
_build_user_response(user)
|
||
→ roles = [ur.role.name for ur in user.user_roles]
|
||
→ permissions = set()
|
||
→ if "platform_admin" in roles:
|
||
permissions += all platform.* permissions
|
||
→ if "platform_user" in roles:
|
||
permissions += dashboard.read
|
||
→ if has module_roles:
|
||
permissions += {module_id}.read
|
||
→ if user.is_superadmin:
|
||
return ALL permissions
|
||
→ return permissions list
|
||
```
|
||
|
||
**Файл:** `platform/backend/app/api/v1/auth.py:17-67`
|
||
|
||
**Критично:** Permissions вычисляются в Platform, НЕ в Module.
|
||
|
||
### 2.4 JWT Content
|
||
|
||
```json
|
||
{
|
||
"sub": "1", // user_id
|
||
"email": "admin@...", // email
|
||
"exp": 1234567890 // expiration
|
||
}
|
||
```
|
||
|
||
**Файл:** `platform/backend/app/core/security.py:21-25`
|
||
|
||
**Важно:** JWT содержит только identity (user_id, email). НЕ содержит roles или permissions.
|
||
|
||
### 2.5 Module Token Validation
|
||
|
||
```
|
||
Module receives JWT
|
||
→ decode_platform_token(token)
|
||
→ try JWT_SECRET_KEY (shared secret)
|
||
→ extract user_id, email, roles
|
||
→ _sync_platform_user_to_local(user_id, email, roles)
|
||
→ create_local_token(user_id, email, roles)
|
||
→ return local_user
|
||
```
|
||
|
||
**Файл:** `request_app/core/security.py:31-77`
|
||
|
||
---
|
||
|
||
## 3. Platform Authorization Components
|
||
|
||
### 3.1 _build_user_response()
|
||
|
||
**Файл:** `platform/backend/app/api/v1/auth.py:17-67`
|
||
|
||
**Что делает:**
|
||
- Получает user из БД
|
||
- Извлекает roles из `user.user_roles`
|
||
- Вычисляет permissions на основе ролей
|
||
- Возвращает user + roles + permissions
|
||
|
||
**Проблема:**
|
||
- Содержит business logic authorization
|
||
- Permissions вычисляются в auth endpoint
|
||
- Module не является authority по своим permissions
|
||
|
||
### 3.2 require_platform_admin()
|
||
|
||
**Файл:** `platform/backend/app/core/auth.py:37-47`
|
||
|
||
**Что делает:**
|
||
- Проверяет `is_superadmin` или `platform_admin` role
|
||
- Используется для Platform admin endpoints
|
||
|
||
**Не используется для module authorization.**
|
||
|
||
### 3.3 get_current_user()
|
||
|
||
**Файл:** `platform/backend/app/core/auth.py:14-34`
|
||
|
||
**Что делает:**
|
||
- Декодирует JWT
|
||
- Получает user_id
|
||
- Загружает user из БД
|
||
- Возвращает user_id или User object
|
||
|
||
**Не проверяет permissions — только identity.**
|
||
|
||
---
|
||
|
||
## 4. Module Authorization Components
|
||
|
||
### 4.1 require_role()
|
||
|
||
**Файл:** `request_app/core/auth.py:101-116`
|
||
|
||
```python
|
||
def require_role(roles: List[str]):
|
||
async def role_checker(
|
||
current_user: dict = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
if current_user.get("is_superadmin"):
|
||
return current_user
|
||
|
||
user_id = current_user.get("user_id")
|
||
if not user_id:
|
||
raise HTTPException(403, "User ID not found")
|
||
|
||
user = db.query(User).filter(User.id == user_id).first()
|
||
has_role = any(
|
||
ur.role.name in roles
|
||
for ur in user.user_roles
|
||
)
|
||
|
||
if not has_role:
|
||
raise HTTPException(403, "Not enough permissions")
|
||
return current_user
|
||
return role_checker
|
||
```
|
||
|
||
**Что делает:**
|
||
- Принимает список ролей
|
||
- Проверяет `is_superadmin` (bypass)
|
||
- Проверяет локальные roles пользователя
|
||
- Возвращает 403 если нет роли
|
||
|
||
**Критично:** Проверяет локальные roles, а не Platform permissions.
|
||
|
||
### 4.2 permissions()
|
||
|
||
**Файл:** `modules/request-module/module.py:68-73`
|
||
|
||
```python
|
||
def permissions(self) -> list[str]:
|
||
return [
|
||
"request.read",
|
||
"request.write",
|
||
"request.delete",
|
||
"request.admin",
|
||
"request.settings.manage",
|
||
"request.report.view",
|
||
]
|
||
```
|
||
|
||
**Что делает:**
|
||
- Возвращает static list permissions
|
||
- Вызывается при module registration
|
||
- Используется для `/api/v1/platform/modules` response
|
||
|
||
**Не используется для runtime authorization.**
|
||
|
||
### 4.3 JIT Provisioning
|
||
|
||
**Файл:** `request_app/core/security.py:57-77`
|
||
|
||
```python
|
||
def _sync_platform_user_to_local(user_id: int, email: str, roles: list):
|
||
# Find or create user
|
||
user = db.query(User).filter(User.email == email).first()
|
||
if not user:
|
||
user = User(id=user_id, email=email, source="platform")
|
||
db.add(user)
|
||
|
||
# Sync roles
|
||
for role_name in roles:
|
||
if role_name == "platform_admin":
|
||
role = db.query(Role).filter(Role.name == "admin").first()
|
||
if role and not any(ur.role_id == role.id for ur in user.user_roles):
|
||
user.user_roles.append(UserRole(role_id=role.id))
|
||
db.commit()
|
||
```
|
||
|
||
**Что делает:**
|
||
- Создает пользователя в module DB при первом входе
|
||
- Синхронизирует roles (platform_admin → admin)
|
||
- НЕ копирует permissions
|
||
|
||
---
|
||
|
||
## 5. Current Data Model
|
||
|
||
### 5.1 Platform Tables
|
||
|
||
| Table | Owner | Purpose |
|
||
|-------|-------|---------|
|
||
| `users` | Platform | User identity |
|
||
| `roles` | Platform | Platform roles |
|
||
| `user_roles` | Platform | User → Role |
|
||
| `modules` | Platform | Module registry |
|
||
| `module_roles` | Platform | Module role definitions |
|
||
| `user_module_roles` | Platform | User → Module Role |
|
||
|
||
### 5.2 Module Tables
|
||
|
||
| Table | Owner | Purpose |
|
||
|-------|-------|---------|
|
||
| `users` | Module | Local user copy |
|
||
| `roles` | Module | Local roles |
|
||
| `user_roles` | Module | Local User → Role |
|
||
|
||
### 5.3 Entity Relationship
|
||
|
||
```
|
||
Platform:
|
||
User (1) ──→ (N) UserRole ──→ (1) Role
|
||
User (1) ──→ (N) UserModuleRole ──→ (1) ModuleRole ──→ (1) Module
|
||
|
||
Module:
|
||
User (1) ──→ (N) UserRole ──→ (1) Role
|
||
```
|
||
|
||
---
|
||
|
||
## 6. Current JWT Contract
|
||
|
||
### 6.1 JWT Claims
|
||
|
||
| Claim | Type | Source | Used by |
|
||
|-------|------|--------|---------|
|
||
| `sub` | string | Platform | Module (user_id) |
|
||
| `email` | string | Platform | Module (email) |
|
||
| `exp` | int | Platform | Both |
|
||
|
||
### 6.2 What JWT Does NOT Contain
|
||
|
||
- Roles
|
||
- Permissions
|
||
- Module information
|
||
- Access profile
|
||
|
||
### 6.3 Module Token
|
||
|
||
Module создает свой own JWT:
|
||
|
||
```python
|
||
def create_local_token(user_id: int, email: str, roles: list):
|
||
payload = {
|
||
"sub": str(user_id),
|
||
"email": email,
|
||
"roles": roles,
|
||
"exp": datetime.utcnow() + timedelta(hours=24)
|
||
}
|
||
return jwt.encode(payload, JWT_SECRET_KEY, algorithm="HS256")
|
||
```
|
||
|
||
**Файл:** `request_app/core/security.py:23-28`
|
||
|
||
**Module JWT содержит roles, но НЕ permissions.**
|
||
|
||
---
|
||
|
||
## 7. Current /auth/me Contract
|
||
|
||
### 7.1 Response Schema
|
||
|
||
```json
|
||
{
|
||
"user": {
|
||
"id": 1,
|
||
"email": "admin@...",
|
||
"first_name": "Admin",
|
||
"last_name": "User",
|
||
"is_active": true,
|
||
"is_superadmin": true,
|
||
"roles": ["platform_admin"],
|
||
"module_roles": {"request": ["admin"]},
|
||
"permissions": [
|
||
"platform.dashboard.read",
|
||
"platform.users.read",
|
||
...
|
||
]
|
||
}
|
||
}
|
||
```
|
||
|
||
### 7.2 What Permissions Are Returned
|
||
|
||
| Category | Permissions | Source |
|
||
|----------|-------------|--------|
|
||
| Platform | `platform.*` | `_build_user_response()` |
|
||
| Module | `{module_id}.read` | `_build_user_response()` |
|
||
|
||
### 7.3 Who Uses /auth/me
|
||
|
||
| Consumer | Uses for |
|
||
|----------|----------|
|
||
| Platform Frontend | Navigation, route guards |
|
||
| Request Module Frontend | Permission checks (via platform-api) |
|
||
|
||
### 7.4 What Should Stay in /auth/me
|
||
|
||
**After migration:**
|
||
- ✅ User identity (id, email, name, is_active, is_superadmin)
|
||
- ✅ Platform roles
|
||
- ✅ Module access list (which modules user can access)
|
||
- ❌ Permissions (should be computed by Module)
|
||
|
||
---
|
||
|
||
## 8. Current Frontend Dependencies
|
||
|
||
### 8.1 AuthContext
|
||
|
||
**Файл:** `platform/frontend/src/contexts/AuthContext.tsx`
|
||
|
||
**Uses:**
|
||
- `user.permissions` — for `hasPermission()`
|
||
- `user.is_superadmin` — bypass all checks
|
||
- `user.module_roles` — for module-specific checks
|
||
|
||
### 8.2 PermissionGuard
|
||
|
||
**Файл:** `platform/frontend/src/components/PermissionGuard.tsx`
|
||
|
||
**Uses:**
|
||
- `hasPermission(permission)` — single permission check
|
||
- `hasAnyPermission(permissions)` — multiple permission check
|
||
|
||
### 8.3 Layout
|
||
|
||
**Файл:** `platform/frontend/src/components/Layout.tsx`
|
||
|
||
**Uses:**
|
||
- `hasPermission('platform.dashboard.read')` — navigation visibility
|
||
- `hasPermission('platform.users.read')` — navigation visibility
|
||
- `hasPermission('platform.roles.read')` — navigation visibility
|
||
- `hasPermission('platform.modules.read')` — navigation visibility
|
||
- `hasPermission(`${mod.id}.read`)` — module visibility
|
||
|
||
---
|
||
|
||
## 9. Reusable Components
|
||
|
||
| Компонент | Файл | Можно переиспользовать для |
|
||
|-----------|------|---------------------------|
|
||
| JWT decode | `security.py` | Token validation |
|
||
| JWT create | `security.py` | Token issuance |
|
||
| bcrypt | `security.py` | Password hashing |
|
||
| User model | `models/user.py` | Identity storage |
|
||
| Role model | `models/role.py` | Role storage |
|
||
| UserRole | `models/associations.py` | Role assignment |
|
||
| ModuleRole | `models/associations.py` | Module role definitions |
|
||
| UserModuleRole | `models/associations.py` | User → Module Role |
|
||
| require_role() | `request_app/core/auth.py` | Permission checking |
|
||
| JIT provisioning | `request_app/core/security.py` | Auto-create users |
|
||
| permissions() | `module.py` | Permission catalog |
|
||
|
||
---
|
||
|
||
## 10. Architectural Conflicts
|
||
|
||
### 10.1 Permissions in Auth Endpoint
|
||
|
||
**Problem:** `_build_user_response()` содержит business logic authorization.
|
||
|
||
**Location:** `platform/backend/app/api/v1/auth.py:17-67`
|
||
|
||
**Impact:** Module не является authority по своим permissions.
|
||
|
||
### 10.2 Module Permissions Not Used
|
||
|
||
**Problem:** `module.permissions()` возвращает catalog, но он не используется для authorization.
|
||
|
||
**Location:** `modules/request-module/module.py:68-73`
|
||
|
||
**Impact:** Permissions вычисляются в Platform hardcoded.
|
||
|
||
### 10.3 Role-Based, Not Permission-Based
|
||
|
||
**Problem:** Module использует `require_role()`, а не `require_permission()`.
|
||
|
||
**Location:** `request_app/core/auth.py:101-116`
|
||
|
||
**Impact:** Нет гранулярного контроля permissions.
|
||
|
||
---
|
||
|
||
## 11. Minimal Migration Path
|
||
|
||
### 11.1 Current State
|
||
|
||
```
|
||
Platform
|
||
→ _build_user_response()
|
||
→ hardcoded permissions
|
||
→ /auth/me
|
||
→ permissions[]
|
||
→ Frontend (AuthContext)
|
||
→ hasPermission()
|
||
```
|
||
|
||
### 11.2 Target State
|
||
|
||
```
|
||
Platform
|
||
→ identity only (user_id, email, roles)
|
||
→ /auth/me
|
||
→ identity + module_access[]
|
||
→ Frontend
|
||
→ for each module:
|
||
→ GET /module/{id}/permissions
|
||
→ module returns effective permissions
|
||
→ Frontend stores per-module permissions
|
||
```
|
||
|
||
### 11.3 Minimal Changes
|
||
|
||
| Что | Изменение | Файл |
|
||
|-----|-----------|------|
|
||
| `_build_user_response()` | Удалить permission computation | `auth.py:17-67` |
|
||
| `/auth/me` | Возвращать identity + module_access | `auth.py:72-80` |
|
||
| Module | Добавить `/permissions` endpoint | `module.py` |
|
||
| Module | Implement permission computation | `auth.py` |
|
||
| Frontend | Запрашивать permissions у Module | `AuthContext.tsx` |
|
||
|
||
### 11.4 What NOT to Change
|
||
|
||
| Что | Почему |
|
||
|-----|--------|
|
||
| JWT format | Module уже валидирует JWT локально |
|
||
| User model | Identity не меняется |
|
||
| Role model | Roles остаются |
|
||
| ModuleRole | Можно переиспользовать |
|
||
| UserModuleRole | Можно переиспользовать |
|
||
| JIT provisioning | Продолжает работать |
|
||
| require_role() | Можно расширить до require_permission() |
|
||
|
||
---
|
||
|
||
## 12. Data Model Impact
|
||
|
||
### 12.1 Tables to Keep
|
||
|
||
| Table | Owner | Reason |
|
||
|-------|-------|--------|
|
||
| `users` | Platform | Identity storage |
|
||
| `roles` | Platform | Platform roles |
|
||
| `user_roles` | Platform | Platform role assignment |
|
||
| `modules` | Platform | Module registry |
|
||
| `module_roles` | Platform | Module role definitions |
|
||
| `user_module_roles` | Platform | User → Module access |
|
||
|
||
### 12.2 Tables to Add (Future)
|
||
|
||
| Table | Owner | Purpose |
|
||
|-------|-------|---------|
|
||
| `permission_catalog` | Module | Module permission definitions |
|
||
| `access_profiles` | Platform | User → Module access profile |
|
||
| `permission_snapshots` | Platform | Cached permission state |
|
||
|
||
### 12.3 Data Ownership
|
||
|
||
| Data | Current Owner | Target Owner |
|
||
|------|---------------|--------------|
|
||
| User identity | Platform | Platform |
|
||
| Platform roles | Platform | Platform |
|
||
| Module roles | Platform | Module |
|
||
| Module permissions | Platform (hardcoded) | Module |
|
||
| Effective policy | Platform | Module |
|
||
|
||
---
|
||
|
||
## 13. Compatibility Risks
|
||
|
||
### 13.1 TT-005 Unified Frontend
|
||
|
||
**Risk:** Frontend зависит от `permissions` в `/auth/me` response.
|
||
|
||
**Mitigation:** Frontend может запрашивать permissions у Module напрямую.
|
||
|
||
### 13.2 PermissionGuard
|
||
|
||
**Risk:** Использует `hasPermission()` из AuthContext.
|
||
|
||
**Mitigation:** AuthContext может быть расширен для per-module permissions.
|
||
|
||
### 13.3 TT-006 Tests
|
||
|
||
**Risk:** Tests проверяют текущий permission model.
|
||
|
||
**Mitigation:** Tests могут быть обновлены после migration.
|
||
|
||
### 13.4 JIT Provisioning
|
||
|
||
**Risk:** `_sync_platform_user_to_local()` копирует roles.
|
||
|
||
**Mitigation:** Roles продолжают синхронизироваться, permissions вычисляются локально.
|
||
|
||
### 13.5 Standalone Mode
|
||
|
||
**Risk:** Module работает без Platform.
|
||
|
||
**Mitigation:** Module уже имеет local token creation, может вычислять permissions локально.
|
||
|
||
---
|
||
|
||
## 14. Recommended Implementation Sequence
|
||
|
||
### Phase 1: Module Permission Catalog
|
||
|
||
1. Module объявляет `permissions()` — УЖЕ ЕСТЬ
|
||
2. Module добавляет `/api/v1/{module_id}/permissions` endpoint
|
||
3. Endpoint возвращает effective permissions для пользователя
|
||
|
||
### Phase 2: Permission Computation in Module
|
||
|
||
1. Module добавляет `get_user_permissions(user_id)` method
|
||
2. Module вычисляет permissions на основе local roles
|
||
3. Module возвращает permissions через API
|
||
|
||
### Phase 3: Platform Changes
|
||
|
||
1. `_build_user_response()` перестает вычислять module permissions
|
||
2. `/auth/me` возвращает identity + module_access
|
||
3. Platform добавляет `access_profiles` table
|
||
|
||
### Phase 4: Frontend Changes
|
||
|
||
1. AuthContext запрашивает permissions у Module
|
||
2. PermissionGuard использует per-module permissions
|
||
3. Layout использует module-specific permissions
|
||
|
||
---
|
||
|
||
## Appendix A: What Can Be Saved Without Changes
|
||
|
||
| Компонент | Файл | Причина |
|
||
|-----------|------|---------|
|
||
| JWT format | `security.py` | Module уже валидирует |
|
||
| User model | `models/user.py` | Identity не меняется |
|
||
| Role model | `models/role.py` | Roles остаются |
|
||
| UserRole | `associations.py` | Role assignment |
|
||
| ModuleRole | `associations.py` | Module role definitions |
|
||
| UserModuleRole | `associations.py` | User → Module Role |
|
||
| require_role() | `request_app/core/auth.py` | Можно расширить |
|
||
| JIT provisioning | `request_app/core/security.py` | Продолжает работать |
|
||
| permissions() | `module.py` | Permission catalog |
|
||
|
||
## Appendix B: What Needs to Change
|
||
|
||
| Компонент | Файл | Изменение |
|
||
|-----------|------|-----------|
|
||
| `_build_user_response()` | `auth.py:17-67` | Удалить permission computation |
|
||
| `/auth/me` response | `auth.py:72-80` | Возвращать identity + module_access |
|
||
| Module auth | `request_app/core/auth.py` | Добавить permission computation |
|
||
| Module API | `module.py` | Добавить `/permissions` endpoint |
|
||
| AuthContext | `AuthContext.tsx` | Запрашивать permissions у Module |
|
||
| PermissionGuard | `PermissionGuard.tsx` | Использовать per-module permissions |
|
||
|
||
## Appendix C: What Needs to Be Added
|
||
|
||
| Компонент | Описание |
|
||
|-----------|----------|
|
||
| Module `/permissions` endpoint | Возвращает effective permissions для пользователя |
|
||
| Module `get_user_permissions()` | Вычисляет permissions на основе local roles |
|
||
| Platform `access_profiles` table | Хранит User → Module access |
|
||
| Frontend per-module permissions | Кэширует permissions для каждого модуля |
|
||
|
||
## Appendix D: What Should Be Deprecated
|
||
|
||
| Компонент | Файл | Причина |
|
||
|-----------|------|---------|
|
||
| Permission computation in `_build_user_response()` | `auth.py:17-67` | Module должен быть authority |
|
||
| Hardcoded module permissions | `auth.py:55-60` | Должны вычисляться в Module |
|
||
|
||
## Appendix E: What NOT to Touch at This Stage
|
||
|
||
| Компонент | Почему |
|
||
|-----------|--------|
|
||
| JWT format | Module уже валидирует, не ломать |
|
||
| User/Role models | Identity не меняется |
|
||
| JIT provisioning | Продолжает работать |
|
||
| Standalone mode | Module может работать без Platform |
|
||
| Frontend structure | Изменения минимальны |
|