feat(identity): enforce shared session and browser request security

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:33:40 +03:00
1 parent 7df521bd89
commit 86f562f5b6
23 files changed
+430 -121

No files matched your search

+12 -12
View File
@@ -102,7 +102,7 @@ The ML service answers its errors with the same `Problem` schema. Its `ProblemCo
### Identity: sessions, cookie, and CSRF
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. Session security allows only the last three protected operations; other operations that require a session remain closed with 401 `unauthenticated`. Frontend registration and confirmation screens remain placeholders.
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Other protected operations pass the boundary but answer 501 `not_implemented` after request validation until their business handlers exist. Frontend registration and confirmation screens remain placeholders.
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -140,7 +140,7 @@ Sessions and CSRF:
- Implemented session operations: Login issues a `__Host-lincodex_session` cookie with `Path=/; Secure; HttpOnly; SameSite=Strict`, no Domain, and Expires/Max-Age at the absolute session deadline. PostgreSQL stores only the SHA-256 hash of the cookie token; the current-session GET returns the account and CSRF token after a reload. Successful login transactionally revokes an active session from the request and creates a new one; only a verified account can sign in. Logout revokes the session and clears the cookie; an expired or revoked cookie is also cleared on 401. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` (range `1m` to `30d`) and `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` (range `1m` to `365d`); idle cannot exceed absolute, and invalid values stop startup. Requests extend only the idle deadline.
- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the current session's token from `Session.csrf_token`. The backend derives it with domain-separated HMAC-SHA-256 from the cookie token and `IDENTITY_KEY_SECRET`, compares it in constant time, and does not store it in the database. All instances must share one `IDENTITY_KEY_SECRET` (at least 32 bytes), stable across restarts; changing it invalidates old CSRF values but does not revoke PostgreSQL sessions. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`.
- The contract requires the exact configured public Origin on every unsafe request, including public operations. The backend currently checks the sole `Origin` header against `APP_PUBLIC_URL` for `ConfirmEmail`, `Login`, and `Logout`; `Logout` also requires CSRF. `RegisterAccount` and `ResendEmailVerification` do not currently check Origin, although the contract requires it. The backend does not derive Origin from `Host` or trust forwarded headers for this check. Public identity operations are rate-limited (429 with `Retry-After`).
- Every unsafe public identity operation requires exactly one `Origin` header matching `APP_PUBLIC_URL`, including `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`. Unsafe operations protected by a session also require the session-bound CSRF token. Origin checks do not use `Host` or forwarded headers. Public identity operations are rate-limited (429 with `Retry-After`).
- Responses with a session or account carry `Cache-Control: no-store`.
- The root `security` requires `sessionCookie`, so an operation that does not declare `security: []` is protected by default.
@@ -148,11 +148,11 @@ How the generated server (ogen v1.24.0) evaluates the schemes, and how `v1.Sessi
- It calls `HandleSessionCookie` before `HandleSessionCsrf` and passes the context returned by a successful call on. An absent value (no cookie, empty `X-CSRF-Token`) does not call the handler, and a handler that returns `ogenerrors.ErrSkipServerSecurity` counts as unsatisfied; both continue with the next scheme, so `HandleSessionCsrf` also runs without a cookie, with the original context.
- Any other handler error stops evaluation and reaches `NewError` as a `SecurityError` whose `Security` is `SessionCookie` or `SessionCsrf`. An unsatisfied requirement reaches `NewError` as a `SecurityError` with `ErrSecurityRequirementIsNotSatisfied` and no `Security` field.
- Implemented mapping: `HandleSessionCookie` authenticates only `GetCurrentSession`, `GetCurrentAccount`, and `Logout`; missing, unknown, expired, or revoked sessions leave the requirement unsatisfied. `HandleSessionCsrf` checks Origin and the token only for `Logout`; without a principal the result is 401, while a wrong Origin or CSRF token with a valid principal is 403 `csrf_check_failed`. Other protected operations fail the allowlist and remain 401 `unauthenticated`. A 401 from `Logout` also clears the cookie.
- Implemented mapping: `HandleSessionCookie` authenticates every operation whose contract requires `sessionCookie`; missing, unknown, expired, revoked, or unverified sessions leave the requirement unsatisfied and answer 401 `unauthenticated`. For protected unsafe operations, `HandleSessionCsrf` checks the exact Origin and the token for that same session. Without a verified principal the result is 401; with one, a missing or wrong Origin or CSRF token is 403 `csrf_check_failed`. A 401 from `Logout` also clears the cookie, while a 403 leaves a valid session intact.
### Catalog and questionnaire
The `catalog` and `candidate` tags cover the specialization catalog and the candidate questionnaire (PRD FR03). The operations are in the contract; their business logic is not implemented yet, so the catalog answers 501 `not_implemented` and the questionnaire answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`).
The `catalog` and `candidate` tags cover the specialization catalog and the candidate questionnaire (PRD FR03). The catalog is public and answers 501 `not_implemented` until its handler exists. The questionnaire is protected: a guest answers 401 `unauthenticated`, while a valid session passes the security boundary and reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -180,7 +180,7 @@ Questionnaire:
### Candidate profile
The `candidate` tag also describes the private candidate profile that the candidate fills in by hand (FR02 in the PRD). The operations are in the contract and the business logic is not implemented yet, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` once a session is accepted and the schema is valid.
The `candidate` tag also describes the private candidate profile that the candidate fills in by hand (FR02 in the PRD). The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
| Method and path | operationId | Protection | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -238,7 +238,7 @@ Open questions for the product owner and legal:
### Assessment
The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`).
The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -315,7 +315,7 @@ Planned, additive: a short approach description of up to 1500 characters next to
### Needs
The `need` tag covers the hiring needs of an organization (PRD FR08, with the versions of FR10): requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`).
The `need` tag covers the hiring needs of an organization (PRD FR08, with the versions of FR10): requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -382,7 +382,7 @@ Planned, additive: reading and comparing versions, exclusions, the market range
### Support cases
The `support` tag covers the cases of the current account (PRD FR18, with the manual assessment of FR04 and C3): questions to support, complaints, appeals of a grade or an anti-cheat decision, and manual assessment requests. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`).
The `support` tag covers the cases of the current account (PRD FR18, with the manual assessment of FR04 and C3): questions to support, complaints, appeals of a grade or an anti-cheat decision, and manual assessment requests. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -448,7 +448,7 @@ Planned contract changes (new enum values; like the catalog codes, generated cli
### Invitations and contact grants
The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`).
The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -530,7 +530,7 @@ No new problem code is added: the `ProblemCode` enum is copied byte-for-byte int
### Consents
The `consent` tag covers the consent ledger of the current account (PRD FR01, FR12, and 7.3): the independent consents C1-C5 with their text versions, sources, states, and revocations. The read operation is in the contract; its handler is not implemented yet, so it answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind it exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#consent-ledger)).
The `consent` tag covers the consent ledger of the current account (PRD FR01, FR12, and 7.3): the independent consents C1-C5 with their text versions, sources, states, and revocations. The read operation is in the contract but its handler is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented`. The storage behind it exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#consent-ledger)).
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -548,7 +548,7 @@ No new problem code is added: the contract reuses `validation_failed` and `unaut
### Organizations
The `organization` tag covers the organizations of employer accounts and the memberships that give an account its role in them (PRD FR07, 2.2, and 6.4): the profile with its public contacts and representatives, the verification level that only the server sets, and the active organization context. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind them exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships)); creating, editing, and the membership checks of the other operations are planned as part of organization management and access control.
The `organization` tag covers the organizations of employer accounts and the memberships that give an account its role in them (PRD FR07, 2.2, and 6.4): the profile with its public contacts and representatives, the verification level that only the server sets, and the active organization context. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. The storage behind them exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships)); creating, editing, and the membership checks of the other operations are planned as part of organization management and access control.
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -613,7 +613,7 @@ No new problem code is added: the contract reuses `validation_failed`, `unauthen
### Candidate visibility
The tag `privacy` describes what organizations may see of the current candidate: the publication of the anonymous card, the search status, the organizations the candidate hides the profile from, a preview, and two histories (FR02 and FR12 in the PRD). The operations are in the contract but their business logic is not implemented, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` after an accepted session and a valid request. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)).
The tag `privacy` describes what organizations may see of the current candidate: the publication of the anonymous card, the search status, the organizations the candidate hides the profile from, a preview, and two histories (FR02 and FR12 in the PRD). The operations are in the contract but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)).
| Method and path | operationId | Protection | Success | Specific errors |
| --- | --- | --- | --- | --- |
+12 -12
View File
@@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Identity: сессии, cookie и CSRF
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session security разрешает только последние три защищенные операции; остальные операции, требующие сессию, остаются закрытыми с 401 `unauthenticated`. Экраны регистрации и подтверждения во frontend остаются заглушками.
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Остальные защищенные операции проходят эту границу, но отвечают 501 `not_implemented` после проверки запроса, пока для них нет бизнес-обработчиков. Экраны регистрации и подтверждения во frontend остаются заглушками.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -140,7 +140,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- Реализованные операции сессии: Login выдает cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict`, без Domain, и с Expires/Max-Age до абсолютного срока. PostgreSQL хранит только SHA-256 хеш cookie token; GET текущей сессии возвращает аккаунт и CSRF-токен после перезагрузки. Успешный вход отзывает действующую сессию из запроса и создает новую транзакционно; войти может только подтвержденный аккаунт. Logout отзывает сессию и очищает cookie; устаревшая или отозванная cookie также очищается с ответом 401. `IDENTITY_SESSION_IDLE_TIMEOUT` по умолчанию `24h` (от `1m` до `30d`), а `IDENTITY_SESSION_ABSOLUTE_LIFETIME` по умолчанию `168h` (от `1m` до `365d`); idle timeout не может превышать absolute lifetime, некорректные значения останавливают запуск. Запросы продлевают только idle deadline.
- Схема `sessionCsrf` - заголовок `X-CSRF-Token` с токеном для текущей сессии из `Session.csrf_token`. Backend выводит его через domain-separated HMAC-SHA-256 из cookie token и `IDENTITY_KEY_SECRET`, сравнивает за постоянное время и не хранит в БД. Все экземпляры должны использовать один `IDENTITY_KEY_SECRET` (не менее 32 байт), одинаковый между перезапусками; смена ключа делает прежние CSRF-токены недействительными, но не отзывает сессии PostgreSQL. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`.
- Контракт требует точный Origin с настроенным публичным origin для любого небезопасного запроса, включая публичные; backend сейчас проверяет единственный заголовок `Origin` на точное совпадение с `APP_PUBLIC_URL` в `ConfirmEmail`, `Login` и `Logout`. Logout дополнительно требует CSRF токен. `RegisterAccount` и `ResendEmailVerification` пока не проверяют Origin, хотя контракт этого требует. Backend не выводит origin из `Host` и не доверяет forwarded headers для этой проверки. Публичные операции identity ограничены по частоте (429 с `Retry-After`).
- Каждая небезопасная публичная identity-операция требует ровно один заголовок `Origin`, совпадающий с `APP_PUBLIC_URL`, включая `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail` и `Login`. Небезопасные защищенные операции также требуют session-bound CSRF-токен. Проверка Origin не использует `Host` или forwarded headers. Публичные identity-операции ограничены по частоте (429 с `Retry-After`).
- Ответы с сессией или аккаунтом несут `Cache-Control: no-store`.
- Корневой `security` требует `sessionCookie`, поэтому операция без явного `security: []` защищена по умолчанию.
@@ -148,11 +148,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- Он вызывает `HandleSessionCookie` раньше `HandleSessionCsrf` и передает дальше контекст, возвращенный успешным вызовом. Отсутствующее значение (нет cookie, пустой `X-CSRF-Token`) не вызывает обработчик, а обработчик, вернувший `ogenerrors.ErrSkipServerSecurity`, считается невыполненным; в обоих случаях проверка продолжается со следующей схемы, поэтому `HandleSessionCsrf` вызывается и без cookie, с исходным контекстом.
- Любая другая ошибка обработчика останавливает проверку и попадает в `NewError` как `SecurityError` с `Security`, равным `SessionCookie` или `SessionCsrf`. Невыполненное требование попадает в `NewError` как `SecurityError` с `ErrSecurityRequirementIsNotSatisfied` и без поля `Security`.
- Реализованное отображение: `HandleSessionCookie` аутентифицирует только `GetCurrentSession`, `GetCurrentAccount` и `Logout`; для отсутствующей, неизвестной, истекшей или отозванной сессии проверка не выполнена. `HandleSessionCsrf` проверяет Origin и токен только для `Logout`; без principal отказ остается 401, неверный Origin или CSRF с действующим principal дает 403 `csrf_check_failed`. Другие protected operations не проходят allowlist и остаются 401 `unauthenticated`. 401 от `Logout` также очищает cookie.
- Реализованное отображение: `HandleSessionCookie` аутентифицирует каждую операцию, для которой контракт требует `sessionCookie`; отсутствующая, неизвестная, истекшая, отозванная или неподтвержденная сессия отвечает 401 `unauthenticated`. Для небезопасных защищенных операций `HandleSessionCsrf` проверяет точный Origin и токен той же сессии. Без подтвержденного principal результат - 401; с ним отсутствующий или неверный Origin либо CSRF дает 403 `csrf_check_failed`. Ответ 401 от `Logout` также очищает cookie, а 403 сохраняет действующую сессию.
### Каталог и анкета
Теги `catalog` и `candidate` описывают каталог специализаций и анкету кандидата (FR03 в PRD). Операции есть в контракте, бизнес-логика еще не реализована: каталог отвечает 501 `not_implemented`, а анкета - 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`).
Теги `catalog` и `candidate` описывают каталог специализаций и анкету кандидата (FR03 в PRD). Каталог публичный и отвечает 501 `not_implemented`, пока не появится его обработчик. Анкета защищена: гость получает 401 `unauthenticated`, а запрос с действующей сессией проходит security boundary и после проверки запроса достигает 501 `not_implemented`. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -180,7 +180,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Профиль кандидата
Тег `candidate` описывает и приватный профиль кандидата, который кандидат заполняет вручную (FR02 в PRD). Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидной схемы - 501 `not_implemented`.
Тег `candidate` описывает и приватный профиль кандидата, который кандидат заполняет вручную (FR02 в PRD). Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -238,7 +238,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Оценка
Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`).
Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -315,7 +315,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Потребности
Тег `need` описывает потребности организации в найме (FR08 в PRD, с версиями из FR10): требования с состоянием подтверждения и происхождением, неизменяемые версии, готовность и рекомендации категорий. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`).
Тег `need` описывает потребности организации в найме (FR08 в PRD, с версиями из FR10): требования с состоянием подтверждения и происхождением, неизменяемые версии, готовность и рекомендации категорий. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -382,7 +382,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Обращения
Тег `support` описывает обращения текущего аккаунта (FR18 в PRD, с ручной оценкой из FR04 и C3): вопросы в поддержку, жалобы, апелляции грейда и античит-решения, запросы ручной оценки. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`).
Тег `support` описывает обращения текущего аккаунта (FR18 в PRD, с ручной оценкой из FR04 и C3): вопросы в поддержку, жалобы, апелляции грейда и античит-решения, запросы ручной оценки. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -448,7 +448,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Приглашения и контактные разрешения
Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Операции есть в контракте; их бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока нет сессий (`v1.DenyAllSecurity`).
Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -530,7 +530,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Согласия
Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Операция чтения есть в контракте, но ее обработчик еще не реализован, поэтому до появления сессий она отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ней уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#журнал-согласий)).
Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Операция чтения есть в контракте, но ее обработчик еще не реализован: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented`. Хранение за ней уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#журнал-согласий)).
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -548,7 +548,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Организации
Тег `organization` описывает организации аккаунтов работодателя и членства, которые дают аккаунту роль в них (FR07, 2.2 и 6.4 в PRD): профиль с публичными контактами и представителями, уровень проверки, который задает только сервер, и активный контекст организации. Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому до появления сессий каждая отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ними уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства)); создание, редактирование и проверки членства в остальных операциях запланированы в управлении организациями и контроле доступа.
Тег `organization` описывает организации аккаунтов работодателя и членства, которые дают аккаунту роль в них (FR07, 2.2 и 6.4 в PRD): профиль с публичными контактами и представителями, уровень проверки, который задает только сервер, и активный контекст организации. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. Хранение за ними уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства)); создание, редактирование и проверки членства в остальных операциях запланированы в управлении организациями и контроле доступа.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -613,7 +613,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Видимость кандидата
Тег `privacy` описывает, что организации могут видеть о текущем кандидате: публикацию анонимной карточки, статус поиска, организации, от которых кандидат скрывает профиль, предпросмотр и две истории (FR02 и FR12 в PRD). Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидного запроса - 501 `not_implemented`. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)).
Тег `privacy` описывает, что организации могут видеть о текущем кандидате: публикацию анонимной карточки, статус поиска, организации, от которых кандидат скрывает профиль, предпросмотр и две истории (FR02 и FR12 в PRD). Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)).
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |