17 KiB
Контрольная точка архитектуры / Architecture Checkpoint
CP-007.2-AUTHORIZATION
Дата / Date: 2026-08-10
Ветка / Branch: feature/modular-platform
Статус / Status: Accepted baseline after TT-007.2
1. Назначение / Purpose
RU
Этот документ фиксирует архитектурное состояние Platform после завершения TT-007.2. Он является baseline для последующих архитектурных и реализационных задач.
Любое изменение зафиксированных инвариантов должно сопровождаться явным архитектурным решением (ADR) либо обновлением данного checkpoint.
EN
This document records the architectural state of Platform after completion of TT-007.2. It serves as the baseline for subsequent architecture and implementation work.
Any change to the established invariants must be accompanied by an explicit architecture decision (ADR) or an updated checkpoint.
2. Владение авторизацией / Authorization Ownership
RU
Platform владеет identity и platform-level access.
Module владеет authorization для собственных бизнес-разрешений.
Platform НЕ вычисляет и НЕ хранит runtime-политику Module-specific permissions.
Module является authority для:
- собственного permission catalog;
- mapping Role → Permission;
- effective policy;
- authorization decisions для собственных операций.
EN
The Platform owns identity and platform-level access.
A Module owns authorization for its own business permissions.
The Platform MUST NOT calculate or maintain Module-specific permissions at runtime.
The Module is the authority for:
- its permission catalog;
- Role → Permission mapping;
- effective policy;
- authorization decisions for its own operations.
3. Identity ≠ Authorization
RU
Identity propagation остаётся Platform-driven через JWT.
Module локально валидирует переданную identity и строит собственный authorization context.
Архитектурный поток:
Platform Identity
↓
JWT
↓
Module Authentication
↓
Local User
↓
Local Roles
↓
Module Permissions
↓
Effective Policy
↓
Authorization Decision
EN
Identity propagation remains Platform-driven through JWT.
The Module validates the propagated identity locally and builds its own authorization context.
Architectural flow:
Platform Identity
↓
JWT
↓
Module Authentication
↓
Local User
↓
Local Roles
↓
Module Permissions
↓
Effective Policy
↓
Authorization Decision
4. Модель разрешений / Permission Data Model
RU
В Request Module используется цепочка:
User
↓
UserRole
↓
Role
↓
RolePermission
↓
Permission
Runtime source of truth для permissions — база данных Module.
Python constants разрешены только для bootstrap/seed и НЕ используются как runtime authorization mapping.
EN
The Request Module uses the following authorization data chain:
User
↓
UserRole
↓
Role
↓
RolePermission
↓
Permission
The Module database is the runtime source of truth for permissions.
Python constants are allowed only for bootstrap/seed operations and MUST NOT be used as runtime authorization mappings.
5. Permission Schema / Схема Permission
RU
Таблица permissions содержит:
idnamedescriptionmodule_idis_systemcreated_atupdated_at
permissions.name имеет UNIQUE.
Таблица role_permissions содержит:
idrole_idpermission_idcreated_atupdated_at
Ограничения:
- FK
role_id → roles.id; - FK
permission_id → permissions.id; ON DELETE CASCADE;- UNIQUE(
role_id,permission_id).
EN
The permissions table contains:
idnamedescriptionmodule_idis_systemcreated_atupdated_at
permissions.name is UNIQUE.
The role_permissions table contains:
idrole_idpermission_idcreated_atupdated_at
Constraints:
- FK
role_id → roles.id; - FK
permission_id → permissions.id; ON DELETE CASCADE;- UNIQUE(
role_id,permission_id).
6. Effective Policy / Эффективная политика
RU
Effective Policy вычисляется локально Module.
Логика:
User
↓
UserRole(s)
↓
Role(s)
↓
RolePermission(s)
↓
Permission(s)
↓
UNION
↓
Effective Policy
Пользователь без локальных ролей получает пустой набор Module permissions.
При наличии нескольких ролей permissions объединяются по UNION без дубликатов.
EN
The Effective Policy is computed locally by the Module.
Logic:
User
↓
UserRole(s)
↓
Role(s)
↓
RolePermission(s)
↓
Permission(s)
↓
UNION
↓
Effective Policy
A user without local roles receives an empty set of Module permissions.
When multiple roles are assigned, permissions are combined using a UNION without duplicates.
7. Authorization Primitives / Примитивы авторизации
RU
Request Module предоставляет:
require_role()
require_permission()
require_permission() использует Module-owned authorization engine.
Authorization failure является локальным решением Module.
Platform superadmin НЕ получает автоматический bypass Module permissions.
EN
The Request Module provides:
require_role()
require_permission()
require_permission() uses the Module-owned authorization engine.
Authorization failures are decided locally by the Module.
Platform superadmin does NOT automatically bypass Module permissions.
8. Permission API / API разрешений
RU
Текущие endpoints Module:
GET /api/v1/request/permissions/catalog
GET /api/v1/request/permissions/me
/permissions/catalog возвращает catalog permissions, определённых Module.
/permissions/me возвращает Effective Policy текущего Principal.
EN
Current Module endpoints:
GET /api/v1/request/permissions/catalog
GET /api/v1/request/permissions/me
/permissions/catalog returns the permission catalog defined by the Module.
/permissions/me returns the Effective Policy of the current Principal.
9. Bootstrap Roles / Bootstrap-роли
RU
Текущие системные роли Request Module:
adminmanagersupport_agentcustomer
Их mappings seed-ятся в Module database.
Bootstrap mappings не являются runtime authorization mappings.
EN
Current Request Module system roles:
adminmanagersupport_agentcustomer
Their mappings are seeded into the Module database.
Bootstrap mappings are not runtime authorization mappings.
10. Database Migration / Миграции БД
RU
Request Module получил первую Alembic migration:
001_add_permissions.py
Она создаёт:
permissions;role_permissions.
Migration была реально проверена на изолированной БД.
Проверены:
- upgrade;
- фактическая schema;
- primary keys;
- foreign keys;
- unique constraints;
- nullable semantics;
- downgrade.
Downgrade удаляет созданные таблицы и не удаляет существующие prerequisite tables.
Base.metadata.create_all() не считается доказательством корректности
migration.
EN
The Request Module now has its first Alembic migration:
001_add_permissions.py
It creates:
permissions;role_permissions.
The migration was actually verified against an isolated database.
Verified:
- upgrade;
- actual schema;
- primary keys;
- foreign keys;
- unique constraints;
- nullable semantics;
- downgrade.
Downgrade removes the newly introduced tables without removing existing prerequisite tables.
Base.metadata.create_all() is not considered proof of migration correctness.
11. ORM ↔ Migration Consistency
RU
Принято правило:
Alembic migration
↕
SQLAlchemy model
структурно должны оставаться согласованными.
Будущие schema changes должны проверяться реальным выполнением migration на чистой тестовой БД, а не только ORM-тестами.
EN
The following rule is established:
Alembic migration
↕
SQLAlchemy model
must remain structurally consistent.
Future schema changes MUST be verified through actual migration execution against a clean test database, not only through ORM tests.
12. Test Baseline / Базовая линия тестов
RU
На момент checkpoint:
- Request Module: 28 tests — PASS
- Platform Backend: 27 tests — PASS
- Frontend: build — PASS
Этот baseline должен сохраняться для последующих изменений.
EN
At the time of this checkpoint:
- Request Module: 28 tests — PASS
- Platform Backend: 27 tests — PASS
- Frontend: build — PASS
This baseline must be preserved for subsequent changes.
13. Известный технический долг / Known Technical Debt
RU
Текущая реализация имеет зависимость, при которой core/auth.py получает
compute_effective_policy() через permissions API module.
Предпочтительное будущее направление:
core/auth.py
↓
authorization service/core
↑
permissions API
Это НЕ является частью TT-007.2 и не должно рефакториться без отдельного архитектурного решения.
EN
The current implementation has a dependency where core/auth.py obtains
compute_effective_policy() through the permissions API module.
Preferred future direction:
core/auth.py
↓
authorization service/core
↑
permissions API
This is NOT part of TT-007.2 and must not be refactored without a separate architecture decision.
14. Explicit Non-Goals / Что пока НЕ реализовано
RU
В этом checkpoint НЕ реализованы:
- Service Accounts;
- service account token lifecycle;
- AD/LDAP;
- OIDC;
- local administrator model;
- policy snapshots;
- policy revision/versioning;
- offline authorization;
- policy distribution;
- remote module deployment;
- runtime endpoint discovery;
- health polling;
- proxy-based routing;
- entity/row-level authorization;
- Access Profiles;
- advanced audit policy;
- Electronic Archive;
- Billing;
- Document Workflow;
- Knowledge Base.
EN
The following are NOT implemented at this checkpoint:
- Service Accounts;
- service account token lifecycle;
- AD/LDAP;
- OIDC;
- local administrator model;
- policy snapshots;
- policy revision/versioning;
- offline authorization;
- policy distribution;
- remote module deployment;
- runtime endpoint discovery;
- health polling;
- proxy-based routing;
- entity/row-level authorization;
- Access Profiles;
- advanced audit policy;
- Electronic Archive;
- Billing;
- Document Workflow;
- Knowledge Base.
15. Архитектурные инварианты / Architectural Invariants
RU
Следующие правила считаются baseline-инвариантами:
- Platform identity не является Module authorization.
- Platform не владеет Module-specific permissions.
- Module permissions хранятся локально.
- Runtime authorization использует Module DB.
- Не существует дублирующего runtime Role → Permission mapping.
- Platform superadmin не получает автоматический bypass Module permissions.
- Module должен иметь возможность принимать собственные authorization decisions независимо от доступности Platform, когда необходимые локальные identity/policy prerequisites выполнены.
- База Module изолирована от базы Platform.
- Module frontend не должен зависеть от семантики Platform permissions.
- Изменения schema требуют проверки реального migration execution.
- Агент не выполняет commit.
- Пользователь является финальным acceptance authority и выполняет commit.
EN
The following rules are established as baseline invariants:
- Platform identity is not Module authorization.
- The Platform does not own Module-specific permissions.
- Module permissions are stored locally.
- Runtime authorization uses the Module database.
- No duplicate runtime Role → Permission mapping exists.
- Platform superadmin does not automatically bypass Module permissions.
- The Module must be able to make its own authorization decisions independently of Platform availability when required local identity/policy prerequisites are satisfied.
- The Module database is isolated from the Platform database.
- The Module frontend must not depend on Platform permission semantics.
- Schema changes require real migration execution verification.
- The agent does not perform commits.
- The user is the final acceptance authority and performs commits.
16. Стратегическое направление / Strategic Direction
RU
Platform проектируется как control plane / ecosystem platform, а не как монолитное бизнес-приложение.
Modules должны быть независимо deployable business products.
Текущие и потенциальные направления:
- Request / Service Desk;
- Electronic Archive;
- Billing;
- Document Workflow;
- Knowledge Base / operational knowledge capabilities.
Коммерческая архитектура должна позволять клиенту приобретать только необходимый Module, когда это технически и коммерчески целесообразно, при этом Platform может оставаться optional.
EN
Platform is designed as a control plane / ecosystem platform rather than a monolithic business application.
Modules are intended to be independently deployable business products.
Current and potential directions include:
- Request / Service Desk;
- Electronic Archive;
- Billing;
- Document Workflow;
- Knowledge Base / operational knowledge capabilities.
The commercial architecture should allow a customer to acquire only the required Module where technically and commercially appropriate, while the Platform may remain optional.
17. Следующий архитектурный фокус / Next Architectural Focus
RU
После фиксации данного checkpoint дальнейшая работа может продолжаться в следующих направлениях:
- Service Account model;
- Module-owned permission administration;
- Permission / policy snapshot;
- local administrator semantics;
- AD/LDAP integration;
- offline authorization and policy TTL;
- policy distribution;
- remote module contract;
- service-to-service authentication;
- runtime endpoint discovery and health monitoring.
Порядок может быть изменён только отдельным архитектурным решением.
EN
After this checkpoint is established, subsequent architecture work may continue in the following areas:
- Service Account model;
- Module-owned permission administration;
- Permission / policy snapshot;
- local administrator semantics;
- AD/LDAP integration;
- offline authorization and policy TTL;
- policy distribution;
- remote module contract;
- service-to-service authentication;
- runtime endpoint discovery and health monitoring.
The order may be changed only through an explicit architecture decision.
18. Checkpoint Rule / Правило checkpoint
RU
Этот документ является baseline.
Любое будущее изменение, нарушающее зафиксированный здесь invariant, должно быть:
- отклонено; или
- оформлено через явное архитектурное решение (ADR) и последующее обновление checkpoint.
Не допускается незаметный architectural drift.
EN
This document is a baseline.
Any future change that violates an invariant established here must either:
- be rejected; or
- be introduced through an explicit architecture decision (ADR) followed by an updated checkpoint.
Silent architectural drift is not allowed.