549 lines
21 KiB
Markdown
549 lines
21 KiB
Markdown
# TT-008 Source Inspection — Service Accounts / Service Accounts Source Inspection
|
|
|
|
## 1. Executive Summary / Резюме
|
|
|
|
| Пункт / Item | Значение / Value |
|
|
|--------------|------------------|
|
|
| Дата / Date | 2026-08-06 |
|
|
| Baseline | TT-008_Service_Accounts_Architecture_Decision_bilingual.md |
|
|
| Тип / Type | READ-ONLY inspection / Только чтение |
|
|
| Код изменён / Code modified | НЕТ / NO |
|
|
| Версия / Version | Corrected per review |
|
|
|
|
**Главный вывод / Key Finding:** Текущая архитектура позволяет реализовать Service Account как отдельный Principal (не подтип User). Существующие authorization primitives (Role, Permission, RolePermission) могут быть переиспользованы через generic Principal abstraction. Нет блокирующих архитектурных препятствий.
|
|
|
|
**Main conclusion:** The current architecture allows implementing Service Account as a separate Principal (not a User subtype). Existing authorization primitives (Role, Permission, RolePermission) can be reused via generic Principal abstraction. There are no blocking architectural obstacles.
|
|
|
|
**Ключевая модель / Key Model:**
|
|
```text
|
|
Principal
|
|
├── User
|
|
└── ServiceAccount
|
|
```
|
|
|
|
---
|
|
|
|
## 2. Current Architecture / Текущая архитектура
|
|
|
|
### 2.1 Platform Backend
|
|
|
|
| Компонент / Component | Файл / File | Описание / Description |
|
|
|-----------------------|-------------|------------------------|
|
|
| User model | `platform/backend/app/models/user.py` | Platform users with is_superadmin |
|
|
| Role model | `platform/backend/app/models/role.py` | Platform roles |
|
|
| UserRole | `platform/backend/app/models/associations.py` | User → Role |
|
|
| JWT | `platform/backend/app/core/security.py` | HS256, 8h lifetime |
|
|
| Auth | `platform/backend/app/core/auth.py` | get_current_user, require_platform_admin |
|
|
|
|
### 2.2 Request Module
|
|
|
|
| Компонент / Component | Файл / File | Описание / Description |
|
|
|-----------------------|-------------|------------------------|
|
|
| User model | `request_app/models/user.py` | Local + platform users |
|
|
| Role model | `request_app/models/role.py` | Local roles (admin, manager, support_agent, customer) |
|
|
| UserRole | `request_app/models/user_role.py` | User → Role |
|
|
| Permission | `request_app/models/permission.py` | DB-driven permission catalog |
|
|
| RolePermission | `request_app/models/role_permission.py` | Role → Permission mapping |
|
|
| Security | `request_app/core/security.py` | JWT validation, bcrypt |
|
|
| Auth | `request_app/core/auth.py` | get_current_user, require_permission |
|
|
| Platform Client | `request_app/core/platform_client.py` | HTTP client to Platform API |
|
|
|
|
---
|
|
|
|
## 3. Principal Model / Identity
|
|
|
|
### 3.1 Approved Architecture / Утверждённая архитектура
|
|
|
|
```text
|
|
Principal
|
|
├── User (human, email/password)
|
|
└── ServiceAccount (machine, credential-based)
|
|
```
|
|
|
|
Service Account — отдельная сущность, НЕ подтип User.
|
|
Service Account is a separate entity, NOT a User subtype.
|
|
|
|
### 3.2 Current Principal Types
|
|
|
|
| Тип / Type | Platform | Module | Описание / Description |
|
|
|------------|----------|--------|------------------------|
|
|
| User | ✅ | ✅ | Human user with email/password |
|
|
| Service Account | ❌ | ❌ | Not implemented |
|
|
| System | ❌ | ❌ | Not implemented |
|
|
|
|
### 3.3 Reusable Authorization Components / Переиспользуемые компоненты
|
|
|
|
| Компонент / Component | Файл / File | Reuse / Переиспользование |
|
|
|-----------------------|-------------|---------------------------|
|
|
| Role model | `models/role.py` | ✅ Generic — не привязан к User |
|
|
| Permission model | `models/permission.py` | ✅ Generic — не привязан к User |
|
|
| RolePermission | `models/role_permission.py` | ✅ Generic — не привязан к User |
|
|
| compute_effective_policy() | `permissions.py` | ⚠️ Требует generic Principal |
|
|
| require_permission() | `auth.py` | ⚠️ Требует generic Principal |
|
|
|
|
### 3.4 Hard User-Specific Dependencies / Жёсткие User-зависимости
|
|
|
|
| Зависимость / Dependency | Файл / File | Адаптация / Adaptation |
|
|
|--------------------------|-------------|------------------------|
|
|
| UserRole.user_id → users.id | `user_role.py` | Нужен GenericPrincipalRole или отдельная ServiceAccountRole |
|
|
| get_current_user() → User | `auth.py` | Нужен get_current_principal() |
|
|
| _sync_platform_user_to_local() | `auth.py` | Не适用于 Service Account |
|
|
| User.email (unique) | `user.py` | Service Account может не иметь email |
|
|
| User.password_hash | `user.py` | Service Account использует другой credential |
|
|
|
|
### 3.5 Implementation Adaptation Points
|
|
|
|
1. **Generic Principal abstraction** — интерфейс для User и ServiceAccount
|
|
2. **PrincipalRole table** — generic link Principal → Role
|
|
3. **get_current_principal()** — dependency для любого Principal type
|
|
4. **Credential abstraction** — password для User, API key/token для ServiceAccount
|
|
|
|
---
|
|
|
|
## 4. Credentials
|
|
|
|
### 4.1 Existing Mechanisms
|
|
|
|
| Механизм / Mechanism | Файл / File | Описание / Description |
|
|
|----------------------|-------------|------------------------|
|
|
| Password hashing | `security.py` | bcrypt |
|
|
| JWT creation | `security.py` | HS256, configurable expiry |
|
|
| JWT validation | `security.py` | Platform key + local key fallback |
|
|
| Token format | JWT | sub=user_id, email, exp |
|
|
|
|
### 4.2 Credential Requirements (не решение / not a decision)
|
|
|
|
| Требование / Requirement | Описание / Description |
|
|
|--------------------------|------------------------|
|
|
| machine-to-machine auth | Service Account authenticates without human |
|
|
| secret shown once | Credential displayed only at creation |
|
|
| rotation | Rotate without downtime |
|
|
| revocation | Immediate invalidation |
|
|
| local validation | No Platform call required |
|
|
| Platform outage | Works during temporary outage |
|
|
|
|
### 4.3 OPEN Questions
|
|
|
|
- Конкретный credential protocol (API key, JWT, mTLS, etc.)
|
|
- Cryptographic algorithm selection
|
|
- Key storage mechanism
|
|
- Rotation strategy
|
|
|
|
---
|
|
|
|
## 5. Lifecycle
|
|
|
|
### 5.1 Service Account Lifecycle States
|
|
|
|
```text
|
|
CREATED → ACTIVE → DISABLED → REVOKED
|
|
↗
|
|
ROTATION
|
|
```
|
|
|
|
### 5.2 Reusable Fields / Переиспользуемые поля
|
|
|
|
| Поле / Field | Таблица / Table | Переиспользование / Reuse |
|
|
|--------------|-----------------|---------------------------|
|
|
| is_active | users | ✅ ACTIVE/DISABLED state |
|
|
| created_at | TimestampMixin | ✅ Audit trail |
|
|
| updated_at | TimestampMixin | ✅ Audit trail |
|
|
|
|
### 5.3 Required New States
|
|
|
|
| Состояние / State | Описание / Description |
|
|
|-------------------|------------------------|
|
|
| CREATED | Initial state, credential not yet activated |
|
|
| REVOKED | Terminal state, cannot be reactivated |
|
|
| Credential state | Separate from Principal state (expired, rotated) |
|
|
|
|
### 5.4 State Differences
|
|
|
|
| Operation | Principal State | Credential State |
|
|
|-----------|-----------------|------------------|
|
|
| Disable | ACTIVE → DISABLED | Unchanged |
|
|
| Enable | DISABLED → ACTIVE | Unchanged |
|
|
| Rotate | Unchanged | Old → Revoked, New → Active |
|
|
| Revoke | ACTIVE → REVOKED | All → Revoked |
|
|
|
|
---
|
|
|
|
## 6. Authorization
|
|
|
|
### 6.1 Current DB-Driven Architecture (после TT-007.2)
|
|
|
|
```
|
|
User → UserRole → Role → RolePermission → Permission
|
|
```
|
|
|
|
### 6.2 Generic Principal Adaptation
|
|
|
|
Для Service Account нужна generic модель:
|
|
For Service Account, a generic model is needed:
|
|
|
|
```
|
|
Principal (User or ServiceAccount)
|
|
↓
|
|
PrincipalRole (generic)
|
|
↓
|
|
Role → RolePermission → Permission
|
|
```
|
|
|
|
### 6.3 Reusable Components
|
|
|
|
| Компонент / Component | Файл / File | Reuse / Переиспользование |
|
|
|-----------------------|-------------|---------------------------|
|
|
| Role | `models/role.py` | ✅ Generic |
|
|
| Permission | `models/permission.py` | ✅ Generic |
|
|
| RolePermission | `models/role_permission.py` | ✅ Generic |
|
|
| compute_effective_policy() | `permissions.py` | ⚠️ Needs generic Principal input |
|
|
| require_permission() | `auth.py` | ⚠️ Needs generic Principal input |
|
|
|
|
---
|
|
|
|
## 7. Platform Boundary
|
|
|
|
### 7.1 Platform Management Operations
|
|
|
|
| Операция / Operation | Механизм / Mechanism |
|
|
|----------------------|----------------------|
|
|
| User sync | JWT claims → _sync_platform_user_to_local() |
|
|
| Role sync | Platform → Module HTTP API |
|
|
| Module registration | Platform registry (in-memory) |
|
|
| Health check | GET /health endpoint |
|
|
|
|
### 7.2 Module-Owned Operations
|
|
|
|
| Операция / Operation | Статус / Status |
|
|
|----------------------|-----------------|
|
|
| Permission catalog | ✅ Module-owned |
|
|
| Role → Permission mapping | ✅ Module-owned |
|
|
| Effective Policy computation | ✅ Module-owned |
|
|
| Authorization decision | ✅ Module-owned |
|
|
| Service Account management | ✅ Should be Module-owned |
|
|
|
|
### 7.3 Direct DB Access
|
|
|
|
- Platform НЕ имеет прямого доступа к Module DB / Platform does NOT have direct access to Module DB
|
|
- Все взаимодействия через HTTP API / All interactions via HTTP API
|
|
|
|
---
|
|
|
|
## 8. Platform Outage
|
|
|
|
### 8.1 Runtime Dependencies
|
|
|
|
| Зависимость / Dependency | Критичность / Criticality |
|
|
|--------------------------|---------------------------|
|
|
| JWT validation | LOW — dual-key fallback |
|
|
| User synchronization | MEDIUM — JIT provisioning |
|
|
| Platform HTTP API | MEDIUM — for token validation |
|
|
|
|
### 8.2 Service Account Feasibility
|
|
|
|
> **Может ли Service Account authentication/authorization быть完全 локальной в Module?**
|
|
>
|
|
> **Can Service Account authentication/authorization be fully local in Module?**
|
|
|
|
**Ответ / Answer:** Да, архитектурно возможно / Yes, architecturally feasible.
|
|
|
|
**Reusable mechanisms:**
|
|
- JWT validation (dual-key)
|
|
- bcrypt for password hashing
|
|
- DB-driven authorization
|
|
|
|
**Implementation gaps:**
|
|
- No Service Account model
|
|
- No credential lifecycle
|
|
- No API key mechanism
|
|
- No machine-to-machine auth flow
|
|
|
|
**Важно / Important:** Existing User/JWT implementation НЕ является автоматически готовой реализацией Service Account. Требуется отдельная реализация.
|
|
Existing User/JWT implementation is NOT automatically a complete Service Account implementation. Separate implementation is required.
|
|
|
|
---
|
|
|
|
## 9. Audit
|
|
|
|
### 9.1 Existing Mechanisms
|
|
|
|
| Механизм / Mechanism | Файл / File | Описание / Description |
|
|
|----------------------|-------------|------------------------|
|
|
| TicketEvent | `models/ticket_event.py` | Audit log for ticket operations |
|
|
| Logging | `core/logging.py` | Rotating file + console logging |
|
|
| auth_logger | `core/logging.py` | Dedicated auth logger |
|
|
|
|
### 9.2 Audit Capabilities
|
|
|
|
| Capability | Статус / Status |
|
|
|------------|-----------------|
|
|
| accountability | ✅ Via logging |
|
|
| forensic history | ⚠️ Limited (logs rotate) |
|
|
| Break-Glass requests | ❌ Not implemented |
|
|
| authorization issuance | ❌ Not tracked |
|
|
| expiration | ❌ Not tracked |
|
|
| results | ❌ Not tracked |
|
|
| security lifecycle events | ❌ Not tracked |
|
|
|
|
### 9.3 Audit Role
|
|
|
|
Audit — accountability mechanism, НЕ защита от SQL tampering.
|
|
Audit is accountability, NOT a defense against SQL tampering.
|
|
|
|
---
|
|
|
|
## 10. LDAP/AD
|
|
|
|
### 10.1 Current State
|
|
|
|
**Статус / Status:** НЕТ интеграции / NO integration.
|
|
|
|
### 10.2 Existing Abstraction Points
|
|
|
|
| Точка / Point | Файл / File | Описание / Description |
|
|
|---------------|-------------|------------------------|
|
|
| source field | User model | Can add "ldap" value |
|
|
| Platform client | `platform_client.py` | Can be extended for LDAP |
|
|
| JWT claims | security.py | Can include LDAP groups |
|
|
|
|
### 10.3 Break-Glass Relationship
|
|
|
|
- LDAP/AD — штатный механизм администрирования / normal administration mechanism
|
|
- Break-Glass — только при потере управляемости / only when normal manageability is lost
|
|
- Это разные границы / Different boundaries
|
|
|
|
---
|
|
|
|
## 11. Break-Glass Integration Points
|
|
|
|
### 11.1 Vendor-assisted Administrative Recovery
|
|
|
|
**Термин / Term:** Vendor-assisted Administrative Recovery
|
|
|
|
**Характеристики / Characteristics:**
|
|
- Только в Corporate Platform / Corporate Platform only
|
|
- Standalone не обязан иметь / Not required in Standalone
|
|
- Не «платный root» / Not paid root access
|
|
- Не backdoor / Not a backdoor
|
|
|
|
### 11.2 Trust Boundary
|
|
|
|
```text
|
|
Customer
|
|
↓
|
|
official recovery request
|
|
↓
|
|
Vendor validation / authorization
|
|
↓
|
|
Vendor Authorization
|
|
↓
|
|
Platform orchestration
|
|
↓
|
|
Module verification
|
|
↓
|
|
Emergency Authority
|
|
```
|
|
|
|
### 11.3 Integration Points
|
|
|
|
| Точка / Point | Описание / Description |
|
|
|---------------|------------------------|
|
|
| Platform privileged operations | is_superadmin, platform_admin role |
|
|
| Module registration | Platform registry |
|
|
| Installation identity | Platform API key |
|
|
| Platform ↔ Module trust | JWT shared secret |
|
|
| Vendor authorization | External verification |
|
|
|
|
---
|
|
|
|
## 12. Emergency Authority Feasibility
|
|
|
|
### 12.1 Approved Model / Утверждённая модель
|
|
|
|
```text
|
|
Vendor Authorization
|
|
↓
|
|
Emergency Authority / Recovery Grant
|
|
↓
|
|
Recovery Policy + Scope + TTL
|
|
↓
|
|
Security Recovery Operations
|
|
```
|
|
|
|
### 12.2 Key Principles
|
|
|
|
1. Emergency Administration НЕ является обычной Role / NOT a normal RBAC role
|
|
2. НЕ получает business permissions / Does NOT receive business permissions
|
|
3. Scope ограничена security recovery operations / Scope limited to security recovery
|
|
4. TTL — обязательно / TTL — mandatory
|
|
5. Module verification — обязательно / Module verification — mandatory
|
|
|
|
### 12.3 Feasibility
|
|
|
|
**Ответ / Answer:** Да, архитектурно возможно / Yes, architecturally feasible.
|
|
|
|
Требуется / Required:
|
|
- Separate authorization artifact (не DB-only state)
|
|
- Vendor Authorization verification
|
|
- Module-side verification
|
|
- TTL enforcement
|
|
- Audit trail
|
|
|
|
---
|
|
|
|
## 13. Database Tampering Risks
|
|
|
|
### 13.1 Architectural Requirement
|
|
|
|
> **Database stores state and audit; authorization proof establishes authority.**
|
|
|
|
### 13.2 Security-Critical Mutable Fields
|
|
|
|
| Поле / Field | Таблица / Table | Риск / Risk |
|
|
|--------------|-----------------|-------------|
|
|
| is_active | users | Отключение пользователя / Disable user |
|
|
| role_id | user_roles | Назначение роли / Role assignment |
|
|
| permission_id | role_permissions | Назначение permissions / Permission assignment |
|
|
| password_hash | users | Сброс пароля / Password reset |
|
|
| is_system | roles | Изменение системной роли / Change system role |
|
|
|
|
### 13.3 Requirements
|
|
|
|
1. mutable DB fields НЕ должны быть единственным источником security-critical authority
|
|
2. SQL UPDATE НЕ должен создавать легитимную Vendor Emergency Authority
|
|
3. Нужен authorization artifact для независимой проверки Module
|
|
4. Конкретная криптография НЕ выбирается сейчас
|
|
|
|
### 13.4 Audit Role
|
|
|
|
Audit — accountability mechanism, НЕ защита от SQL tampering.
|
|
Audit is accountability, NOT a defense against SQL tampering.
|
|
|
|
---
|
|
|
|
## 14. Reusable Components
|
|
|
|
| Компонент / Component | Файл / File | Переиспользование / Reuse |
|
|
|-----------------------|-------------|---------------------------|
|
|
| Role model | `models/role.py` | ✅ Generic, not User-specific |
|
|
| Permission model | `models/permission.py` | ✅ Generic, not User-specific |
|
|
| RolePermission | `models/role_permission.py` | ✅ Generic, not User-specific |
|
|
| TimestampMixin | `models/base.py` | ✅ Audit fields |
|
|
| JWT validation | `core/security.py` | ⚠️ Extend for credentials |
|
|
| bcrypt | `core/security.py` | ✅ Password hashing |
|
|
| Logging | `core/logging.py` | ✅ Audit logging |
|
|
| compute_effective_policy() | `permissions.py` | ⚠️ Needs generic Principal |
|
|
| require_permission() | `auth.py` | ⚠️ Needs generic Principal |
|
|
|
|
---
|
|
|
|
## 15. Required New Components
|
|
|
|
| Компонент / Component | Описание / Description |
|
|
|-----------------------|------------------------|
|
|
| ServiceAccount model | Separate Principal type |
|
|
| PrincipalRole table | Generic Principal → Role link |
|
|
| Credential storage | Secure credential storage |
|
|
| Credential lifecycle | CREATED/ACTIVE/DISABLED/REVOKED |
|
|
| Security audit table | Dedicated security event tracking |
|
|
| Authorization artifact | Verifiable proof for Emergency Authority |
|
|
|
|
---
|
|
|
|
## 16. Architectural Gaps
|
|
|
|
| Gap | Severity | Описание / Description |
|
|
|-----|----------|------------------------|
|
|
| No Service Account model | HIGH | Need separate Principal type |
|
|
| No generic Principal abstraction | HIGH | Current code assumes User |
|
|
| No credential lifecycle | HIGH | Need CREATED/ACTIVE/DISABLED/REVOKED |
|
|
| No authorization artifact | MEDIUM | Need verifiable proof |
|
|
| No security audit | MEDIUM | Need dedicated audit table |
|
|
| No TTL-based access | LOW | Need for emergency access |
|
|
|
|
---
|
|
|
|
## 17. Blocking Questions
|
|
|
|
| Вопрос / Question | Статус / Status |
|
|
|-------------------|-----------------|
|
|
| Can SA be separate from User? | YES — approved architecture |
|
|
| Can authorization primitives be reused? | YES — Role, Permission, RolePermission are generic |
|
|
| Is Platform dependency blocking? | NO — Module can operate standalone |
|
|
| Can Emergency Authority work without RBAC role? | YES — separate authorization artifact |
|
|
|
|
**Нет блокирующих вопросов / No blocking questions.**
|
|
|
|
---
|
|
|
|
## 18. Recommendation
|
|
|
|
### 18.1 Implementation Path
|
|
|
|
1. Create ServiceAccount model (separate from User)
|
|
2. Create generic PrincipalRole table
|
|
3. Adapt compute_effective_policy() for generic Principal
|
|
4. Add credential storage and lifecycle
|
|
5. Implement machine-to-machine auth flow
|
|
6. Add security audit table
|
|
7. (Future) Add authorization artifact for Emergency Authority
|
|
|
|
### 18.2 Key Principles
|
|
|
|
- Service Account ≠ User subtype
|
|
- Authorization primitives are generic
|
|
- Module is authority for its own authorization
|
|
- Audit ≠ tamper protection
|
|
- Emergency Authority ≠ RBAC role
|
|
|
|
---
|
|
|
|
## 19. Final Verdict
|
|
|
|
**READY FOR TT-008 IMPLEMENTATION**
|
|
|
|
Текущая архитектура позволяет реализовать Service Account как отдельный Principal. Нет блокирующих архитектурных препятствий. Существующие authorization primitives (Role, Permission, RolePermission) могут быть переиспользованы через generic Principal abstraction.
|
|
|
|
The current architecture allows implementing Service Account as a separate Principal. There are no blocking architectural obstacles. Existing authorization primitives (Role, Permission, RolePermission) can be reused via generic Principal abstraction.
|
|
|
|
---
|
|
|
|
## Appendix A: What We Keep / Что сохраняем
|
|
|
|
| Компонент / Component | Причина / Reason |
|
|
|-----------------------|------------------|
|
|
| Role model | Generic, not User-specific |
|
|
| Permission model | Generic, not User-specific |
|
|
| RolePermission | Generic, not User-specific |
|
|
| TimestampMixin | Audit fields |
|
|
| JWT validation | Extendable |
|
|
| bcrypt | Password hashing |
|
|
| Logging | Audit logging |
|
|
|
|
## Appendix B: What We Add / Что добавляем
|
|
|
|
| Компонент / Component | Описание / Description |
|
|
|-----------------------|------------------------|
|
|
| ServiceAccount model | Separate Principal |
|
|
| PrincipalRole table | Generic Principal → Role |
|
|
| Credential storage | Secure storage |
|
|
| Security audit table | Security events |
|
|
|
|
## Appendix C: What We Adapt / Что адаптируем
|
|
|
|
| Компонент / Component | Адаптация / Adaptation |
|
|
|-----------------------|------------------------|
|
|
| compute_effective_policy() | Accept generic Principal |
|
|
| require_permission() | Accept generic Principal |
|
|
| get_current_user() | Create get_current_principal() |
|
|
|
|
## Appendix D: What We Don't Do / Что не делаем
|
|
|
|
| Компонент / Component | Причина / Reason |
|
|
|-----------------------|------------------|
|
|
| API keys in User model | SA ≠ User |
|
|
| emergency_admin role | Emergency ≠ RBAC |
|
|
| Platform as root authority | Module is authority |
|
|
| Concrete cryptography | OPEN decision |
|
|
| LDAP/AD integration | Future scope |
|