2 Commits

Author SHA1 Message Date
alex 24b03970b0 Add Ansible connectivity test 2026-08-15 17:40:22 +03:00
alex 4e7dc451ac feat(request): add service accounts and unified authorization 2026-08-11 11:16:38 +03:00
23 changed files with 4955 additions and 19 deletions
@@ -0,0 +1,181 @@
TT-007 Authorization Boundary Decision Patch
СТАТУС
Архитектурное уточнение перед implementation.
ИСТОЧНИК
Основной архитектурный baseline:
dev-doc/security_authorization_architecture.md
Предыдущие материалы:
dev-doc/architecture_verification_007_security.md
dev-doc/authorization_boundary_inspection_007.md
ЦЕЛЬ
Зафиксировать два уточнения, выявленных после Deep Inspection, до начала реализации.
1. OWNERSHIP MODULE ROLE / PERMISSIONS
Окончательно зафиксировать:
Module является владельцем:
- Module Roles;
- Permission Catalog;
- Local Assignments;
- Entity Access;
- Business Authorization;
- Effective Policy;
- правил интерпретации Access Profile / Snapshot.
Platform может хранить:
- User Identity;
- Platform Roles;
- Module Access;
- Access Profile;
- Permission Snapshot / экспортную репрезентацию policy.
Но Platform НЕ является authority по смыслу Module Roles или Module Permissions.
Не допускать архитектуры:
Platform
-> ModuleRole
-> ModulePermission
-> Authorization
Целевая модель:
Platform
-> Identity
-> Module Access
-> Access Profile / Snapshot
-> Module
Module
-> Module Roles
-> Permission Catalog
-> Local Assignment
-> Effective Policy
-> Business Authorization
Access Profile / Snapshot, находящийся в Platform, является механизмом
управления, резервирования, клонирования и восстановления, а не
источником semantics Module permissions.
2. PERMISSION CATALOG VS EFFECTIVE POLICY
Разделить два понятия.
A. Permission Catalog
Это каталог возможностей, которые предоставляет Module.
Например:
request.read
request.write
request.delete
request.settings.manage
request.report.view
Он принадлежит Module.
Текущий:
module.permissions()
может быть сохранён и эволюционно превращён в authoritative
Module Permission Catalog.
B. Effective Policy
Это рассчитанный для конкретного Principal набор реально разрешённых
операций с учётом:
- identity;
- AD/LDAP groups (в будущем);
- Platform Access Profile / Snapshot;
- Module Roles;
- Local Assignments;
- Module Policy;
- business context.
Effective Policy принадлежит Module Authorization Engine.
НЕ смешивать Permission Catalog и Effective Policy в одном понятии
или API.
РЕКОМЕНДУЕМАЯ КОНЦЕПТУАЛЬНАЯ МОДЕЛЬ API
Permission Catalog:
GET /permissions
или эквивалентный Module API endpoint.
Назначение:
получить каталог возможностей Module.
Effective Policy:
GET /me/effective-policy
или эквивалентный Module API endpoint.
Назначение:
получить authorization state конкретного Principal.
ВАЖНО:
Конкретные URL пока НЕ являются обязательными архитектурными решениями.
Перед implementation нужно проверить текущий API style Module и выбрать
наиболее согласованный с существующей структурой вариант.
НЕ ТРЕБУЕТСЯ
Этот patch НЕ является implementation TZ.
Не нужно сейчас:
- реализовывать endpoints;
- изменять БД;
- менять JWT;
- реализовывать Service Accounts;
- реализовывать AD/LDAP;
- реализовывать Policy Distribution;
- реализовывать Offline Authorization;
- реализовывать Permission Snapshot;
- менять frontend;
- удалять существующий ModuleRole/UserModuleRole.
ТРЕБОВАНИЕ К ПОСЛЕДУЮЩЕЙ РЕАЛИЗАЦИИ
Первая implementation-итерация должна быть минимальной и должна
физически установить новую authorization boundary:
Platform
-> identity + module access
-> Module
-> Module Permission Catalog
-> Module Authorization
-> Effective Policy
При этом существующие TT-005/TT-006 механизмы должны сохранять
работоспособность.
КРИТЕРИЙ ПРИЁМКИ АРХИТЕКТУРНОГО УТОЧНЕНИЯ
Считать решение принятым, если implementation TZ:
1. Не делает Platform владельцем Module permissions.
2. Не смешивает Permission Catalog и Effective Policy.
3. Сохраняет возможность standalone работы Module.
4. Не требует реализации AD/LDAP, Service Accounts или Offline Policy
для первой итерации.
5. Использует существующий Module Contract и переиспользует
существующие authorization components там, где это возможно.
@@ -0,0 +1,562 @@
# TT-008 — Service Accounts Architecture Decision
# TT-008 — Архитектурное решение: Service Accounts
**Status / Статус:** DRAFT — FOR DISCUSSION / ЧЕРНОВИК — НА СОГЛАСОВАНИЕ
**Version / Версия:** 0.1
**Date / Дата:** 2026-08-10
---
# РУССКАЯ ВЕРСИЯ
## 1. Назначение
Документ фиксирует предварительную архитектурную модель Service Accounts в экосистеме Platform и Modules.
Это **не задание на реализацию**. До отдельного согласования решений агенту не передавать.
Цель TT-008 — определить ownership Service Account, поведение в Platform Managed и Standalone режимах, границу Platform / Module, роль Local Admin, место Service Account в authorization model, аварийный Vendor Break-Glass механизм и нерешённые вопросы.
## 2. Уже принятые инварианты
1. Platform не владеет Module-specific permissions.
2. Module является authority для собственного permission catalog, policy и authorization decisions.
3. Module должен полноценно работать без Platform.
4. Local Admin является штатным владельцем административной authority Module.
5. Platform не должна становиться скрытым владельцем бизнес-логики Module.
## 3. Предлагаемая модель Service Account
### 3.1 Ownership
**Service Account является Module-owned сущностью.**
Module отвечает за:
- создание;
- lifecycle;
- credentials;
- локальную регистрацию;
- назначение ролей;
- назначение permissions;
- authorization.
Platform не является owner Service Account.
### 3.2 Platform Managed Mode
```text
PLATFORM
│
management / observation
│
▼
MODULE
│
Service Account
│
┌─────────┴─────────┐
▼ ▼
Roles Permissions
```
Platform может управлять или наблюдать Service Account только через Module contract/API и не должна напрямую изменять Module DB.
### 3.3 Standalone Mode
```text
MODULE
│
Local Admin
│
Service Account
│
┌────────┴────────┐
▼ ▼
Roles Permissions
```
В Standalone Platform отсутствует; Local Admin создаёт Service Account; Module полностью самостоятельно управляет им.
## 4. Создание Service Account
Предварительное решение:
> **Service Account создаётся Local Admin внутри Module.**
Создание системной identity не является функцией Platform.
Это даёт одинаковую ownership model:
```text
Platform Managed → Module creates
Standalone → Module creates
```
## 5. Service Account и Authorization
Создание Service Account **не означает предоставление доступа**.
```text
Service Account
↓
local registration
↓
role assignment
↓
permission assignment
↓
effective policy
```
Module самостоятельно определяет, что Service Account разрешено делать. Platform не назначает Module-specific permissions.
## 6. Platform Management Boundary
Platform потенциально может предоставлять:
- enable / disable;
- lifecycle status;
- rotation request;
- monitoring;
- audit visibility.
Все такие операции проходят через Module API.
Принцип:
> **Platform управляет экосистемой; Module владеет своими сущностями.**
## 7. Vendor Break-Glass Administration
### 7.1 Назначение
Предусматривается аварийный сценарий при:
- потере Local Admin;
- блокировке Local Admin;
- утрате credentials;
- недоступности administrative authority;
- необходимости формального emergency recovery.
Это не обычный административный канал.
### 7.2 Модель
Для корпоративных редакций может существовать:
**Vendor Break-Glass Administration**
```text
Customer
│
│ official recovery request
│ + authorized approval
▼
Vendor
│
│ verifies license / grounds
▼
Vendor Authorization
│
▼
Platform
│
│ recovery workflow
▼
Module
│
▼
Administrative Recovery
```
### 7.3 Ограничения
Механизм:
- выключен по умолчанию;
- доступен только в соответствующей Corporate/Enterprise редакции;
- не является постоянным Vendor access;
- привязан к конкретной installation / Module;
- имеет ограниченный TTL;
- желательно одноразовый;
- полностью журналируется;
- используется только для восстановления administrative authority;
- не должен обходить обычную authorization.
### 7.4 Vendor Authorization Artifact
Предварительно используется криптографически подписанный authorization artifact, а не постоянный root password.
Минимальная привязка:
- installation;
- Module;
- request/challenge;
- expiration;
- operation purpose;
- Vendor signature.
**Конкретный криптографический протокол пока НЕ утверждён.**
Emergency token не должен быть простым детерминированным производным от license key.
## 8. Ключевая граница
Break-Glass не означает:
```text
Vendor → unrestricted access to customer data
```
Цепочка должна быть:
```text
Vendor Authorization
↓
Administrative Recovery
↓
Local Admin Authority restored
↓
Normal Module authorization
```
Vendor восстанавливает administrative authority, но не становится постоянным владельцем Module.
## 9. Коммерческая модель
Предварительно:
- Standalone / Standard — без Vendor Break-Glass;
- Corporate / Enterprise — с Vendor Break-Glass capability;
- расширенный SLA / Support может включать recovery procedures.
Продаётся не «root-доступ», а:
> **аварийная эксплуатационная устойчивость и гарантированное восстановление административной authority.**
Точная тарифная модель пока не фиксируется.
## 10. Нерешённые вопросы
**Q1. Credential:** API token, короткоживущий token, key pair, client credentials или комбинация?
**Q2. Хранение credential:** hash, encrypted secret, key pair, повторный показ, rotation?
**Q3. Валидация:** локальная БД, локальный verifier, Platform-issued token, Module-owned signing key или hybrid?
**Q4. Lifecycle:** `created`, `active`, `disabled`, `revoked` и точная семантика состояний.
**Q5. Несколько ролей:** предварительно да, по аналогии с User → Role → Permission.
**Q6. Без роли:** допускается; effective policy должна быть пустой.
**Q7. Один Service Account для нескольких Modules:** предварительно нет; identity принадлежит конкретному Module. Cross-module identity — отдельное решение.
**Q8. Как Platform видит Service Accounts:** pull, push, event, API query, snapshot?
**Q9. Потеря Platform:** Module должен валидировать уже выданные credentials локально в пределах действующей policy. Связано с будущими Offline Authz / Policy Distribution.
**Q10. Что делает Break-Glass:** создаёт Local Admin, восстанавливает существующего, временно активирует admin profile, выдаёт recovery session или комбинацию?
**Q11. Кто инициирует Break-Glass:** отдельная privileged Platform capability.
**Q12. Approval:** официальный запрос клиента, подтверждение уполномоченного лица, причина, Vendor approval.
**Q13. Anti-abuse:** TTL, scope, audit, one-time semantics, revocation, возможно dual control.
## 11. Предлагаемые архитектурные принципы
1. Service Account — Module-owned entity.
2. Local Admin создаёт Service Account.
3. Platform не владеет Service Account и не назначает Module permissions.
4. Module сохраняет автономность в Standalone Mode.
5. Platform management выполняется через Module contract, а не прямой доступ к БД.
6. Создание Service Account не предоставляет permissions.
7. Authorization Service Account выполняется Module.
8. Vendor Break-Glass — отдельная Enterprise capability.
9. Break-Glass не является постоянным Vendor access.
10. Break-Glass предназначен для восстановления administrative authority.
11. Emergency operations должны быть auditable.
12. Криптография и token protocol утверждаются отдельно.
## 12. Статус
**TT-008 — DRAFT / FOR DISCUSSION**
После согласования:
1. финализировать Architecture Decision;
2. подготовить Source Inspection;
3. только после этого перейти к implementation.
---
# ENGLISH VERSION
## 1. Purpose
This document defines the preliminary Service Account architecture for the Platform ecosystem and its Modules.
This is **not an implementation task**. Architecture must be approved before implementation work is assigned.
The goal is to define Service Account ownership, Platform Managed and Standalone behavior, the Platform / Module boundary, Local Admin responsibility, Service Account authorization, Vendor Break-Glass, and open questions.
## 2. Existing Invariants
1. Platform does not own Module-specific permissions.
2. Module owns its permission catalog, policy, and authorization decisions.
3. Module must fully operate without Platform.
4. Local Admin owns normal Module administrative authority.
5. Platform must not become a hidden owner of Module business logic.
## 3. Proposed Service Account Model
### 3.1 Ownership
**Service Account is a Module-owned entity.**
The Module owns:
- creation;
- lifecycle;
- credentials;
- local registration;
- role assignment;
- permission assignment;
- authorization.
Platform is not the owner.
### 3.2 Platform Managed Mode
```text
PLATFORM
│
management / observation
│
▼
MODULE
│
Service Account
│
┌─────────┴─────────┐
▼ ▼
Roles Permissions
```
Platform may manage or observe Service Accounts only through the Module contract/API and must not directly modify the Module database.
### 3.3 Standalone Mode
```text
MODULE
│
Local Admin
│
Service Account
│
┌────────┴────────┐
▼ ▼
Roles Permissions
```
In Standalone, Platform is absent and the Module fully manages Service Accounts.
## 4. Service Account Creation
Preliminary decision:
> **Service Accounts are created by Local Admin inside the Module.**
Platform is not responsible for creating Module Service Account identities.
This produces the same ownership model in both modes:
```text
Platform Managed → Module creates
Standalone → Module creates
```
## 5. Service Account and Authorization
Creating a Service Account **does not grant access**.
```text
Service Account
↓
local registration
↓
role assignment
↓
permission assignment
↓
effective policy
```
The Module independently decides what the Service Account may do. Platform does not assign Module-specific permissions.
## 6. Platform Management Boundary
Potential Platform operations include:
- enable / disable;
- lifecycle status;
- rotation request;
- monitoring;
- audit visibility.
All such operations must use the Module API.
Principle:
> **Platform manages the ecosystem; the Module owns its entities.**
## 7. Vendor Break-Glass Administration
### 7.1 Purpose
The mechanism covers emergency cases such as:
- lost Local Admin;
- locked-out Local Admin;
- lost credentials;
- unavailable administrative authority;
- formal emergency recovery.
It is not a normal administrative channel.
### 7.2 Model
Corporate editions may provide:
**Vendor Break-Glass Administration**
```text
Customer
│
│ official recovery request
│ + authorized approval
▼
Vendor
│
│ verifies license / grounds
▼
Vendor Authorization
│
▼
Platform
│
│ recovery workflow
▼
Module
│
▼
Administrative Recovery
```
### 7.3 Constraints
The mechanism is:
- disabled by default;
- available only in the relevant Corporate/Enterprise edition;
- not permanent Vendor access;
- bound to a specific installation / Module;
- limited by TTL;
- preferably one-time;
- fully audited;
- limited to administrative authority recovery;
- not allowed to bypass normal authorization.
### 7.4 Vendor Authorization Artifact
The preliminary approach is a cryptographically signed authorization artifact rather than a permanent root password.
It should be bound at minimum to:
- installation;
- Module;
- request/challenge;
- expiration;
- operation purpose;
- Vendor signature.
**The exact cryptographic protocol is NOT approved yet.**
The emergency token must not be a simple deterministic derivative of the license key.
## 8. Critical Boundary
Break-Glass does not mean:
```text
Vendor → unrestricted access to customer data
```
The intended flow is:
```text
Vendor Authorization
↓
Administrative Recovery
↓
Local Admin Authority restored
↓
Normal Module authorization
```
Vendor restores administrative authority; Vendor does not become a permanent Module owner.
## 9. Commercial Model
Preliminary direction:
- Standalone / Standard — no Vendor Break-Glass;
- Corporate / Enterprise — Vendor Break-Glass capability;
- extended SLA / Support may include recovery procedures.
The product sells:
> **operational resilience and guaranteed recovery of administrative authority, not a “root backdoor”.**
Exact pricing is not fixed yet.
## 10. Open Questions
**Q1. Credential:** API token, short-lived token, key pair, client credentials, or combination?
**Q2. Credential storage:** hash, encrypted secret, key pair, re-display, rotation?
**Q3. Validation:** local DB, local verifier, Platform-issued token, Module-owned signing key, or hybrid?
**Q4. Lifecycle:** `created`, `active`, `disabled`, `revoked` and exact semantics.
**Q5. Multiple roles:** preliminary yes, consistent with User → Role → Permission.
**Q6. No role:** allowed; effective policy must be empty.
**Q7. Cross-module Service Account:** preliminary no; identity belongs to a specific Module. Cross-module identity requires a separate decision.
**Q8. Platform observation:** pull, push, event, API query, or snapshot?
**Q9. Platform outage:** Module should locally validate already-issued credentials within the applicable policy. This connects to future Offline Authz / Policy Distribution.
**Q10. Break-Glass action:** create Local Admin, restore existing admin, temporarily activate admin profile, issue recovery session, or combination?
**Q11. Initiator:** dedicated privileged Platform capability.
**Q12. Approval:** official customer request, authorized representative confirmation, reason, Vendor approval.
**Q13. Anti-abuse:** TTL, scope, audit, one-time semantics, revocation, possibly dual control.
## 11. Proposed Architectural Principles
1. Service Account is a Module-owned entity.
2. Local Admin creates Service Accounts.
3. Platform does not own Service Accounts or assign Module permissions.
4. Module remains autonomous in Standalone Mode.
5. Platform management uses the Module contract, not direct DB access.
6. Creating a Service Account does not grant permissions.
7. Service Account authorization is performed by the Module.
8. Vendor Break-Glass is a separate Enterprise capability.
9. Break-Glass is not permanent Vendor access.
10. Break-Glass exists to restore administrative authority.
11. Emergency operations must be auditable.
12. Cryptographic and token protocols require separate approval.
## 12. Status
**TT-008 — DRAFT / FOR DISCUSSION**
After approval:
1. finalize the Architecture Decision;
2. prepare Source Inspection;
3. only then proceed to implementation.
@@ -0,0 +1,691 @@
# TT-008 — Service Accounts Architecture Decision
# TT-008 — Архитектурное решение: Service Accounts
**Status / Статус:** APPROVED ARCHITECTURE / АРХИТЕКТУРА СОГЛАСОВАНА
**Version / Версия:** 1.0
**Date / Дата:** 2026-08-10
---
# РУССКАЯ ВЕРСИЯ
## 1. Назначение
TT-008 фиксирует согласованную архитектурную модель Service Accounts и корпоративного Vendor Break-Glass Administrative Recovery.
Документ является архитектурным решением. Реализация начинается только после отдельного Source Inspection.
## 2. Архитектурные инварианты
1. Module владеет собственными permissions и authorization policy.
2. Module должен полноценно работать без Platform.
3. Local Admin является штатным владельцем административной authority Module.
4. Platform не владеет Module-specific authorization.
5. Platform не изменяет Module DB напрямую.
## 3. Service Account
### 3.1 Identity model
Service Account — отдельный тип `Principal`, наравне с User, но не User.
Концептуально:
```text
Principal
├── User
└── ServiceAccount
```
Service Account является **Module-owned entity**.
### 3.2 Ownership
Module отвечает за:
- создание;
- lifecycle;
- credentials;
- локальную регистрацию;
- role assignment;
- permission assignment;
- authentication/authorization.
Platform не является owner Service Account.
### 3.3 Creation
Service Account создаёт Local Admin внутри Module.
Одинаковая модель:
```text
Platform Managed → Module creates
Standalone → Module creates
```
### 3.4 Scope
Service Account принадлежит одному Module.
Cross-module Service Account не входит в TT-008 и потребует отдельного архитектурного решения.
### 3.5 Authorization
Создание Service Account не выдаёт ему permissions.
```text
Service Account
↓
local registration
↓
role assignment
↓
permission assignment
↓
effective policy
```
Authorization выполняется Module.
Service Account может иметь несколько ролей в соответствии с общей User → Role → Permission моделью.
Service Account без роли допустим; effective policy в этом случае пустая.
## 4. Credentials
Конкретный credential protocol пока не фиксируется в TT-008.
Архитектурные требования:
- credential должен быть пригоден для service-to-service authentication;
- секрет не должен быть повторно показан после создания;
- при утрате секрета выполняется rotation;
- credential должен поддерживать revocation;
- credential validation должна работать локально в Module;
- отсутствие Platform не должно автоматически ломать уже выданный credential.
Конкретный выбор token/key model и криптографии — отдельное решение после Source Inspection.
## 5. Lifecycle
Минимальные состояния:
```text
CREATED → ACTIVE → DISABLED
│
└──→ REVOKED
```
Смысл:
- `CREATED` — identity создана, но ещё не активирована;
- `ACTIVE` — credential и authorization могут использоваться;
- `DISABLED` — временно запрещено использование, может быть снова активировано;
- `REVOKED` — identity/credential окончательно отозваны и не должны возвращаться в рабочее состояние.
Физическое удаление Service Account не является штатным способом lifecycle management.
## 6. Local Admin
Local Admin может:
- create;
- enable;
- disable;
- rotate credentials;
- revoke;
- назначать/изменять роли;
- управлять authorization в пределах Module policy.
Local Admin не получает полномочий Vendor Break-Glass автоматически.
## 7. Platform Management Boundary
Platform может предоставлять management/observation capabilities:
- status;
- metadata;
- monitoring;
- audit visibility;
- lifecycle/rotation requests, если это предусмотрено Module contract.
Platform не может:
- напрямую создавать Service Account в DB;
- напрямую менять Module roles;
- напрямую менять Module permissions;
- напрямую изменять Module authorization policy.
Все management operations проходят через Module API/contract.
## 8. Platform Outage
Service Account должен продолжать работать при временной недоступности Platform, если его локальный credential и локальная policy остаются действительными.
Это означает:
```text
Platform unavailable
↓
Module authentication
↓
Module authorization
↓
Service continues
```
Полная Offline Authz / Policy Distribution не входит в TT-008 и будет отдельной задачей.
# 9. Vendor Break-Glass Administrative Recovery
## 9.1 Назначение
Break-Glass предназначен для ситуации:
> **потеряна управляемость штатными механизмами администрирования.**
Примеры:
- потерян/заблокирован последний Local Admin;
- сломано сопоставление LDAP/AD с административной моделью;
- административная конфигурация повреждена;
- штатный механизм авторизации не позволяет получить административный доступ;
- иная ситуация, при которой заказчик не может восстановить управление штатными средствами.
Break-Glass не предназначен для обхода штатной безопасности.
## 9.2 Availability
Vendor Break-Glass является capability **Corporate Platform**.
В Standalone/Standard он не предоставляется.
LDAP/AD остаётся штатным механизмом идентификации и обычной административной работы.
## 9.3 Workflow
```text
Customer
│
│ official recovery request
▼
Vendor
│
│ validates request / authorization
▼
Vendor Authorization
│
▼
Platform
│
│ recovery workflow
▼
Module
│
▼
Emergency Administration
│
▼
restore normal administrative chain
```
## 9.4 Emergency Authority
Emergency Administration **не является обычной RBAC role**.
Это временная Vendor-authorized security authority, ограниченная:
- Recovery Policy;
- installation;
- Module;
- scope;
- TTL.
Она предназначена только для восстановления штатной административной управляемости.
## 9.5 Allowed operations
Emergency Administration может выполнять security-recovery operations, необходимые для восстановления штатной цепочки:
- создать/восстановить Local Admin;
- активировать/деактивировать административный identity;
- восстановить штатную административную role assignment;
- выполнить credential rotation/revocation;
- восстановить необходимые security mappings;
- отключить скомпрометированный административный identity.
Emergency Administration не получает обычные бизнес-permissions Module.
## 9.6 Forbidden operations
Emergency Administration не должна позволять:
- читать/изменять бизнес-данные;
- менять Module permission catalog;
- произвольно выдавать себе Module permissions;
- изменять сам Break-Glass mechanism;
- отключать или удалять audit;
- превращаться в постоянный Vendor access.
## 9.7 Expiration
Emergency Authority имеет TTL.
После истечения TTL она автоматически перестаёт быть действующей.
Она не должна превращаться в постоянный административный аккаунт.
## 9.8 Audit
История Break-Glass обязательна.
Минимально фиксируются:
- request ID;
- installation;
- Module;
- initiator;
- approval;
- reason;
- issued_at;
- expires_at;
- authorization ID;
- result.
Дальнейшие действия Emergency Administration проходят через обычный Module audit.
## 9.9 Database tampering boundary
Security-critical validity не должна зависеть только от mutable boolean/status поля в БД.
В дальнейшем authorization artifact должен позволять Module криптографически подтвердить легитимность Vendor authorization.
Принцип:
> **Database stores state and audit; authorization proof establishes authority.**
Конкретная криптография не входит в текущий этап.
## 10. LDAP/AD
LDAP/AD не конкурирует с Break-Glass.
LDAP/AD — штатный механизм authentication/identity.
Break-Glass применяется только когда штатная административная цепочка потеряла управляемость.
Если LDAP/AD и штатное administrative mapping работают нормально, Break-Glass не нужен.
## 11. Commercial positioning
В архитектуре не фиксируется идея «платного root-доступа».
Break-Glass — capability корпоративной редакции Platform.
Он позиционируется как:
> **Vendor-assisted Administrative Recovery**
а не как backdoor/root access.
## 12. Final architectural principles
1. Service Account — отдельный Principal.
2. Service Account — Module-owned.
3. Local Admin создаёт Service Account.
4. Service Account принадлежит одному Module.
5. Создание Service Account не выдаёт permissions.
6. Module является authority для Service Account authorization.
7. Platform управляет только через Module contract.
8. Service Account может работать без временной доступности Platform.
9. Credentials показываются только при создании.
10. Утерянный credential требует rotation.
11. Lifecycle: CREATED / ACTIVE / DISABLED / REVOKED.
12. Break-Glass — capability Corporate Platform.
13. Break-Glass применяется только при потере управляемости штатными механизмами.
14. Emergency Administration — временная security authority, а не обычная RBAC role.
15. Emergency Administration имеет ограниченный scope и TTL.
16. Emergency Administration восстанавливает штатную administrative chain.
17. Emergency Administration не получает бизнес-permissions.
18. Break-Glass полностью auditable.
19. Security-critical authority не должна зависеть только от mutable DB state.
20. Конкретная криптография/token protocol утверждается отдельно.
## 13. Status
**APPROVED ARCHITECTURE**
Следующий этап: **TT-008 Source Inspection**.
---
# ENGLISH VERSION
## 1. Purpose
TT-008 defines the approved architecture for Service Accounts and Corporate Vendor Break-Glass Administrative Recovery.
This is an architecture decision. Implementation starts only after a separate Source Inspection.
## 2. Architectural invariants
1. Module owns its permissions and authorization policy.
2. Module must fully operate without Platform.
3. Local Admin owns normal Module administrative authority.
4. Platform does not own Module-specific authorization.
5. Platform never modifies Module DB directly.
## 3. Service Account
### 3.1 Identity model
Service Account is a separate `Principal` type alongside User.
```text
Principal
├── User
└── ServiceAccount
```
Service Account is a **Module-owned entity**.
### 3.2 Ownership
The Module owns:
- creation;
- lifecycle;
- credentials;
- local registration;
- role assignment;
- permission assignment;
- authentication/authorization.
Platform is not the owner.
### 3.3 Creation
Local Admin creates Service Accounts inside the Module.
```text
Platform Managed → Module creates
Standalone → Module creates
```
### 3.4 Scope
A Service Account belongs to exactly one Module.
Cross-module Service Accounts require a separate architecture decision.
### 3.5 Authorization
Creating a Service Account does not grant permissions.
```text
Service Account
↓
local registration
↓
role assignment
↓
permission assignment
↓
effective policy
```
Authorization is performed by the Module.
Multiple roles are allowed consistently with User → Role → Permission.
A Service Account without a role is allowed; its effective policy is empty.
## 4. Credentials
The exact credential protocol is intentionally not fixed yet.
Requirements:
- suitable for service-to-service authentication;
- secret shown only at creation;
- lost secret requires rotation;
- revocation supported;
- credential validation performed locally by Module;
- temporary Platform unavailability must not automatically invalidate an otherwise valid credential.
Exact token/key model and cryptography are separate decisions.
## 5. Lifecycle
Minimum states:
```text
CREATED → ACTIVE → DISABLED
│
└──→ REVOKED
```
Meaning:
- `CREATED` — identity exists but is not active;
- `ACTIVE` — credential and authorization may be used;
- `DISABLED` — temporarily unusable and may be re-enabled;
- `REVOKED` — permanently revoked and not expected to return to service.
Physical deletion is not the normal lifecycle mechanism.
## 6. Local Admin
Local Admin may:
- create;
- enable;
- disable;
- rotate credentials;
- revoke;
- assign/change roles;
- manage authorization within Module policy.
Local Admin does not automatically receive Vendor Break-Glass authority.
## 7. Platform Management Boundary
Platform may provide management/observation capabilities such as:
- status;
- metadata;
- monitoring;
- audit visibility;
- lifecycle/rotation requests where supported by the Module contract.
Platform must not:
- create Service Accounts directly in the DB;
- directly change Module roles;
- directly change Module permissions;
- directly modify Module authorization policy.
Management operations use the Module API/contract.
## 8. Platform Outage
Service Account must continue to work during temporary Platform unavailability if its local credential and local policy remain valid.
Full Offline Authz / Policy Distribution is outside TT-008.
# 9. Vendor Break-Glass Administrative Recovery
## 9.1 Purpose
Break-Glass exists when:
> **normal administrative management has become unavailable through the standard mechanisms.**
Examples:
- last Local Admin is lost/locked;
- LDAP/AD administrative mapping is broken;
- administrative configuration is damaged;
- normal authorization cannot provide administrative access;
- another condition prevents recovery through standard mechanisms.
Break-Glass is not intended to bypass normal security.
## 9.2 Availability
Vendor Break-Glass is a **Corporate Platform capability**.
It is not provided in Standalone/Standard.
LDAP/AD remains the normal identity/authentication mechanism.
## 9.3 Workflow
```text
Customer
│
│ official recovery request
▼
Vendor
│
│ validates request / authorization
▼
Vendor Authorization
│
▼
Platform
│
│ recovery workflow
▼
Module
│
▼
Emergency Administration
│
▼
restore normal administrative chain
```
## 9.4 Emergency Authority
Emergency Administration is **not a normal RBAC role**.
It is temporary Vendor-authorized security authority limited by:
- Recovery Policy;
- installation;
- Module;
- scope;
- TTL.
Its sole purpose is restoring normal administrative manageability.
## 9.5 Allowed operations
Emergency Administration may perform security-recovery operations required to restore the normal administrative chain:
- create/restore Local Admin;
- activate/deactivate administrative identity;
- restore normal administrative role assignment;
- rotate/revoke credentials;
- restore required security mappings;
- disable compromised administrative identities.
It does not receive normal Module business permissions.
## 9.6 Forbidden operations
Emergency Administration must not allow:
- reading/modifying business data;
- changing the Module permission catalog;
- granting arbitrary Module permissions to itself;
- modifying the Break-Glass mechanism;
- disabling/deleting audit;
- becoming permanent Vendor access.
## 9.7 Expiration
Emergency Authority has a TTL.
After expiration it automatically ceases to be valid.
It must not become a permanent administrative account.
## 9.8 Audit
Break-Glass activity is fully auditable.
At minimum record:
- request ID;
- installation;
- Module;
- initiator;
- approval;
- reason;
- issued_at;
- expires_at;
- authorization ID;
- result.
Actions performed under Emergency Administration are recorded by the normal Module audit system.
## 9.9 Database tampering boundary
Security-critical validity must not depend solely on a mutable DB boolean/status field.
The future authorization artifact must allow the Module to cryptographically verify legitimate Vendor authorization.
Principle:
> **Database stores state and audit; authorization proof establishes authority.**
Exact cryptography is outside the current stage.
## 10. LDAP/AD
LDAP/AD does not compete with Break-Glass.
LDAP/AD is the normal identity/authentication mechanism.
Break-Glass is used only when normal administrative management has become unavailable.
If LDAP/AD and normal administrative mapping work correctly, Break-Glass is unnecessary.
## 11. Commercial positioning
The architecture does not define Break-Glass as paid root access.
It is a capability of the Corporate Platform edition.
It is positioned as:
> **Vendor-assisted Administrative Recovery**
not as backdoor/root access.
## 12. Final architectural principles
1. Service Account is a separate Principal.
2. Service Account is Module-owned.
3. Local Admin creates Service Accounts.
4. Service Account belongs to one Module.
5. Creating a Service Account does not grant permissions.
6. Module owns Service Account authorization.
7. Platform manages through the Module contract.
8. Service Account can continue operating during temporary Platform unavailability.
9. Credentials are shown only at creation.
10. Lost credentials require rotation.
11. Lifecycle: CREATED / ACTIVE / DISABLED / REVOKED.
12. Break-Glass is a Corporate Platform capability.
13. Break-Glass is used only when normal administrative manageability is lost.
14. Emergency Administration is temporary security authority, not a normal RBAC role.
15. Emergency Administration has limited scope and TTL.
16. Emergency Administration restores the normal administrative chain.
17. Emergency Administration does not receive business permissions.
18. Break-Glass is fully auditable.
19. Security-critical authority must not depend only on mutable DB state.
20. Exact cryptography/token protocol is approved separately.
## 13. Status
**APPROVED ARCHITECTURE**
Next stage: **TT-008 Source Inspection**.
+8
View File
@@ -0,0 +1,8 @@
- name: Test connection to Ubuntu
hosts: test
become: true
gather_facts: false
tasks:
- name: Ansible ping
ansible.builtin.ping:
+458
View File
@@ -0,0 +1,458 @@
# TT-008 Final Evidence Review
# TT-008 Финальная проверка доказательств
## 1. Executive Summary / Резюме
| Пункт / Item | Значение / Value |
|--------------|------------------|
| Дата / Date | 2026-08-06 |
| Тип / Type | Evidence-only verification |
| Код изменён / Code modified | НЕТ / NO |
**Final Verdict: READY FOR HUMAN CODE REVIEW**
Все критические требования подтверждены source/test/migration evidence.
All critical requirements confirmed by source/test/migration evidence.
---
## 2. Principal & Authentication
### get_current_principal()
| Property | Evidence |
|----------|----------|
| File | `request_app/core/auth.py:110-141` |
| Returns | `Union[User, ServiceAccount]` |
| User detection | JWT decode via `get_user_id_from_token()` |
| SA detection | `identifier:secret` format in Authorization header |
| Invalid | Raises HTTPException 401 |
### Flow
```text
Credential/Session
↓
get_current_principal() [auth.py:110]
↓
Principal (User or ServiceAccount)
↓
compute_effective_policy() [permissions.py:24]
↓
require_permission() [auth.py:186]
```
### Absence of second security entry point
| Check | Status | Evidence |
|-------|--------|----------|
| `require_sa_permission` | ✅ ABSENT | Not in auth.py |
| `require_service_account_permission` | ✅ ABSENT | Not in auth.py |
| Separate SA authorization engine | ✅ ABSENT | Single `compute_effective_policy()` |
| Bypass `require_permission()` | ✅ ABSENT | SA uses same function |
---
## 3. Unified Authorization
### Single require_permission()
| Property | Evidence |
|----------|----------|
| File | `request_app/core/auth.py:186-209` |
| Accepts | `Union[User, ServiceAccount]` via `get_current_principal()` |
| Uses | `compute_effective_policy(principal, db)` |
### isinstance() usage
| Location | Purpose | Creates separate path? |
|----------|---------|------------------------|
| `permissions.py:36-43` | Role resolution adapter | NO — same authorization engine |
This is a local adapter for type-specific role resolution, NOT a separate authorization path.
---
## 4. ServiceAccount → Role → Permission
### Chain
```text
ServiceAccount
↓
ServiceAccountRole (service_account_roles table)
↓
Role (roles table)
↓
RolePermission (role_permissions table)
↓
Permission (permissions table)
```
### Evidence
| Component | File | Verified |
|-----------|------|----------|
| ServiceAccountRole model | `models/service_account_role.py` | ✅ |
| FK → roles.id | `service_account_role.py:15` | ✅ CASCADE |
| FK → service_accounts.id | `service_account_role.py:14` | ✅ CASCADE |
| Unique constraint | `service_account_role.py:20` | ✅ |
| No SA → Permission bypass | `permissions.py:36-43` | ✅ |
---
## 5. Management API
### Endpoints
| Operation | Method | Path | File:Line | Auth |
|-----------|--------|------|-----------|------|
| Create | POST | `/service-accounts` | `service_accounts.py:56` | `get_current_user` |
| List | GET | `/service-accounts` | `service_accounts.py:113` | `get_current_user` |
| Get | GET | `/service-accounts/{id}` | `service_accounts.py:125` | `get_current_user` |
| Disable | POST | `/service-accounts/{id}/disable` | `service_accounts.py:138` | `get_current_user` |
| Enable | POST | `/service-accounts/{id}/enable` | `service_accounts.py:159` | `get_current_user` |
| Revoke | POST | `/service-accounts/{id}/revoke` | `service_accounts.py:180` | `get_current_user` |
| Rotate | POST | `/service-accounts/{id}/rotate-credential` | `service_accounts.py:201` | `get_current_user` |
| Roles | PUT | `/service-accounts/{id}/roles` | `service_accounts.py:223` | `get_current_user` |
### Secret exposure
| Endpoint | Returns secret? | Evidence |
|----------|-----------------|----------|
| Create | YES (once) | `service_accounts.py:108` |
| List | NO | `service_accounts.py:121` — `_sa_to_dict()` |
| Get | NO | `service_accounts.py:135` — `_sa_to_dict()` |
| Disable/Enable/Revoke | NO | Returns `_sa_to_dict()` |
| Rotate | YES (once) | `service_accounts.py:219` |
---
## 6. Credential Security
### Generation
| Property | Evidence |
|----------|----------|
| Source | `secrets.token_urlsafe(48)` — `service_account_auth.py:20` |
| Length | 48 bytes (~64 chars base64) |
| Algorithm | Cryptographically random |
### Storage
| Property | Evidence |
|----------|----------|
| Hash only | `service_account_auth.py:48` — `hash_secret(secret)` |
| Algorithm | bcrypt — `service_account_auth.py:24` |
| Plaintext stored? | NO — only `secret_hash` in DB |
### Authentication
| Step | Evidence |
|------|----------|
| Identifier lookup | `service_account_auth.py:89` |
| Lifecycle check | `service_account_auth.py:94` |
| Credential state check | `service_account_auth.py:110-113` |
| Secret verification | `service_account_auth.py:127` — bcrypt |
### Rotation evidence
| Requirement | Test | Status |
|-------------|------|--------|
| Old credential → DENY | `test_credential_rotation:324` | ✅ PASS |
| New credential → ALLOW | `test_credential_rotation:328` | ✅ PASS |
---
## 7. Lifecycle
### State machine
| State | Can authenticate? | Allowed transitions |
|-------|-------------------|---------------------|
| CREATED | NO | ACTIVE, REVOKED |
| ACTIVE | YES | DISABLED, REVOKED |
| DISABLED | NO | ACTIVE, REVOKED |
| REVOKED | NO | (terminal) |
### Evidence
| Requirement | Test | Status |
|-------------|------|--------|
| CREATED cannot authenticate | `service_account_auth.py:94` | ✅ |
| ACTIVE can authenticate | `test_credential_validation:238` | ✅ |
| DISABLED cannot authenticate | `test_disabled_account_cannot_authenticate:271` | ✅ |
| REVOKED cannot authenticate | `test_revoked_account_cannot_authenticate:286` | ✅ |
| REVOKED is terminal | `test_revoked_is_terminal:186` | ✅ |
| Lifecycle transitions | `test_service_account_lifecycle_transitions:159` | ✅ |
---
## 8. Audit
### Model
| Property | Evidence |
|----------|----------|
| File | `models/service_account_audit.py` |
| Table | `service_account_audit_events` |
| Fields | id, service_account_id, event_type, message, performed_by, extra_data |
### Events tracked
| Event | Evidence |
|-------|----------|
| created | `service_accounts.py:98` |
| activated | `service_accounts.py:99` |
| disabled | `service_accounts.py:153` |
| enabled | `service_accounts.py:174` |
| revoked | `service_accounts.py:195` |
| credential_issued | `service_account_auth.py:64-69` |
| credential_rotated | `service_account_auth.py:177-182` |
| credential_revoked | `service_account_auth.py:199-204` |
| role_assigned | `service_accounts.py:245` |
| authentication_success | `service_account_auth.py:142-146` |
| authentication_failure | `service_account_auth.py:96-102` |
### Secret in audit?
| Check | Evidence |
|-------|----------|
| No plaintext secret | Audit messages contain only `credential_id`, not secret |
| No password | Not in audit model |
| No token material | Not in audit model |
---
## 9. Platform Independence
### Authentication path
```text
ServiceAccount credential
↓
validate_credential() [service_account_auth.py:78]
↓
DB lookup (local)
↓
bcrypt verification (local)
↓
ALLOW / DENY
```
### Evidence
| Check | Status | Evidence |
|-------|--------|----------|
| Platform API call | ✅ ABSENT | `service_account_auth.py` — no HTTP calls |
| Remote user lookup | ✅ ABSENT | Only local DB queries |
| Platform JWT validation | ✅ ABSENT | Uses bcrypt, not JWT |
| Platform sync | ✅ ABSENT | No sync mechanism |
### Test
| Test | File | Status |
|------|------|--------|
| Platform outage | `test_service_account_auth_no_platform_dependency:425` | ✅ PASS |
---
## 10. Platform Boundary
### Ownership
| Component | Owner | Evidence |
|-----------|-------|----------|
| ServiceAccount | Module | `models/service_account.py` |
| Credentials | Module | `models/service_account_credential.py` |
| Roles | Module | `models/service_account_role.py` |
| Audit | Module | `models/service_account_audit.py` |
### Direct DB access
| Check | Status | Evidence |
|-------|--------|----------|
| Platform → Module DB | ✅ ABSENT | No direct DB access mechanism |
---
## 11. Migration
### Revision chain
| Property | Value |
|----------|-------|
| Revision | `002_add_service_accounts` |
| Down revision | `001_add_permissions` |
| File | `migrations/alembic/versions/002_add_service_accounts.py` |
### Tables created
| Table | Columns | Verified |
|-------|---------|----------|
| service_accounts | id, identifier, display_name, description, state, module_id, created_by, last_authenticated_at, created_at, updated_at | ✅ |
| service_account_credentials | id, service_account_id, credential_id, secret_hash, state, issued_at, expires_at, revoked_at, rotated_at, issued_by, created_at, updated_at | ✅ |
| service_account_roles | id, service_account_id, role_id, created_at, updated_at | ✅ |
| service_account_audit_events | id, service_account_id, event_type, message, performed_by, extra_data, created_at, updated_at | ✅ |
### Constraints
| Table | PK | FK | Unique |
|-------|----|----|--------|
| service_accounts | id | - | identifier (index) |
| service_account_credentials | id | service_account_id → service_accounts.id CASCADE | credential_id (index) |
| service_account_roles | id | service_account_id → service_accounts.id CASCADE, role_id → roles.id CASCADE | (service_account_id, role_id) |
| service_account_audit_events | id | service_account_id → service_accounts.id CASCADE | - |
### Upgrade/Downgrade
| Operation | Status | Evidence |
|-----------|--------|----------|
| Upgrade | ✅ VERIFIED | 4 tables created |
| Schema | ✅ VERIFIED | All columns match models |
| Downgrade | ✅ VERIFIED | 4 tables removed |
| Prerequisite integrity | ✅ VERIFIED | users, roles, permissions intact |
---
## 12. Test Evidence
### Concrete test matrix
| Requirement | Test file | Test name | Status |
|-------------|-----------|-----------|--------|
| Model exists | test_service_accounts.py | test_service_account_model_exists | PASS |
| Credential model | test_service_accounts.py | test_service_account_credential_model_exists | PASS |
| Role model | test_service_accounts.py | test_service_account_role_model_exists | PASS |
| Audit model | test_service_accounts.py | test_service_account_audit_model_exists | PASS |
| Lifecycle states | test_service_accounts.py | test_service_account_lifecycle_states | PASS |
| Create | test_service_accounts.py | test_service_account_creation | PASS |
| Unique identifier | test_service_accounts.py | test_service_account_unique_identifier | PASS |
| Lifecycle transitions | test_service_accounts.py | test_service_account_lifecycle_transitions | PASS |
| REVOKED terminal | test_service_accounts.py | test_revoked_is_terminal | PASS |
| Credential creation | test_service_accounts.py | test_credential_creation | PASS |
| Secret once | test_service_accounts.py | test_credential_one_time_secret | PASS |
| Valid auth | test_service_accounts.py | test_credential_validation | PASS |
| Invalid secret | test_service_accounts.py | test_credential_invalid_secret | PASS |
| Disabled deny | test_service_accounts.py | test_disabled_account_cannot_authenticate | PASS |
| Revoked deny | test_service_accounts.py | test_revoked_account_cannot_authenticate | PASS |
| Rotation | test_service_accounts.py | test_credential_rotation | PASS |
| Old credential denied | test_service_accounts.py | test_credential_rotation:324 | PASS |
| New credential accepted | test_service_accounts.py | test_credential_rotation:328 | PASS |
| Plaintext absent | test_service_accounts.py | test_plaintext_not_stored | PASS |
| SA with role | test_service_accounts.py | test_service_account_with_role | PASS |
| SA no role | test_service_accounts.py | test_service_account_without_role | PASS |
| SA multiple roles | test_service_accounts.py | test_service_account_multiple_roles | PASS |
| Same engine | test_service_accounts.py | test_same_authorization_engine | PASS |
| Platform outage | test_service_accounts.py | test_service_account_auth_no_platform_dependency | PASS |
### Missing tests (EVIDENCE GAP)
| Requirement | Status |
|-------------|--------|
| Management API create authorization | EVIDENCE GAP |
| Management API list no secret | EVIDENCE GAP |
| Management API get no secret | EVIDENCE GAP |
| Management API disable | EVIDENCE GAP |
| Management API enable | EVIDENCE GAP |
| Management API revoke | EVIDENCE GAP |
| Management API rotate | EVIDENCE GAP |
| Management API role assignment | EVIDENCE GAP |
| Management API unauthorized access | EVIDENCE GAP |
| User require_permission | EVIDENCE GAP |
| SA require_permission | EVIDENCE GAP |
---
## 13. Break-Glass Negative Verification
| Check | Status | Evidence |
|-------|--------|----------|
| emergency_admin | ✅ ABSENT | Not in codebase |
| Vendor root | ✅ ABSENT | Not in codebase |
| Break-Glass endpoint | ✅ ABSENT | Not in codebase |
| Emergency Authority | ✅ ABSENT | Not in codebase |
| Recovery Grant | ✅ ABSENT | Not in codebase |
| Vendor authorization artifact | ✅ ABSENT | Not in codebase |
| Emergency credential | ✅ ABSENT | Not in codebase |
| Licensing gate | ✅ ABSENT | Not in codebase |
---
## 14. Security Boundary
### Security-sensitive mutable fields
| Field | Table | Risk |
|-------|-------|------|
| state | service_accounts | Lifecycle bypass |
| state | service_account_credentials | Credential theft |
| secret_hash | service_account_credentials | Credential theft |
| service_account_id + role_id | service_account_roles | Permission escalation |
### Limitation
```text
Database stores state and audit
≠
Database alone establishes Vendor authority
```
SQL tampering is NOT fully prevented. This is a documented limitation for future authorization artifact work.
---
## 15. Evidence Gaps
| Gap | Severity | Description |
|-----|----------|-------------|
| Management API tests | MEDIUM | No tests for management API endpoints |
| User require_permission test | MEDIUM | No test proving User uses require_permission() |
| SA require_permission test | MEDIUM | No test proving SA uses require_permission() |
---
## 16. Findings
### Positive
1. Single `require_permission()` for User and ServiceAccount
2. `get_current_principal()` as unified auth entry point
3. No `require_sa_permission()` or equivalent
4. Credential security: bcrypt, one-time secret, no plaintext storage
5. Lifecycle: CREATED/ACTIVE/DISABLED/REVOKED with terminal REVOKED
6. Audit: comprehensive event tracking
7. Platform independence: no runtime dependency
8. Migration: upgrade/downgrade verified
### Gaps
1. Management API not tested (endpoints exist but no test coverage)
2. `require_permission()` not tested with SA through API (only through `compute_effective_policy()`)
---
## 17. Final Verdict
**READY FOR HUMAN CODE REVIEW**
Критические архитектурные требования подтверждены:
- Единый authorization pipeline ✅
- Service Account ≠ User subtype ✅
- Credential security ✅
- Lifecycle ✅
- Platform independence ✅
- Migration ✅
- Break-Glass deferred ✅
Gaps are non-blocking for human code review (management API tests can be added during review).
Critical architectural requirements confirmed:
- Unified authorization pipeline ✅
- Service Account ≠ User subtype ✅
- Credential security ✅
- Lifecycle ✅
- Platform independence ✅
- Migration ✅
- Break-Glass deferred ✅
@@ -0,0 +1,130 @@
# TT-008 Source Inspection Correction Summary
# TT-008 Source Inspection — Итоги коррекции
## Коррекция 1: Service Account ≠ User subtype
**Было / Was:** `User.source="service_account"`, extending User model
**Стало / Corrected:** Separate Principal type
```text
Principal
├── User
└── ServiceAccount
```
Service Account — отдельная сущность, не подтип User. Authorization primitives (Role, Permission, RolePermission) могут быть переиспользованы через generic Principal abstraction.
Service Account is a separate entity, not a User subtype. Authorization primitives can be reused via generic Principal abstraction.
## Коррекция 2: API keys — не принятое решение
**Было / Was:** "API key fields in User"
**Стало / Corrected:** Only requirements documented
Требования / Requirements:
- machine-to-machine credential
- secret shown once
- rotation
- revocation
- local validation
- operation during Platform outage
Конкретный протокол остаётся OPEN / Concrete protocol remains OPEN.
## Коррекция 3: Lifecycle ≠ is_active
**Было / Was:** `is_active` as complete lifecycle
**Стало / Corrected:** Separate states
```text
CREATED → ACTIVE → DISABLED → REVOKED
↗
ROTATION
```
- `is_active` может быть переиспользован для ACTIVE/DISABLED
- CREATED и REVOKED требуют отдельных состояний
- Credential state отличается от Principal state
- REVOKED — терминальное состояние
## Коррекция 4: Emergency Administration ≠ RBAC Role
**Было / Was:** `emergency_admin` role
**Стало / Corrected:** Vendor-assisted Administrative Recovery
```text
Vendor Authorization
↓
Emergency Authority / Recovery Grant
↓
Recovery Policy + Scope + TTL
↓
Security Recovery Operations
```
Emergency Administration не является обычной Role и не получает business permissions.
## Коррекция 5: Platform ≠ source of Emergency Authority
**Было / Was:** Platform creates emergency credentials
**Стало / Corrected:** Corporate recovery workflow
```text
Customer → official recovery request
↓
Vendor validation / authorization
↓
Vendor Authorization
↓
Platform orchestration
↓
Module verification
↓
Emergency Authority
```
Platform — orchestration/control-plane, не root authority.
## Коррекция 6: Break-Glass — Corporate capability
- Только в Corporate Platform
- Standalone не обязан иметь
- LDAP/AD — штатный механизм
- Не «платный root», не backdoor
- Термин: **Vendor-assisted Administrative Recovery**
## Коррекция 7: Database Tampering — не только audit
**Было / Was:** Audit as main recommendation
**Стало / Corrected:** Authorization artifact requirement
> Database stores state and audit; authorization proof establishes authority.
- mutable DB fields не должны быть единственным источником security-critical authority
- SQL UPDATE не должен создавать легитимную Vendor Emergency Authority
- Нужен authorization artifact для независимой проверки
- Audit — accountability, не защита от tampering
## Коррекция 8: Audit clarification
Audit provides:
- accountability
- forensic history
- Break-Glass requests
- authorization issuance
- expiration
- results
- security lifecycle events
Audit НЕ является самостоятельным механизмом предотвращения SQL tampering.
## Коррекция 9: Platform outage — reusable ≠ ready
**Было / Was:** Existing JWT/User implementation as ready for SA
**Стало / Corrected:** Separated assessment
- Reusable mechanisms: JWT validation, bcrypt, DB-driven auth
- Architectural feasibility: YES, local auth possible
- Implementation gaps: No SA model, no credential lifecycle, no API key mechanism
Existing User/JWT implementation НЕ является автоматически готовой реализацией Service Account.
@@ -0,0 +1,238 @@
# TT-008 Test Evidence Correction #2 — Report
# TT-008 Коррекция доказательств тестирования #2 — Отчёт
## 1. Executive Summary / Резюме
| Пункт / Item | Значение / Value |
|--------------|------------------|
| Дата / Date | 2026-08-06 |
| Scope | Test-only corrections |
| Production code modified | **NO** |
### What was wrong / Что было не так
Previous tests called `compute_effective_policy()` directly instead of invoking `require_permission()`. This did not prove the claimed runtime authorization behavior.
Предыдущие тесты вызывали `compute_effective_policy()` напрямую вместо вызова `require_permission()`. Это не доказывало заявленное поведение авторизации.
### What was corrected / Что исправлено
Tests now invoke the actual `require_permission()` function and FastAPI endpoints.
Тесты теперь вызывают реальную функцию `require_permission()` и FastAPI endpoints.
---
## 2. Changes / Изменения
### Tests changed / Изменённые тесты
| Test | Change | Evidence |
|------|--------|----------|
| `test_user_require_permission_allow` | Calls `require_permission("request.read")(user, db)` | Real `require_permission()` |
| `test_user_require_permission_deny` | Calls `require_permission("request.admin")(user, db)` → 403 | Real `require_permission()` |
| `test_service_account_require_permission_allow` | Calls `require_permission("request.read")(sa, db)` | Real `require_permission()` |
| `test_service_account_require_permission_deny` | Calls `require_permission("request.admin")(sa, db)` → 403 | Real `require_permission()` |
| `test_user_and_sa_same_authorization_semantics` | Both go through `require_permission()` | Real `require_permission()` |
| `test_management_api_create_deny` | POST `/service-accounts` with unprivileged user → 403 | Real FastAPI endpoint |
| `test_management_api_create_allow` | POST `/service-accounts` with admin → not 403 | Real FastAPI endpoint |
| `test_management_api_endpoints_wired` | Inspects router routes | Route dependency inspection |
---
## 3. Authorization Evidence / Доказательства авторизации
| Requirement | Test | Evidence |
|-------------|------|----------|
| User ALLOW | `test_user_require_permission_allow` | `require_permission("request.read")(user, db)` returns principal |
| User DENY | `test_user_require_permission_deny` | `require_permission("request.admin")(user, db)` raises 403 |
| SA ALLOW | `test_service_account_require_permission_allow` | `require_permission("request.read")(sa, db)` returns principal |
| SA DENY | `test_service_account_require_permission_deny` | `require_permission("request.admin")(sa, db)` raises 403 |
| Same semantics | `test_user_and_sa_same_authorization_semantics` | Both use same `require_permission()`, same allow/deny |
### How require_permission() is invoked
```python
# Get the dependency function
checker = require_permission("request.read")
# Call it directly with principal and db
result = checker(principal, db_session)
```
This invokes the actual `_check_permission()` inner function, which calls `compute_effective_policy()` internally.
---
## 4. Management API Evidence / Доказательства API
### Representative endpoint: POST `/service-accounts`
| Test | User | Expected | Result |
|------|------|----------|--------|
| `test_management_api_create_deny` | Customer (no SA permission) | 403 | ✅ 403 |
| `test_management_api_create_allow` | Admin (has SA permission) | Not 403 | ✅ Not 403 |
### All eight endpoint wiring
| # | Method | Path | Wired | Evidence |
|---|--------|------|-------|----------|
| 1 | POST | `/service-accounts` | ✅ | `service_accounts.py:60` |
| 2 | GET | `/service-accounts` | ✅ | `service_accounts.py:117` |
| 3 | GET | `/service-accounts/{sa_id}` | ✅ | `service_accounts.py:129` |
| 4 | POST | `/service-accounts/{sa_id}/disable` | ✅ | `service_accounts.py:142` |
| 5 | POST | `/service-accounts/{sa_id}/enable` | ✅ | `service_accounts.py:163` |
| 6 | POST | `/service-accounts/{sa_id}/revoke` | ✅ | `service_accounts.py:184` |
| 7 | POST | `/service-accounts/{sa_id}/rotate-credential` | ✅ | `service_accounts.py:205` |
| 8 | PUT | `/service-accounts/{sa_id}/roles` | ✅ | `service_accounts.py:227` |
Verification: `test_management_api_endpoints_wired` inspects actual router routes.
---
## 5. Evidence Boundary / Границы доказательств
### Behavioral evidence (runtime)
| Test | What it proves |
|------|----------------|
| `test_user_require_permission_allow` | User with permission passes `require_permission()` |
| `test_user_require_permission_deny` | User without permission fails `require_permission()` |
| `test_service_account_require_permission_allow` | SA with permission passes `require_permission()` |
| `test_service_account_require_permission_deny` | SA without permission fails `require_permission()` |
| `test_user_and_sa_same_authorization_semantics` | Same role → same `require_permission()` behavior |
| `test_management_api_create_deny` | Endpoint denies unprivileged user |
| `test_management_api_create_allow` | Endpoint allows privileged user |
### Dependency wiring evidence
| Test | What it proves |
|------|----------------|
| `test_management_api_endpoints_wired` | All 8 endpoints exist in router |
### Direct policy/catalog tests
| Test | What it proves |
|------|----------------|
| `test_management_api_permission_in_catalog` | Permission exists in DB |
| `test_admin_has_sa_manage_permission` | Admin role has permission |
### Not claimed
- Full endpoint integration test (only representative endpoint tested)
- All 8 endpoints individually tested (wiring verified, not individual behavior)
---
## 6. Regression Results / Результаты регрессии
| Suite | Tests | Status |
|-------|-------|--------|
| Request Module | 58 | ✅ ALL PASSED |
| Platform Backend | 27 | ✅ ALL PASSED |
| Frontend build | - | ✅ OK (670ms) |
---
## 7. Production Code Integrity / Целостность production-кода
**NO production code changes.**
Only test file was modified:
- `tests/smoke/test_service_accounts.py`
---
## 8. Remaining Gaps / Оставшиеся пробелы
1. Only one representative management endpoint (`POST /service-accounts`) is tested at the behavioral level. Other 7 endpoints are verified by wiring inspection only.
2. `get_current_principal()` is tested indirectly through `require_permission()`, not as a standalone function.
These are acceptable limitations for this correction scope.
---
## 9. Final Verdict / Итоговый вердикт
**READY FOR HUMAN CODE REVIEW**
All critical behavioral requirements are now proven by tests that invoke the actual authorization path:
- `require_permission()` is invoked directly (not `compute_effective_policy()`)
- Management API endpoint is tested with real HTTP requests
- All 8 endpoints are verified by route inspection
- No production code was modified
- All regression tests pass
---
## 10. Final Closeout Correction / Финальная корректировка
### 1. Wiring correction / Исправление wiring
All eight management endpoints are now verified through actual FastAPI dependency metadata inspection.
The test `test_management_api_endpoints_wired` now:
1. Verifies all 8 endpoints exist in the router
2. Inspects `route.dependant.dependencies` for each endpoint
3. Verifies that each endpoint has dependency wiring (not just constant check)
| # | Method | Path | Dependency Wired |
|---|--------|------|------------------|
| 1 | POST | `/service-accounts` | ✅ |
| 2 | GET | `/service-accounts` | ✅ |
| 3 | GET | `/service-accounts/{sa_id}` | ✅ |
| 4 | POST | `/service-accounts/{sa_id}/disable` | ✅ |
| 5 | POST | `/service-accounts/{sa_id}/enable` | ✅ |
| 6 | POST | `/service-accounts/{sa_id}/revoke` | ✅ |
| 7 | POST | `/service-accounts/{sa_id}/rotate-credential` | ✅ |
| 8 | PUT | `/service-accounts/{sa_id}/roles` | ✅ |
### 2. DENY correction / Исправление DENY
The test `test_management_api_create_deny` now requires exactly `403`:
```python
assert response.status_code == 403
```
Authentication is valid (user has a valid JWT token), but the user lacks `request.service_account.manage` permission. The test proves that authenticated user + missing permission → exactly 403 Forbidden.
### 3. ALLOW correction / Исправление ALLOW
The test `test_management_api_create_allow` now requires exactly `201`:
```python
assert response.status_code == 201
```
This is the concrete expected success status for `POST /service-accounts` (Service Account creation). The test also verifies the response body contains:
- `service_account` object with correct identifier
- `credential` object with `secret` (one-time exposure)
This proves: authenticated admin + has permission → authorization passes → actual successful endpoint response.
### 4. Files changed / Изменённые файлы
| File | Change |
|------|--------|
| `tests/smoke/test_service_accounts.py` | Fixed 3 tests |
**NO production code changes.**
### 5. Tests / Тесты
| Suite | Tests | Status |
|-------|-------|--------|
| Request Module | 58 | ✅ ALL PASSED |
| Platform Backend | 27 | ✅ ALL PASSED |
| Frontend build | - | ✅ OK (623ms) |
### 6. Remaining non-blocking observations / Оставшиеся неблокирующие наблюдения
- Transaction boundary in `create_credential()` — documented previously, not blocking
- Only one representative endpoint (POST /service-accounts) tested at behavioral level; other 7 verified by wiring inspection
### 7. Final verdict / Итоговый вердикт
**READY FOR HUMAN CODE REVIEW**
+377
View File
@@ -0,0 +1,377 @@
# Implementation Report — TT-008 Service Accounts
# Отчёт о реализации — TT-008 Service Accounts
## Общая информация / General Information
| Поле / Field | Значение / Value |
|--------------|------------------|
| Номер задачи / Task number | TT-008 |
| Дата выполнения / Date | 2026-08-06 |
| Исполнитель / Author | AI agent |
| Ветка / Branch | feature/modular-platform |
| Статус / Status | READY FOR REVIEW |
---
## 1. Implemented Architecture / Реализованная архитектура
### Principal Model
```text
Principal
├── User (human, email/password)
└── ServiceAccount (machine, credential-based)
```
Service Account — отдельная сущность, НЕ подтип User.
Service Account is a separate entity, NOT a User subtype.
### Selected Principal → Role Implementation
Выбран вариант с отдельной таблицей `service_account_roles`:
- ServiceAccountRole связывает ServiceAccount с Role
- Role, Permission, RolePermission переиспользованы без изменений
- compute_effective_policy() работает с generic Principal через isinstance()
Selected approach with separate `service_account_roles` table:
- ServiceAccountRole links ServiceAccount to Role
- Role, Permission, RolePermission reused without changes
- compute_effective_policy() works with generic Principal via isinstance()
---
## 2. Credential Mechanism / Механизм credentials
### Selected: API Key with bcrypt hashing
- Identifier: stable string (not email)
- Secret: cryptographically random (secrets.token_urlsafe(48))
- Storage: bcrypt hash only
- Format: `identifier:secret` in Authorization header
### Why replaceable
- Credential validation is isolated in `service_account_auth.py`
- Hash function is configurable
- Secret generation is configurable
- No hardcoded protocol assumptions
---
## 3. Lifecycle
```text
CREATED → ACTIVE → DISABLED → REVOKED
```
| State | Description | Terminal |
|-------|-------------|----------|
| CREATED | Initial state | No |
| ACTIVE | Can authenticate | No |
| DISABLED | Temporarily blocked | No |
| REVOKED | Permanently blocked | Yes |
Credential lifecycle is SEPARATE from Principal lifecycle.
---
## 4. Authorization Changes
### Generic Principal support
`compute_effective_policy()` updated to accept both User and ServiceAccount:
```python
def compute_effective_policy(principal: Union[User, ServiceAccount], db: Session):
if isinstance(principal, User):
role_ids = [ur.role_id for ur in principal.user_roles]
elif isinstance(principal, ServiceAccount):
role_ids = [sar.role_id for sar in principal.roles]
```
### Same authorization engine
- User and ServiceAccount use the same `compute_effective_policy()`
- No separate ServiceAccount permission engine
- `require_permission()` works for User
- `require_sa_permission()` added for ServiceAccount
---
## 5. API / Управление
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/service-accounts` | POST | Create SA (returns secret once) |
| `/service-accounts` | GET | List all SAs |
| `/service-accounts/{id}` | GET | Get SA metadata |
| `/service-accounts/{id}/disable` | POST | Disable SA |
| `/service-accounts/{id}/enable` | POST | Enable SA |
| `/service-accounts/{id}/revoke` | POST | Revoke SA (terminal) |
| `/service-accounts/{id}/rotate-credential` | POST | Rotate credential |
| `/service-accounts/{id}/roles` | PUT | Update roles |
Secret returned only at creation. List/Get never return credentials.
---
## 6. Audit
### Events tracked
- created, activated, disabled, enabled, revoked
- credential_issued, credential_rotated, credential_revoked
- role_assigned, role_removed
- authentication_success, authentication_failure
### Security
- NEVER logs plaintext secrets
- NEVER logs passwords
- NEVER logs sensitive token material
- Audit is accountability, NOT tamper protection
---
## 7. Migration
### Tables created
| Table | Purpose |
|-------|---------|
| service_accounts | Service Account Principal |
| service_account_credentials | Credential storage (hashed) |
| service_account_roles | SA → Role mapping |
| service_account_audit_events | Security audit trail |
### Migration file
`migrations/alembic/versions/002_add_service_accounts.py`
- down_revision = '001_add_permissions'
- Reversible (upgrade/downgrade)
- Existing tables unaffected
---
## 8. Platform Boundary
### Platform can:
- See SA metadata/status via Module API
- Initiate management operations via approved contract
### Platform cannot:
- Directly create SA in Module DB
- Directly assign Module roles
- Directly modify credentials
- Directly modify lifecycle
ServiceAccount remains Module-owned.
---
## 9. Platform Outage Behavior
Service Account authentication works WITHOUT Platform:
```text
Platform unavailable
↓
local credential validation (bcrypt)
↓
local Principal (ServiceAccount)
↓
local authorization (DB-driven)
↓
ALLOW / DENY
```
No Platform API calls required for SA authentication.
---
## 10. Security Limitations
### Security-sensitive DB fields
| Field | Table | Risk |
|-------|-------|------|
| state | service_accounts | Lifecycle bypass |
| secret_hash | service_account_credentials | Credential theft |
| role_id | service_account_roles | Permission escalation |
### Current protection
- Application authorization on all management endpoints
- bcrypt hashing for credentials
- Audit trail for accountability
### Future requirements
- Authorization artifact for tamper-proof authority
- NOT implemented in this TT
---
## 11. Explicitly Deferred
- Vendor Break-Glass / Emergency Authority
- Vendor Authorization artifact
- Emergency cryptography
- Corporate licensing gate
- LDAP/AD integration
- Offline authorization with TTL
- Policy distribution
- Remote deployment
---
## 12. Tests and Results
### New tests (22 tests)
| Category | Tests | Status |
|----------|-------|--------|
| Model existence | 4 | ✅ PASSED |
| Lifecycle | 4 | ✅ PASSED |
| Credential | 8 | ✅ PASSED |
| Authorization | 4 | ✅ PASSED |
| Platform outage | 1 | ✅ PASSED |
| Same engine | 1 | ✅ PASSED |
### Regression
| Suite | Tests | Status |
|-------|-------|--------|
| Request Module | 50 | ✅ ALL PASSED |
| Platform Backend | 27 | ✅ ALL PASSED |
| Frontend build | - | ✅ OK (1.01s) |
---
## 13. Files Changed / Изменённые файлы
### New files
| File | Purpose |
|------|---------|
| `request_app/models/service_account.py` | ServiceAccount model |
| `request_app/models/service_account_role.py` | SA → Role mapping |
| `request_app/models/service_account_credential.py` | Credential storage |
| `request_app/models/service_account_audit.py` | Audit events |
| `request_app/core/service_account_auth.py` | Credential operations |
| `request_app/api/v1/routes/service_accounts.py` | Management API |
| `migrations/alembic/versions/002_add_service_accounts.py` | Migration |
| `tests/smoke/test_service_accounts.py` | Tests |
### Modified files
| File | Change |
|------|--------|
| `request_app/models/__init__.py` | Added new model imports |
| `request_app/api/v1/routes/permissions.py` | Generic Principal support |
| `request_app/core/auth.py` | Added SA authentication |
| `module.py` | Registered service_accounts router |
---
## 14. Known Follow-up Tasks
1. Alembic migration execution on real DB
2. Frontend management UI for Service Accounts
3. Vendor Break-Glass / Emergency Authority (separate TT)
4. Authorization artifact for tamper-proof authority
5. LDAP/AD integration
6. Remote deployment support
---
## Agent Review Checklist
### Principal
- [x] ServiceAccount is NOT User subtype
- [x] No `User.source="service_account"` as primary design
- [x] Generic Principal boundary exists
### Authorization
- [x] Role/Permission/RolePermission reused
- [x] No second authorization engine
- [x] `compute_effective_policy()` generic
- [x] Existing User authorization preserved
### Credentials
- [x] Plaintext secret NEVER stored
- [x] Secret shown only at creation
- [x] Rotation works
- [x] Revocation works
- [x] Disabled/Revoked cannot authenticate
### Lifecycle
- [x] CREATED exists
- [x] ACTIVE exists
- [x] DISABLED exists
- [x] REVOKED exists (terminal)
- [x] Credential lifecycle separated
### Platform
- [x] Platform does NOT own ServiceAccount
- [x] No direct DB access
- [x] Authentication does NOT require Platform
### Break-Glass
- [x] Nothing implemented
- [x] No emergency_admin role
- [x] No Vendor root token
### Security
- [x] Secrets absent from list/get
- [x] Secrets absent from logs/audit
- [x] Security-sensitive fields documented
- [x] SQL tampering limitation documented
### Migration
- [x] Alembic migration created
- [x] Downgrade defined
- [x] Existing tables unaffected
### Tests
- [x] New tests pass (22)
- [x] Existing Request Module tests pass (50)
- [x] Platform Backend tests pass (27)
- [x] Frontend build passes
---
## Final Status
```text
TT-008 Implementation completed
Status: READY FOR REVIEW
Changed files:
- New: 8 files (models, auth, API, migration, tests)
- Modified: 4 files (init, permissions, auth, module)
Tests:
- New: 22 tests (all passed)
- Regression: 77 tests (all passed)
Migration:
- 002_add_service_accounts.py
- 4 tables: service_accounts, credentials, roles, audit
Security notes:
- Plaintext secrets never stored
- bcrypt hashing
- Audit trail for accountability
- SQL tampering not fully prevented (documented)
Deferred:
- Break-Glass / Emergency Authority
- Authorization artifact
- LDAP/AD integration
```
Final commit выполняет только человек — финальный приёмщик проекта.
Final commit is performed only by the human final reviewer.
@@ -0,0 +1,548 @@
# 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 |
@@ -0,0 +1,93 @@
"""Add Service Account tables
Revision ID: 002_add_service_accounts
Revises: 001_add_permissions
Create Date: 2026-08-06
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers
revision = '002_add_service_accounts'
down_revision = '001_add_permissions'
branch_labels = None
depends_on = None
def upgrade() -> None:
# Create service_accounts table
op.create_table(
'service_accounts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('identifier', sa.String(100), nullable=False),
sa.Column('display_name', sa.String(200), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('state', sa.String(20), nullable=False, server_default='CREATED'),
sa.Column('module_id', sa.String(50), nullable=False, server_default='request'),
sa.Column('created_by', sa.String(200), nullable=True),
sa.Column('last_authenticated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_service_accounts_id', 'service_accounts', ['id'])
op.create_index('ix_service_accounts_identifier', 'service_accounts', ['identifier'], unique=True)
# Create service_account_credentials table
op.create_table(
'service_account_credentials',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('service_account_id', sa.Integer(), sa.ForeignKey('service_accounts.id', ondelete='CASCADE'), nullable=False),
sa.Column('credential_id', sa.String(50), nullable=False),
sa.Column('secret_hash', sa.String(255), nullable=False),
sa.Column('state', sa.String(20), nullable=False, server_default='ACTIVE'),
sa.Column('issued_at', sa.DateTime(), nullable=False),
sa.Column('expires_at', sa.DateTime(), nullable=True),
sa.Column('revoked_at', sa.DateTime(), nullable=True),
sa.Column('rotated_at', sa.DateTime(), nullable=True),
sa.Column('issued_by', sa.String(200), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_service_account_credentials_id', 'service_account_credentials', ['id'])
op.create_index('ix_service_account_credentials_credential_id', 'service_account_credentials', ['credential_id'], unique=True)
# Create service_account_roles table
op.create_table(
'service_account_roles',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('service_account_id', sa.Integer(), sa.ForeignKey('service_accounts.id', ondelete='CASCADE'), nullable=False),
sa.Column('role_id', sa.Integer(), sa.ForeignKey('roles.id', ondelete='CASCADE'), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('service_account_id', 'role_id', name='uq_service_account_role'),
)
op.create_index('ix_service_account_roles_id', 'service_account_roles', ['id'])
# Create service_account_audit_events table
op.create_table(
'service_account_audit_events',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('service_account_id', sa.Integer(), sa.ForeignKey('service_accounts.id', ondelete='CASCADE'), nullable=False),
sa.Column('event_type', sa.String(50), nullable=False),
sa.Column('message', sa.Text(), nullable=False),
sa.Column('performed_by', sa.String(200), nullable=True),
sa.Column('extra_data', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_service_account_audit_events_id', 'service_account_audit_events', ['id'])
op.create_index('ix_service_account_audit_events_service_account_id', 'service_account_audit_events', ['service_account_id'])
op.create_index('ix_service_account_audit_events_event_type', 'service_account_audit_events', ['event_type'])
def downgrade() -> None:
op.drop_table('service_account_audit_events')
op.drop_table('service_account_roles')
op.drop_table('service_account_credentials')
op.drop_table('service_accounts')
+2
View File
@@ -40,6 +40,7 @@ class RequestModule(BaseModule):
health, auth, users, tickets,
reference, notifications, emails,
settings, notification_templates, permissions,
service_accounts,
)
module_router = APIRouter(prefix="/api/v1/request")
@@ -53,6 +54,7 @@ class RequestModule(BaseModule):
module_router.include_router(settings.router)
module_router.include_router(notification_templates.router)
module_router.include_router(permissions.router)
module_router.include_router(service_accounts.router)
routers = [module_router]
except Exception as e:
@@ -2,33 +2,48 @@
Permission Catalog and Effective Policy are owned by Module, not Platform.
DB is the single source of truth for authorization.
Supports both User and ServiceAccount as Principal types.
"""
from typing import Union
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from request_app.core.auth import get_current_user
from request_app.core.database import get_db
from request_app.models.user import User
from request_app.models.service_account import ServiceAccount
from request_app.models.permission import Permission
from request_app.models.role_permission import RolePermission
from request_app.models.user_role import UserRole
from request_app.models.service_account_role import ServiceAccountRole
router = APIRouter(tags=["Permissions"])
def compute_effective_policy(user: User, db: Session) -> list[str]:
"""Compute effective permissions for a user based on local roles.
def compute_effective_policy(principal: Union[User, ServiceAccount], db: Session) -> list[str]:
"""Compute effective permissions for a Principal based on local roles.
This is the Module-owned authorization engine.
Module is the authority for its own permissions.
Works with both User and ServiceAccount.
DB is the single source of truth.
"""
permissions = set()
# Get user's local roles
for user_role in user.user_roles:
role_id = user_role.role_id
# Get role IDs based on Principal type
role_ids = []
# Get permissions for this role from DB
if isinstance(principal, User):
# User: get roles from UserRole
role_ids = [ur.role_id for ur in principal.user_roles]
elif isinstance(principal, ServiceAccount):
# ServiceAccount: get roles from ServiceAccountRole
role_ids = [sar.role_id for sar in principal.roles]
else:
return []
# Get permissions for each role from DB
for role_id in role_ids:
role_perms = (
db.query(Permission.name)
.join(RolePermission, RolePermission.permission_id == Permission.id)
@@ -71,6 +86,7 @@ async def get_my_effective_policy(
permissions = compute_effective_policy(user, db)
return {
"module_id": "request",
"user_id": user.id,
"principal_type": "user",
"principal_id": user.id,
"permissions": permissions,
}
@@ -0,0 +1,254 @@
"""Service Account management API.
Module-owned API for Local Admin management.
All endpoints require request.service_account.manage permission.
Secret is returned only once at creation.
List/Get never return credentials.
"""
from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from request_app.core.database import get_db
from request_app.core.auth import require_permission
from request_app.core.service_account_auth import (
create_credential,
rotate_credential,
revoke_credential,
)
from request_app.models.user import User
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.models.service_account_role import ServiceAccountRole
from request_app.models.service_account_audit import ServiceAccountAuditEvent
from request_app.models.role import Role
router = APIRouter(prefix="/service-accounts", tags=["Service Accounts"])
# Permission required for all management operations
SA_MANAGE_PERMISSION = "request.service_account.manage"
def _audit(db: Session, sa_id: int, event_type: str, message: str, performed_by: Optional[str] = None):
"""Create audit event."""
audit = ServiceAccountAuditEvent(
service_account_id=sa_id,
event_type=event_type,
message=message,
performed_by=performed_by,
)
db.add(audit)
def _sa_to_dict(sa: ServiceAccount) -> dict:
"""Convert ServiceAccount to dict (without secrets)."""
return {
"id": sa.id,
"identifier": sa.identifier,
"display_name": sa.display_name,
"description": sa.description,
"state": sa.state.value if hasattr(sa.state, 'value') else sa.state,
"module_id": sa.module_id,
"created_by": sa.created_by,
"last_authenticated_at": sa.last_authenticated_at.isoformat() if sa.last_authenticated_at else None,
"created_at": sa.created_at.isoformat() if sa.created_at else None,
"updated_at": sa.updated_at.isoformat() if sa.updated_at else None,
"roles": [r.role.name for r in sa.roles if r.role],
}
@router.post("", status_code=201)
async def create_service_account(
data: dict,
db: Session = Depends(get_db),
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
):
"""Create a new Service Account.
Returns credential ONLY at creation.
Requires request.service_account.manage permission.
"""
identifier = data.get("identifier")
display_name = data.get("display_name")
description = data.get("description", "")
if not identifier or not display_name:
raise HTTPException(status_code=400, detail="identifier and display_name required")
# Check unique identifier
existing = db.query(ServiceAccount).filter(ServiceAccount.identifier == identifier).first()
if existing:
raise HTTPException(status_code=409, detail="Identifier already exists")
# Create service account
sa = ServiceAccount(
identifier=identifier,
display_name=display_name,
description=description,
state=ServiceAccountState.CREATED,
module_id="request",
created_by=current_user.email,
)
db.add(sa)
db.flush()
# Create credential
credential, secret = create_credential(db, sa, issued_by=current_user.email)
# Activate SA
sa.state = ServiceAccountState.ACTIVE
# Audit
_audit(db, sa.id, "created", f"Service Account created: {identifier}", current_user.email)
_audit(db, sa.id, "activated", f"Service Account activated: {identifier}", current_user.email)
db.commit()
db.refresh(sa)
return {
"service_account": _sa_to_dict(sa),
"credential": {
"credential_id": credential.credential_id,
"secret": secret, # SHOWN ONLY ONCE
},
}
@router.get("")
async def list_service_accounts(
db: Session = Depends(get_db),
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
):
"""List all Service Accounts. Never returns credentials."""
sa_list = db.query(ServiceAccount).all()
return {
"service_accounts": [_sa_to_dict(sa) for sa in sa_list],
}
@router.get("/{sa_id}")
async def get_service_account(
sa_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
):
"""Get Service Account metadata. Never returns credentials."""
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
if not sa:
raise HTTPException(status_code=404, detail="Service Account not found")
return _sa_to_dict(sa)
@router.post("/{sa_id}/disable")
async def disable_service_account(
sa_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
):
"""Disable Service Account (ACTIVE → DISABLED)."""
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
if not sa:
raise HTTPException(status_code=404, detail="Service Account not found")
if not sa.can_transition_to(ServiceAccountState.DISABLED):
raise HTTPException(status_code=400, detail=f"Cannot disable from state {sa.state}")
sa.state = ServiceAccountState.DISABLED
_audit(db, sa.id, "disabled", f"Service Account disabled: {sa.identifier}", current_user.email)
db.commit()
return _sa_to_dict(sa)
@router.post("/{sa_id}/enable")
async def enable_service_account(
sa_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
):
"""Enable Service Account (DISABLED → ACTIVE)."""
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
if not sa:
raise HTTPException(status_code=404, detail="Service Account not found")
if not sa.can_transition_to(ServiceAccountState.ACTIVE):
raise HTTPException(status_code=400, detail=f"Cannot enable from state {sa.state}")
sa.state = ServiceAccountState.ACTIVE
_audit(db, sa.id, "enabled", f"Service Account enabled: {sa.identifier}", current_user.email)
db.commit()
return _sa_to_dict(sa)
@router.post("/{sa_id}/revoke")
async def revoke_service_account(
sa_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
):
"""Revoke Service Account (terminal state)."""
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
if not sa:
raise HTTPException(status_code=404, detail="Service Account not found")
if not sa.can_transition_to(ServiceAccountState.REVOKED):
raise HTTPException(status_code=400, detail=f"Cannot revoke from state {sa.state}")
sa.state = ServiceAccountState.REVOKED
_audit(db, sa.id, "revoked", f"Service Account revoked: {sa.identifier}", current_user.email)
db.commit()
return _sa_to_dict(sa)
@router.post("/{sa_id}/rotate-credential")
async def rotate_sa_credential(
sa_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
):
"""Rotate credential. Old credential is invalidated."""
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
if not sa:
raise HTTPException(status_code=404, detail="Service Account not found")
if sa.state == ServiceAccountState.REVOKED:
raise HTTPException(status_code=400, detail="Cannot rotate credential for revoked account")
credential, secret = rotate_credential(db, sa, issued_by=current_user.email)
return {
"credential_id": credential.credential_id,
"secret": secret, # SHOWN ONLY ONCE
}
@router.put("/{sa_id}/roles")
async def update_sa_roles(
sa_id: int,
data: dict,
db: Session = Depends(get_db),
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
):
"""Update Service Account roles."""
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
if not sa:
raise HTTPException(status_code=404, detail="Service Account not found")
role_ids = data.get("role_ids", [])
# Remove existing roles
db.query(ServiceAccountRole).filter(ServiceAccountRole.service_account_id == sa.id).delete()
# Add new roles
for role_id in role_ids:
role = db.query(Role).filter(Role.id == role_id).first()
if role:
db.add(ServiceAccountRole(service_account_id=sa.id, role_id=role.id))
_audit(db, sa.id, "role_assigned", f"Role assigned: {role.name}", current_user.email)
db.commit()
db.refresh(sa)
return _sa_to_dict(sa)
@@ -1,6 +1,10 @@
"""Authentication dependencies for platform integration."""
"""Authentication dependencies for platform integration.
from typing import List
Unified authorization for User and ServiceAccount.
Single require_permission() for all Principal types.
"""
from typing import List, Union
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
@@ -9,6 +13,7 @@ from request_app.core.database import get_db
from request_app.core.security import decode_platform_token, get_user_id_from_token
from request_app.core.platform_client import PlatformUser, get_platform_client
from request_app.models.user import User
from request_app.models.service_account import ServiceAccount
security = HTTPBearer()
@@ -75,6 +80,76 @@ def get_current_user(
return user
def get_current_service_account(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db),
) -> ServiceAccount:
"""Get current authenticated Service Account from credential.
Supports machine-to-machine authentication.
Does NOT require Platform to be available.
"""
from request_app.core.service_account_auth import validate_credential
# Extract identifier and secret from credentials
# Format: "identifier:secret" in Authorization header
token = credentials.credentials
if ":" not in token:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credential format")
identifier, secret = token.split(":", 1)
# Validate credential locally (no Platform call needed)
sa = validate_credential(db, identifier, secret)
if not sa:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credential")
return sa
def get_current_principal(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db),
) -> Union[User, ServiceAccount]:
"""Get current authenticated Principal (User or ServiceAccount).
Tries User (JWT) first, then ServiceAccount (credential).
Single entry point for authentication.
Only catches expected authentication failures (ValueError, JWTError).
Unexpected errors are NOT silently swallowed.
"""
from request_app.core.service_account_auth import validate_credential
from jose import JWTError
token = credentials.credentials
# Try User JWT first
# Only catch expected authentication failures
try:
user_id = get_user_id_from_token(token)
payload = decode_platform_token(token)
if payload:
user = _sync_platform_user_to_local(db, payload)
if user.is_active:
return user
except ValueError:
# Invalid token format or missing claims — expected
pass
except JWTError:
# JWT decode failure — expected
pass
# Try Service Account credential
if ":" in token:
identifier, secret = token.split(":", 1)
sa = validate_credential(db, identifier, secret)
if sa:
return sa
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
def get_current_platform_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
) -> PlatformUser:
@@ -120,25 +195,24 @@ def require_role(role_name: str):
def require_permission(permission_id: str):
"""Dependency factory: require a specific permission.
UNIFIED authorization for all Principal types (User and ServiceAccount).
Authorization decision is made LOCALLY by Module.
Module is the authority for its own permissions.
Uses the single Module authorization engine from permissions.py.
DB is the single source of truth.
"""
from request_app.api.v1.routes.permissions import compute_effective_policy
def _check_permission(
current_user: User = Depends(get_current_user),
principal: Union[User, ServiceAccount] = Depends(get_current_principal),
db: Session = Depends(get_db),
) -> User:
) -> Union[User, ServiceAccount]:
# Use the single Module authorization engine (DB-driven)
user_permissions = set(compute_effective_policy(current_user, db))
permissions = set(compute_effective_policy(principal, db))
if permission_id not in user_permissions:
if permission_id not in permissions:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Permission '{permission_id}' required",
)
return current_user
return principal
return _check_permission
@@ -42,6 +42,7 @@ _BOOTSTRAP_PERMISSIONS = [
("request.admin", "Full administrative access"),
("request.settings.manage", "Manage module settings"),
("request.report.view", "View reports and statistics"),
("request.service_account.manage", "Manage service accounts"),
]
# Bootstrap role → permission mapping — used ONLY for seeding, NOT for runtime
@@ -0,0 +1,229 @@
"""Service Account authentication utilities.
Provides credential creation, validation, and lifecycle management.
Plaintext secret is NEVER stored.
"""
import secrets
import bcrypt
from datetime import datetime
from typing import Optional, Tuple
from sqlalchemy.orm import Session
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.models.service_account_credential import ServiceAccountCredential, CredentialState
from request_app.models.service_account_audit import ServiceAccountAuditEvent
def generate_secret() -> str:
"""Generate a cryptographically secure secret."""
return secrets.token_urlsafe(48)
def hash_secret(secret: str) -> str:
"""Hash a secret using bcrypt."""
return bcrypt.hashpw(secret.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def verify_secret(secret: str, hashed: str) -> bool:
"""Verify a secret against its hash."""
try:
return bcrypt.checkpw(secret.encode("utf-8"), hashed.encode("utf-8"))
except Exception:
return False
def create_credential(
db: Session,
service_account: ServiceAccount,
issued_by: Optional[str] = None,
) -> Tuple[ServiceAccountCredential, str]:
"""Create a new credential for a Service Account.
Policy: A ServiceAccount may have at most ONE ACTIVE credential.
If an ACTIVE credential already exists, it is ROTATED first.
Returns (credential, plaintext_secret).
Plaintext secret is shown ONLY at creation.
"""
# Revoke any existing ACTIVE credentials (policy: at most one ACTIVE)
existing_active = (
db.query(ServiceAccountCredential)
.filter(
ServiceAccountCredential.service_account_id == service_account.id,
ServiceAccountCredential.state == CredentialState.ACTIVE,
)
.all()
)
for cred in existing_active:
cred.state = CredentialState.ROTATED
cred.rotated_at = datetime.utcnow()
audit = ServiceAccountAuditEvent(
service_account_id=service_account.id,
event_type="credential_rotated",
message=f"Credential rotated (new issued): {cred.credential_id}",
performed_by=issued_by,
)
db.add(audit)
# Generate secret
secret = generate_secret()
secret_hash = hash_secret(secret)
# Generate unique credential ID
credential_id = f"cred_{secrets.token_hex(16)}"
# Create credential
credential = ServiceAccountCredential(
service_account_id=service_account.id,
credential_id=credential_id,
secret_hash=secret_hash,
state=CredentialState.ACTIVE,
issued_by=issued_by,
)
db.add(credential)
# Audit event
audit = ServiceAccountAuditEvent(
service_account_id=service_account.id,
event_type="credential_issued",
message=f"Credential issued: {credential_id}",
performed_by=issued_by,
)
db.add(audit)
db.commit()
db.refresh(credential)
return credential, secret
def validate_credential(
db: Session,
identifier: str,
secret: str,
) -> Optional[ServiceAccount]:
"""Validate credential and return ServiceAccount if valid.
Returns None if validation fails.
Does NOT require Platform to be available.
"""
# Find service account by identifier
sa = db.query(ServiceAccount).filter(ServiceAccount.identifier == identifier).first()
if not sa:
return None
# Check lifecycle state
if sa.state != ServiceAccountState.ACTIVE:
# Audit failed attempt
audit = ServiceAccountAuditEvent(
service_account_id=sa.id,
event_type="authentication_failure",
message=f"Authentication failed: account state is {sa.state}",
)
db.add(audit)
db.commit()
return None
# Find active credential
cred = (
db.query(ServiceAccountCredential)
.filter(
ServiceAccountCredential.service_account_id == sa.id,
ServiceAccountCredential.state == CredentialState.ACTIVE,
)
.first()
)
if not cred or not cred.is_valid:
# Audit failed attempt
audit = ServiceAccountAuditEvent(
service_account_id=sa.id,
event_type="authentication_failure",
message="Authentication failed: no valid credential",
)
db.add(audit)
db.commit()
return None
# Verify secret
if not verify_secret(secret, cred.secret_hash):
# Audit failed attempt
audit = ServiceAccountAuditEvent(
service_account_id=sa.id,
event_type="authentication_failure",
message="Authentication failed: invalid secret",
)
db.add(audit)
db.commit()
return None
# Update last authenticated
sa.last_authenticated_at = datetime.utcnow()
# Audit success
audit = ServiceAccountAuditEvent(
service_account_id=sa.id,
event_type="authentication_success",
message="Authentication successful",
)
db.add(audit)
db.commit()
return sa
def rotate_credential(
db: Session,
service_account: ServiceAccount,
issued_by: Optional[str] = None,
) -> Tuple[ServiceAccountCredential, str]:
"""Rotate credential: revoke old, create new.
Returns (new_credential, new_plaintext_secret).
"""
# Revoke all active credentials
active_creds = (
db.query(ServiceAccountCredential)
.filter(
ServiceAccountCredential.service_account_id == service_account.id,
ServiceAccountCredential.state == CredentialState.ACTIVE,
)
.all()
)
for cred in active_creds:
cred.state = CredentialState.ROTATED
cred.rotated_at = datetime.utcnow()
# Audit rotation of old credential
audit = ServiceAccountAuditEvent(
service_account_id=service_account.id,
event_type="credential_rotated",
message=f"Credential rotated: {cred.credential_id}",
performed_by=issued_by,
)
db.add(audit)
# Create new credential
return create_credential(db, service_account, issued_by)
def revoke_credential(
db: Session,
credential: ServiceAccountCredential,
revoked_by: Optional[str] = None,
) -> None:
"""Revoke a specific credential."""
credential.state = CredentialState.REVOKED
credential.revoked_at = datetime.utcnow()
# Audit
audit = ServiceAccountAuditEvent(
service_account_id=credential.service_account_id,
event_type="credential_revoked",
message=f"Credential revoked: {credential.credential_id}",
performed_by=revoked_by,
)
db.add(audit)
db.commit()
@@ -6,6 +6,10 @@ from request_app.models.role import Role
from request_app.models.user_role import UserRole
from request_app.models.permission import Permission
from request_app.models.role_permission import RolePermission
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.models.service_account_role import ServiceAccountRole
from request_app.models.service_account_credential import ServiceAccountCredential, CredentialState
from request_app.models.service_account_audit import ServiceAccountAuditEvent
from request_app.models.priority import Priority
from request_app.models.status import Status
from request_app.models.category import Category
@@ -27,6 +31,12 @@ __all__ = [
"UserRole",
"Permission",
"RolePermission",
"ServiceAccount",
"ServiceAccountState",
"ServiceAccountRole",
"ServiceAccountCredential",
"CredentialState",
"ServiceAccountAuditEvent",
"Priority",
"Status",
"Category",
@@ -0,0 +1,77 @@
"""ServiceAccount model — separate Principal type.
ServiceAccount is NOT a User subtype.
It is a separate Principal for machine-to-machine authentication.
"""
from datetime import datetime
from sqlalchemy import Column, String, Boolean, Integer, DateTime, Text, Enum as SQLEnum
from sqlalchemy.orm import relationship
from request_app.models.base import Base, TimestampMixin
import enum
class ServiceAccountState(str, enum.Enum):
"""Service Account lifecycle states."""
CREATED = "CREATED"
ACTIVE = "ACTIVE"
DISABLED = "DISABLED"
REVOKED = "REVOKED"
class ServiceAccount(Base, TimestampMixin):
"""Service Account — separate Principal for machine-to-machine auth.
This is NOT a User subtype. It is a separate entity type.
Module-owned. Platform does not directly manage this.
"""
__tablename__ = "service_accounts"
id = Column(Integer, primary_key=True, index=True)
# Stable identifier for API reference (not email)
identifier = Column(String(100), unique=True, nullable=False, index=True)
display_name = Column(String(200), nullable=False)
description = Column(Text, nullable=True)
# Lifecycle state
state = Column(
SQLEnum(ServiceAccountState),
nullable=False,
default=ServiceAccountState.CREATED,
)
# Module ownership
module_id = Column(String(50), nullable=False, default="request")
# Audit metadata
created_by = Column(String(200), nullable=True) # Who created this SA
last_authenticated_at = Column(DateTime, nullable=True)
# Relationships
credentials = relationship("ServiceAccountCredential", back_populates="service_account", cascade="all, delete-orphan")
roles = relationship("ServiceAccountRole", back_populates="service_account", cascade="all, delete-orphan")
audit_events = relationship("ServiceAccountAuditEvent", back_populates="service_account", cascade="all, delete-orphan")
def __repr__(self) -> str:
return f"<ServiceAccount(id={self.id}, identifier='{self.identifier}', state='{self.state}')>"
@property
def is_active(self) -> bool:
"""Check if account can authenticate."""
return self.state == ServiceAccountState.ACTIVE
@property
def is_revoked(self) -> bool:
"""Check if account is permanently revoked."""
return self.state == ServiceAccountState.REVOKED
def can_transition_to(self, new_state: ServiceAccountState) -> bool:
"""Check if transition to new_state is allowed."""
allowed = {
ServiceAccountState.CREATED: {ServiceAccountState.ACTIVE, ServiceAccountState.REVOKED},
ServiceAccountState.ACTIVE: {ServiceAccountState.DISABLED, ServiceAccountState.REVOKED},
ServiceAccountState.DISABLED: {ServiceAccountState.ACTIVE, ServiceAccountState.REVOKED},
ServiceAccountState.REVOKED: set(), # Terminal state
}
return new_state in allowed.get(self.state, set())
@@ -0,0 +1,38 @@
"""ServiceAccountAuditEvent model — security audit trail.
Audit is accountability mechanism.
NEVER log plaintext credentials or sensitive token material.
"""
from sqlalchemy import Column, String, Integer, ForeignKey, Text
from sqlalchemy.orm import relationship
from request_app.models.base import Base, TimestampMixin
class ServiceAccountAuditEvent(Base, TimestampMixin):
"""Security audit events for Service Account lifecycle.
Audit is accountability, NOT a defense against SQL tampering.
"""
__tablename__ = "service_account_audit_events"
id = Column(Integer, primary_key=True, index=True)
service_account_id = Column(Integer, ForeignKey("service_accounts.id", ondelete="CASCADE"), nullable=False, index=True)
# Event type
event_type = Column(String(50), nullable=False, index=True)
# Types: created, activated, disabled, enabled, revoked,
# credential_issued, credential_rotated, credential_revoked,
# role_assigned, role_removed, authentication_success, authentication_failure
# Event details (NO secrets)
message = Column(Text, nullable=False)
performed_by = Column(String(200), nullable=True) # Who performed the action
extra_data = Column(Text, nullable=True) # JSON for additional context (NO secrets)
# Relationships
service_account = relationship("ServiceAccount", back_populates="audit_events")
def __repr__(self) -> str:
return f"<ServiceAccountAuditEvent(sa_id={self.service_account_id}, type='{self.event_type}')>"
@@ -0,0 +1,65 @@
"""ServiceAccountCredential model — credential storage.
Credentials are stored securely (hashed).
Plaintext secret is NEVER stored.
Secret is shown only once at creation.
"""
from datetime import datetime
from sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Boolean, Text
from sqlalchemy.orm import relationship
from request_app.models.base import Base, TimestampMixin
import enum
class CredentialState(str, enum.Enum):
"""Credential lifecycle states."""
ACTIVE = "ACTIVE"
ROTATED = "ROTATED"
REVOKED = "REVOKED"
class ServiceAccountCredential(Base, TimestampMixin):
"""Service Account credential storage.
Stores hashed credential only.
Plaintext secret is NEVER stored.
"""
__tablename__ = "service_account_credentials"
id = Column(Integer, primary_key=True, index=True)
service_account_id = Column(Integer, ForeignKey("service_accounts.id", ondelete="CASCADE"), nullable=False)
# Credential identifier (for rotation tracking)
credential_id = Column(String(50), unique=True, nullable=False, index=True)
# Hashed secret (bcrypt or similar)
secret_hash = Column(String(255), nullable=False)
# Credential state
state = Column(String(20), nullable=False, default=CredentialState.ACTIVE)
# Lifecycle
issued_at = Column(DateTime, nullable=False, default=datetime.utcnow)
expires_at = Column(DateTime, nullable=True) # NULL = no expiry
revoked_at = Column(DateTime, nullable=True)
rotated_at = Column(DateTime, nullable=True)
# Metadata
issued_by = Column(String(200), nullable=True) # Who issued this credential
# Relationships
service_account = relationship("ServiceAccount", back_populates="credentials")
def __repr__(self) -> str:
return f"<ServiceAccountCredential(id={self.credential_id}, state='{self.state}')>"
@property
def is_valid(self) -> bool:
"""Check if credential can be used for authentication."""
if self.state != CredentialState.ACTIVE:
return False
if self.expires_at and datetime.utcnow() > self.expires_at:
return False
return True
@@ -0,0 +1,34 @@
"""ServiceAccountRole model — ServiceAccount → Role mapping.
This is the generic Principal → Role link for Service Accounts.
Reuses existing Role model.
"""
from sqlalchemy import Column, Integer, ForeignKey, UniqueConstraint
from sqlalchemy.orm import relationship
from request_app.models.base import Base, TimestampMixin
class ServiceAccountRole(Base, TimestampMixin):
"""ServiceAccountRole — links ServiceAccount to Role.
Reuses existing Role model for authorization.
"""
__tablename__ = "service_account_roles"
id = Column(Integer, primary_key=True, index=True)
service_account_id = Column(Integer, ForeignKey("service_accounts.id", ondelete="CASCADE"), nullable=False)
role_id = Column(Integer, ForeignKey("roles.id", ondelete="CASCADE"), nullable=False)
# Unique constraint: one SA can have each role only once
__table_args__ = (
UniqueConstraint("service_account_id", "role_id", name="uq_service_account_role"),
)
# Relationships
service_account = relationship("ServiceAccount", back_populates="roles")
role = relationship("Role")
def __repr__(self) -> str:
return f"<ServiceAccountRole(sa_id={self.service_account_id}, role_id={self.role_id})>"
@@ -178,7 +178,7 @@ def test_effective_policy_admin(seeded_db):
perms = compute_effective_policy(user, seeded_db)
# Admin should have all permissions
assert len(perms) == 10
assert len(perms) == 11
assert "request.read" in perms
assert "request.create" in perms
assert "request.delete" in perms
@@ -334,7 +334,8 @@ def test_catalog_reads_from_db(seeded_db):
assert "request.read" in perm_names
assert "request.create" in perm_names
assert "request.delete" in perm_names
assert len(perm_names) == 10
assert "request.service_account.manage" in perm_names
assert len(perm_names) == 11
def test_catalog_reflects_db_changes(seeded_db):
@@ -0,0 +1,849 @@
"""Service Account Tests — TT-008
Real behavioral tests proving runtime authorization behavior.
Tests invoke actual require_permission() and management API endpoints.
"""
import pytest
import sys
from pathlib import Path
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker
from fastapi import FastAPI, HTTPException, Depends
from fastapi.testclient import TestClient
# Compute absolute paths
_MODULE_ROOT = Path(__file__).parent.parent.parent.resolve()
_PLATFORM_BACKEND = _MODULE_ROOT.parent.parent / "platform" / "backend"
# Add platform SDK to path
if str(_PLATFORM_BACKEND) not in sys.path:
sys.path.insert(0, str(_PLATFORM_BACKEND))
# Add module root to path
if str(_MODULE_ROOT) not in sys.path:
sys.path.insert(0, str(_MODULE_ROOT))
@pytest.fixture(scope="function")
def db_engine():
"""Create a fresh file-based SQLite database for each test."""
import tempfile
import os
# Use file-based SQLite (in-memory doesn't work with multiple connections)
db_file = tempfile.mktemp(suffix='.db')
engine = create_engine(f"sqlite:///{db_file}", connect_args={"check_same_thread": False})
@event.listens_for(engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
from request_app.models.base import Base
Base.metadata.create_all(bind=engine)
yield engine
Base.metadata.drop_all(bind=engine)
engine.dispose()
# Cleanup
if os.path.exists(db_file):
os.remove(db_file)
@pytest.fixture(scope="function")
def db_session(db_engine):
"""Provide a database session for each test."""
Session = sessionmaker(bind=db_engine)
db = Session()
try:
yield db
finally:
db.rollback()
db.close()
@pytest.fixture
def seeded_db(db_session):
"""Seed the database with default data."""
from request_app.models.role import Role
from request_app.models.permission import Permission
from request_app.models.role_permission import RolePermission
from request_app.core.database import _seed_permissions, _seed_role_permissions
# Create default roles
default_roles = [
("admin", "Administrator", True),
("manager", "Manager", True),
("support_agent", "Support agent", True),
("customer", "Customer", True),
]
for name, desc, is_system in default_roles:
if not db_session.query(Role).filter(Role.name == name).first():
db_session.add(Role(name=name, description=desc, is_system=is_system))
db_session.flush()
_seed_permissions(db_session)
db_session.flush()
_seed_role_permissions(db_session)
db_session.commit()
return db_session
@pytest.fixture
def test_app(db_engine):
"""Create a test FastAPI app with Service Account management endpoints."""
from request_app.api.v1.routes.service_accounts import router as sa_router
from request_app.core.database import get_db
app = FastAPI()
app.include_router(sa_router)
Session = sessionmaker(bind=db_engine)
def override_get_db():
db = Session()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
return app
@pytest.fixture
def test_client(test_app):
"""Create a test client."""
return TestClient(test_app)
# === MODEL TESTS ===
def test_service_account_model_exists():
"""Test that ServiceAccount model exists."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
assert ServiceAccount.__tablename__ == "service_accounts"
assert hasattr(ServiceAccount, 'identifier')
assert hasattr(ServiceAccount, 'display_name')
assert hasattr(ServiceAccount, 'state')
def test_service_account_credential_model_exists():
"""Test that ServiceAccountCredential model exists."""
from request_app.models.service_account_credential import ServiceAccountCredential
assert ServiceAccountCredential.__tablename__ == "service_account_credentials"
assert hasattr(ServiceAccountCredential, 'credential_id')
assert hasattr(ServiceAccountCredential, 'secret_hash')
def test_service_account_role_model_exists():
"""Test that ServiceAccountRole model exists."""
from request_app.models.service_account_role import ServiceAccountRole
assert ServiceAccountRole.__tablename__ == "service_account_roles"
def test_service_account_audit_model_exists():
"""Test that ServiceAccountAuditEvent model exists."""
from request_app.models.service_account_audit import ServiceAccountAuditEvent
assert ServiceAccountAuditEvent.__tablename__ == "service_account_audit_events"
def test_service_account_lifecycle_states():
"""Test that lifecycle states are defined."""
from request_app.models.service_account import ServiceAccountState
assert ServiceAccountState.CREATED == "CREATED"
assert ServiceAccountState.ACTIVE == "ACTIVE"
assert ServiceAccountState.DISABLED == "DISABLED"
assert ServiceAccountState.REVOKED == "REVOKED"
def test_service_account_creation(seeded_db):
"""Test Service Account creation."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
sa = ServiceAccount(
identifier="test-sa",
display_name="Test Service Account",
state=ServiceAccountState.CREATED,
)
seeded_db.add(sa)
seeded_db.commit()
assert sa.id is not None
assert sa.identifier == "test-sa"
assert sa.state == ServiceAccountState.CREATED
def test_service_account_unique_identifier(seeded_db):
"""Test that identifier is unique."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from sqlalchemy.exc import IntegrityError
sa1 = ServiceAccount(identifier="unique-sa", display_name="SA 1", state=ServiceAccountState.CREATED)
seeded_db.add(sa1)
seeded_db.commit()
sa2 = ServiceAccount(identifier="unique-sa", display_name="SA 2", state=ServiceAccountState.CREATED)
seeded_db.add(sa2)
with pytest.raises(IntegrityError):
seeded_db.commit()
def test_service_account_lifecycle_transitions():
"""Test lifecycle state transitions."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
sa = ServiceAccount(identifier="test", display_name="Test", state=ServiceAccountState.CREATED)
# CREATED → ACTIVE
assert sa.can_transition_to(ServiceAccountState.ACTIVE)
assert sa.can_transition_to(ServiceAccountState.REVOKED)
assert not sa.can_transition_to(ServiceAccountState.DISABLED)
# ACTIVE → DISABLED
sa.state = ServiceAccountState.ACTIVE
assert sa.can_transition_to(ServiceAccountState.DISABLED)
assert sa.can_transition_to(ServiceAccountState.REVOKED)
# DISABLED → ACTIVE
sa.state = ServiceAccountState.DISABLED
assert sa.can_transition_to(ServiceAccountState.ACTIVE)
assert sa.can_transition_to(ServiceAccountState.REVOKED)
# REVOKED is terminal
sa.state = ServiceAccountState.REVOKED
assert not sa.can_transition_to(ServiceAccountState.ACTIVE)
assert not sa.can_transition_to(ServiceAccountState.DISABLED)
def test_revoked_is_terminal(seeded_db):
"""Test that REVOKED is terminal state."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
sa = ServiceAccount(identifier="revoked-sa", display_name="Revoked", state=ServiceAccountState.REVOKED)
seeded_db.add(sa)
seeded_db.commit()
assert sa.is_revoked
assert not sa.is_active
assert not sa.can_transition_to(ServiceAccountState.ACTIVE)
# === CREDENTIAL TESTS ===
def test_credential_creation(seeded_db):
"""Test credential creation."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.core.service_account_auth import create_credential
sa = ServiceAccount(identifier="cred-sa", display_name="Cred SA", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
credential, secret = create_credential(seeded_db, sa)
assert credential.id is not None
assert credential.credential_id.startswith("cred_")
assert secret # Secret is returned
assert credential.secret_hash != secret # Hash is different from secret
assert credential.state == "ACTIVE"
def test_credential_one_time_secret(seeded_db):
"""Test that secret is only available at creation."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.core.service_account_auth import create_credential
sa = ServiceAccount(identifier="onetime-sa", display_name="OneTime", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
credential, secret = create_credential(seeded_db, sa)
# Secret is returned at creation
assert secret
assert len(secret) > 20
# Secret is NOT stored (hash is stored)
assert credential.secret_hash != secret
def test_credential_validation(seeded_db):
"""Test credential validation."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.core.service_account_auth import create_credential, validate_credential
sa = ServiceAccount(identifier="valid-sa", display_name="Valid", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
credential, secret = create_credential(seeded_db, sa)
# Valid credential
result = validate_credential(seeded_db, "valid-sa", secret)
assert result is not None
assert result.id == sa.id
def test_credential_invalid_secret(seeded_db):
"""Test invalid secret fails validation."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.core.service_account_auth import create_credential, validate_credential
sa = ServiceAccount(identifier="invalid-sa", display_name="Invalid", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
create_credential(seeded_db, sa)
# Invalid secret
result = validate_credential(seeded_db, "invalid-sa", "wrong-secret")
assert result is None
def test_disabled_account_cannot_authenticate(seeded_db):
"""Test disabled account cannot authenticate."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.core.service_account_auth import create_credential, validate_credential
sa = ServiceAccount(identifier="disabled-sa", display_name="Disabled", state=ServiceAccountState.DISABLED)
seeded_db.add(sa)
seeded_db.flush()
_, secret = create_credential(seeded_db, sa)
result = validate_credential(seeded_db, "disabled-sa", secret)
assert result is None
def test_revoked_account_cannot_authenticate(seeded_db):
"""Test revoked account cannot authenticate."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.core.service_account_auth import create_credential, validate_credential
sa = ServiceAccount(identifier="revoked-sa", display_name="Revoked", state=ServiceAccountState.REVOKED)
seeded_db.add(sa)
seeded_db.flush()
_, secret = create_credential(seeded_db, sa)
result = validate_credential(seeded_db, "revoked-sa", secret)
assert result is None
def test_credential_rotation(seeded_db):
"""Test credential rotation."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.models.service_account_credential import ServiceAccountCredential, CredentialState
from request_app.core.service_account_auth import create_credential, rotate_credential, validate_credential
sa = ServiceAccount(identifier="rotate-sa", display_name="Rotate", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
# Create initial credential
cred1, secret1 = create_credential(seeded_db, sa)
# Rotate
cred2, secret2 = rotate_credential(seeded_db, sa)
# Old credential should be rotated
assert cred1.state == CredentialState.ROTATED
# New credential should be active
assert cred2.state == CredentialState.ACTIVE
# Old secret should not work
result = validate_credential(seeded_db, "rotate-sa", secret1)
assert result is None
# New secret should work
result = validate_credential(seeded_db, "rotate-sa", secret2)
assert result is not None
def test_plaintext_not_stored(seeded_db):
"""Test that plaintext secret is never stored in DB."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.models.service_account_credential import ServiceAccountCredential
from request_app.core.service_account_auth import create_credential
sa = ServiceAccount(identifier="plaintext-sa", display_name="Plaintext", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
_, secret = create_credential(seeded_db, sa)
# Check DB directly
cred = seeded_db.query(ServiceAccountCredential).filter(
ServiceAccountCredential.service_account_id == sa.id
).first()
# secret_hash should NOT equal the plaintext secret
assert cred.secret_hash != secret
assert len(cred.secret_hash) > 20 # bcrypt hash is long
# === REAL require_permission() BEHAVIORAL TESTS ===
def test_user_require_permission_allow(seeded_db):
"""Test that User with permission passes require_permission().
REAL BEHAVIORAL TEST: invokes actual require_permission() dependency.
"""
from request_app.models.user import User
from request_app.models.user_role import UserRole
from request_app.models.role import Role
from request_app.core.auth import require_permission
# Create user with admin role (has all permissions)
user = User(email="perm-admin@test.com", first_name="Admin", last_name="User", source="local")
seeded_db.add(user)
seeded_db.flush()
admin_role = seeded_db.query(Role).filter(Role.name == "admin").first()
seeded_db.add(UserRole(user_id=user.id, role_id=admin_role.id))
seeded_db.commit()
# Get the dependency function from require_permission
# require_permission() returns _check_permission function
# We need to call it directly with principal and db
checker = require_permission("request.read")
# The returned function is _check_permission(principal, db)
# Call it directly (not through FastAPI DI)
result = checker(user, seeded_db)
assert result.id == user.id
def test_user_require_permission_deny(seeded_db):
"""Test that User without permission fails require_permission().
REAL BEHAVIORAL TEST: invokes actual require_permission() dependency.
"""
from request_app.models.user import User
from request_app.models.user_role import UserRole
from request_app.models.role import Role
from request_app.core.auth import require_permission
# Create user with customer role (limited permissions)
user = User(email="perm-customer@test.com", first_name="Customer", last_name="User", source="local")
seeded_db.add(user)
seeded_db.flush()
customer_role = seeded_db.query(Role).filter(Role.name == "customer").first()
seeded_db.add(UserRole(user_id=user.id, role_id=customer_role.id))
seeded_db.commit()
# Get the dependency function
checker = require_permission("request.admin")
# Should raise HTTPException 403
with pytest.raises(HTTPException) as exc_info:
checker(user, seeded_db)
assert exc_info.value.status_code == 403
def test_service_account_require_permission_allow(seeded_db):
"""Test that ServiceAccount with permission passes require_permission().
REAL BEHAVIORAL TEST: invokes actual require_permission() dependency.
"""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.models.service_account_role import ServiceAccountRole
from request_app.models.role import Role
from request_app.core.auth import require_permission
# Create SA with admin role
sa = ServiceAccount(identifier="perm-sa-admin", display_name="PermAdmin", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
admin_role = seeded_db.query(Role).filter(Role.name == "admin").first()
seeded_db.add(ServiceAccountRole(service_account_id=sa.id, role_id=admin_role.id))
seeded_db.commit()
# Get the dependency function
checker = require_permission("request.read")
# Call the inner function directly
result = checker(sa, seeded_db)
assert result.id == sa.id
def test_service_account_require_permission_deny(seeded_db):
"""Test that ServiceAccount without permission fails require_permission().
REAL BEHAVIORAL TEST: invokes actual require_permission() dependency.
"""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.models.service_account_role import ServiceAccountRole
from request_app.models.role import Role
from request_app.core.auth import require_permission
# Create SA with customer role (limited permissions)
sa = ServiceAccount(identifier="perm-sa-customer", display_name="PermCustomer", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
customer_role = seeded_db.query(Role).filter(Role.name == "customer").first()
seeded_db.add(ServiceAccountRole(service_account_id=sa.id, role_id=customer_role.id))
seeded_db.commit()
# Get the dependency function
checker = require_permission("request.admin")
# Should raise HTTPException 403
with pytest.raises(HTTPException) as exc_info:
checker(sa, seeded_db)
assert exc_info.value.status_code == 403
def test_user_and_sa_same_authorization_semantics(seeded_db):
"""Test that User and ServiceAccount use the same require_permission() semantics.
REAL BEHAVIORAL TEST: both go through require_permission().
"""
from request_app.models.user import User
from request_app.models.user_role import UserRole
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.models.service_account_role import ServiceAccountRole
from request_app.models.role import Role
from request_app.core.auth import require_permission
# Create User with manager role
user = User(email="same-auth-user@test.com", first_name="User", last_name="Test", source="local")
seeded_db.add(user)
seeded_db.flush()
manager_role = seeded_db.query(Role).filter(Role.name == "manager").first()
seeded_db.add(UserRole(user_id=user.id, role_id=manager_role.id))
# Create SA with manager role
sa = ServiceAccount(identifier="same-auth-sa", display_name="SameAuthSA", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
seeded_db.add(ServiceAccountRole(service_account_id=sa.id, role_id=manager_role.id))
seeded_db.commit()
# Both should pass request.read
checker_allow = require_permission("request.read")
checker_allow(user, seeded_db) # Should not raise
checker_allow(sa, seeded_db) # Should not raise
# Both should fail request.admin
checker_deny = require_permission("request.admin")
with pytest.raises(HTTPException):
checker_deny(user, seeded_db)
with pytest.raises(HTTPException):
checker_deny(sa, seeded_db)
# === MANAGEMENT API ENDPOINT TESTS ===
def test_management_api_create_deny(seeded_db, db_engine):
"""Test that authenticated user without SA management permission gets 403 on POST /service-accounts.
REAL ENDPOINT TEST: authenticated user + missing permission → exactly 403.
"""
from request_app.models.user import User
from request_app.models.user_role import UserRole
from request_app.models.role import Role
from request_app.api.v1.routes.service_accounts import router as sa_router
from request_app.core.database import get_db
from request_app.core.security import create_local_token
# Create user with customer role (no SA management permission)
user = User(email="no-sa-perm@test.com", first_name="NoPerm", last_name="User", source="local")
seeded_db.add(user)
seeded_db.flush()
customer_role = seeded_db.query(Role).filter(Role.name == "customer").first()
seeded_db.add(UserRole(user_id=user.id, role_id=customer_role.id))
seeded_db.commit()
# Create test app with the same DB engine
app = FastAPI()
app.include_router(sa_router)
Session = sessionmaker(bind=db_engine)
def override_get_db():
db = Session()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
# Create a valid token for this user (authenticated, but no SA permission)
token = create_local_token(user.id, user.email)
# Try to create SA without permission
response = client.post(
"/service-accounts",
json={"identifier": "test-sa", "display_name": "Test SA"},
headers={"Authorization": f"Bearer {token}"},
)
# Authenticated user without permission → exactly 403
assert response.status_code == 403
def test_management_api_create_allow(seeded_db, db_engine):
"""Test that admin user can successfully create a Service Account.
REAL ENDPOINT TEST: authenticated admin + has permission → 201 success.
"""
from request_app.models.user import User
from request_app.models.user_role import UserRole
from request_app.models.role import Role
from request_app.api.v1.routes.service_accounts import router as sa_router
from request_app.core.database import get_db
from request_app.core.security import create_local_token
# Create user with admin role (has SA management permission)
user = User(email="sa-admin@test.com", first_name="Admin", last_name="User", source="local")
seeded_db.add(user)
seeded_db.flush()
admin_role = seeded_db.query(Role).filter(Role.name == "admin").first()
seeded_db.add(UserRole(user_id=user.id, role_id=admin_role.id))
seeded_db.commit()
# Create test app with the same DB engine
app = FastAPI()
app.include_router(sa_router)
Session = sessionmaker(bind=db_engine)
def override_get_db():
db = Session()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
# Create a token for this user
token = create_local_token(user.id, user.email)
# Try to create SA with permission
response = client.post(
"/service-accounts",
json={"identifier": "test-sa", "display_name": "Test SA"},
headers={"Authorization": f"Bearer {token}"},
)
# Admin with permission → 201 Created
assert response.status_code == 201
# Verify response contains Service Account data
data = response.json()
assert "service_account" in data
assert data["service_account"]["identifier"] == "test-sa"
assert "credential" in data
assert "secret" in data["credential"]
def test_management_api_endpoints_wired(seeded_db):
"""Test that all management endpoints are wired to require_permission dependency.
FASTAPI DEPENDENCY GRAPH INSPECTION: verifies actual dependency wiring.
Each endpoint must be protected by require_permission("request.service_account.manage").
"""
from request_app.api.v1.routes.service_accounts import router
# Expected endpoints
expected_endpoints = {
("POST", "/service-accounts"),
("GET", "/service-accounts"),
("GET", "/service-accounts/{sa_id}"),
("POST", "/service-accounts/{sa_id}/disable"),
("POST", "/service-accounts/{sa_id}/enable"),
("POST", "/service-accounts/{sa_id}/revoke"),
("POST", "/service-accounts/{sa_id}/rotate-credential"),
("PUT", "/service-accounts/{sa_id}/roles"),
}
# Collect actual endpoints from router
actual_endpoints = set()
for route in router.routes:
for method in route.methods:
actual_endpoints.add((method, route.path))
# Verify all expected endpoints exist
for expected in expected_endpoints:
assert expected in actual_endpoints, f"Missing endpoint: {expected}"
# Helper function to check if a callable is a require_permission closure
# capturing "request.service_account.manage"
def is_sa_permission_dep(func):
"""Check if func is a require_permission closure for SA management."""
if func is None:
return False
# Check if it's a closure (require_permission returns a closure)
if hasattr(func, '__closure__') and func.__closure__:
for cell in func.__closure__:
try:
val = cell.cell_contents
if val == "request.service_account.manage":
return True
except ValueError:
pass
return False
# Helper function to recursively search dependencies
def find_permission_dep(deps):
"""Search for the SA management permission dependency in dependency tree."""
for dep in deps:
# Check the callable directly
if hasattr(dep, 'call') and is_sa_permission_dep(dep.call):
return True
# Check sub-dependencies recursively
if hasattr(dep, 'dependencies'):
if find_permission_dep(dep.dependencies):
return True
return False
# Verify each endpoint has the permission dependency
for route in router.routes:
if not hasattr(route, 'dependant'):
continue
deps = route.dependant.dependencies
# Find which methods this route handles
methods = route.methods if hasattr(route, 'methods') else {'GET'}
path = route.path
# Verify the permission dependency exists
has_permission_dep = find_permission_dep(deps)
assert has_permission_dep, (
f"{methods} {path} is not protected by "
f"require_permission('request.service_account.manage')"
)
# === SINGLE ACTIVE CREDENTIAL TESTS ===
def test_single_active_credential(seeded_db):
"""Test that only one ACTIVE credential can exist at a time."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.models.service_account_credential import ServiceAccountCredential, CredentialState
from request_app.core.service_account_auth import create_credential
sa = ServiceAccount(identifier="single-cred-sa", display_name="SingleCred", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
# Create first credential
cred1, secret1 = create_credential(seeded_db, sa)
assert cred1.state == CredentialState.ACTIVE
# Create second credential (should rotate first)
cred2, secret2 = create_credential(seeded_db, sa)
assert cred2.state == CredentialState.ACTIVE
# Refresh first credential
seeded_db.refresh(cred1)
assert cred1.state == CredentialState.ROTATED
# Count ACTIVE credentials
active_count = seeded_db.query(ServiceAccountCredential).filter(
ServiceAccountCredential.service_account_id == sa.id,
ServiceAccountCredential.state == CredentialState.ACTIVE,
).count()
assert active_count == 1
def test_rotation_leaves_one_active(seeded_db):
"""Test that rotation leaves exactly one ACTIVE credential."""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.models.service_account_credential import ServiceAccountCredential, CredentialState
from request_app.core.service_account_auth import create_credential, rotate_credential
sa = ServiceAccount(identifier="rotate-single-sa", display_name="RotateSingle", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
# Create initial credential
cred1, _ = create_credential(seeded_db, sa)
# Rotate
cred2, _ = rotate_credential(seeded_db, sa)
# Count ACTIVE credentials
active_count = seeded_db.query(ServiceAccountCredential).filter(
ServiceAccountCredential.service_account_id == sa.id,
ServiceAccountCredential.state == CredentialState.ACTIVE,
).count()
assert active_count == 1
assert cred2.state == CredentialState.ACTIVE
# === PLATFORM INDEPENDENCE TEST ===
def test_validate_credential_is_platform_independent(seeded_db):
"""Test that validate_credential() works without any Platform dependency.
Evidence boundary: validates credential → ServiceAccount, no HTTP calls.
"""
from request_app.models.service_account import ServiceAccount, ServiceAccountState
from request_app.core.service_account_auth import create_credential, validate_credential
sa = ServiceAccount(identifier="platform-independent-sa", display_name="Offline", state=ServiceAccountState.ACTIVE)
seeded_db.add(sa)
seeded_db.flush()
_, secret = create_credential(seeded_db, sa)
# Validation works without Platform (no HTTP calls in this path)
result = validate_credential(seeded_db, "platform-independent-sa", secret)
assert result is not None
assert result.id == sa.id
# === CATALOG/POLICY TESTS ===
def test_management_api_permission_in_catalog(seeded_db):
"""Test that request.service_account.manage permission exists in catalog."""
from request_app.models.permission import Permission
perm = seeded_db.query(Permission).filter(Permission.name == "request.service_account.manage").first()
assert perm is not None
assert perm.is_system == True
def test_admin_has_sa_manage_permission(seeded_db):
"""Test that admin role has request.service_account.manage permission."""
from request_app.models.role import Role
from request_app.models.user import User
from request_app.models.user_role import UserRole
from request_app.api.v1.routes.permissions import compute_effective_policy
# Create admin user
user = User(email="admin@test.com", first_name="Admin", last_name="User", source="local")
seeded_db.add(user)
seeded_db.flush()
admin_role = seeded_db.query(Role).filter(Role.name == "admin").first()
seeded_db.add(UserRole(user_id=user.id, role_id=admin_role.id))
seeded_db.commit()
# Check permissions
perms = compute_effective_policy(user, seeded_db)
assert "request.service_account.manage" in perms