diff --git a/api/README.en.md b/api/README.en.md index e20b7a6..8758222 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -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. 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. +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. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -530,21 +530,30 @@ 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 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)). +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. Implemented handlers provide public C1 text, current settings text and the caller's own history, settings grants of C1/C2/C3/C5, revocation of C2/C3/C5, scoped C4 revocation for one organization, and a durable C1 account-deletion request. The request does not synchronously delete the account. Protected operations require an active verified PostgreSQL session; mutations also require the session-bound CSRF token and the sole `Origin` matching `APP_PUBLIC_URL`. Guests receive 401; a disallowed account role, Origin, or CSRF token receives 403. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | +| `GET /api/v1/identity/consent-texts/c1` | `GetConsentText` | public | 200 `ConsentText` | 400 `validation_failed` | +| `GET /api/v1/me/consent-texts/{purpose}` | `GetMyConsentText` | session | 200 `ConsentText`, `Cache-Control: no-store` | 400, 401 | | `GET /api/v1/me/consents` | `ListMyConsents` | session | 200 `ConsentRecordList`, `Cache-Control: no-store` | 400, 401 | +| `PUT /api/v1/me/consents/{purpose}` | `GrantMyConsent` | session and CSRF | 200 `ConsentRecord`, `Cache-Control: no-store` | 400, 401, 403 | +| `DELETE /api/v1/me/consents/{purpose}` | `RevokeMyConsent` | session and CSRF | 204 | 401, 403 | +| `DELETE /api/v1/me/consents/c4/organizations/{org_id}` | `RevokeMyOrganizationContactConsent` | session and CSRF | 204 | 400, 401, 403 | +| `POST /api/v1/me/account-deletion-requests` | `RequestMyAccountDeletion` | session and CSRF | 202 `ConsentDeletionRequest`, `Cache-Control: no-store` | 401, 403 | -- Purposes (`ConsentPurposeCode`): `c1` personal data processing, `c2` publication of the candidate card, `c3` automatic categorization, `c4` transfer of selected contacts to one organization, `c5` import of FSP results. `ConsentPurpose` stays the subset whose text is public before registration (`c1`), so `GetConsentText` does not widen. +- Purposes (`ConsentPurposeCode`): `c1` personal data processing, `c2` publication of the candidate card, `c3` automatic categorization, `c4` transfer of selected contacts to one organization, `c5` import of FSP results. Public `GetConsentText` remains C1-only. `GetMyConsentText` returns the current C1/C2/C3/C5 text before a settings grant. C4 text remains part of an invitation with its specific scope. - The subject comes from the session; no parameter names an account, so the response holds only the caller's own records. A page lists records newest grant first with cursor pagination; the optional `state` filter takes `active`, `superseded`, or `revoked`, and an unknown value answers 400 with the pointer `/state`. - A `ConsentRecord` has the purpose, the accepted `text_version`, the `source` (`registration`, `consent_settings`, or `invitation_acceptance`), `granted_at`, the computed `state`, and `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A `c4` record also names the `organization` (`ConsentOrganization`, whose `name` is the snapshot the consent text showed, so a later rename does not change it), the contact `fields` (`ContactFieldKind`), the `invitation_id`, and the `invitation_terms_version`; they are null for every other purpose. A `c2` record proves the consent to the publication text; which fields were published, and when, is evidence of the publication history ([Candidate visibility](#candidate-visibility)), and a field scope on `c2` records would be an additive change. The record never carries a contact value, the subject, or the text hash: the server stores the SHA-256 of exactly the text the subject saw, and the client never sends or receives it, as for C1 at registration. -- The ledger is append-only. A newer text version of a purpose is a new record and the earlier one becomes `superseded` without any change; a revocation stamps the unrevoked records of the purpose, and for `c4` of one organization, once; a later grant is a new record, and a revoked `c4` of an invitation never comes back. Purposes are independent. -- Planned, additive: granting C1, C2, C3, and C5 in the consent settings and revoking any purpose with its consequences, as new operations of this tag; C1 at registration and C4 in `AcceptMyInvitation` already have their own operations. The C4 permission to pass data on to an ATS and the C4 of an application (PRD Q9) are planned as an additive flag and an additional `source` value. +- Settings grants require explicit `accepted: true` and the current version of the text the user read. C1 is available to candidate and employer accounts; C2/C3/C5 are candidate-only. C4 is excluded from the general settings grant and is granted only when accepting a specific invitation. +- The ledger is append-only. A newer text version is a new record and the earlier one becomes `superseded` without changes; revocation stamps every unrevoked record of the purpose, including earlier versions. C4 revocation is limited to one organization and takes its fields from stored records, never from request data. Repeated revocation is harmless and creates no duplicate event. +- C2 revocation closes the current publication, clears its fields, appends privacy history, and writes a bounded outbox intent in one transaction. A later C2 grant does not reopen the old publication. C3 revocation does not block the manual assessment path. C5 revocation immediately closes the consent gate for future imports and writes a stop/delete intent; no external FSP adapter exists, so actual deletion at FSP is not claimed. +- A C1 deletion request revokes C1 and creates or returns an active durable request plus an outbox intent in one transaction. Repeats return the same request; a later C1 grant never cancels it. The future account-deletion processor is not synchronous and is not implemented yet. +- The C4 permission to pass data on to an ATS and the C4 of an application (PRD Q9) are planned as an additive flag and an additional `source` value. Open legal item: whether `c2` is a consent to the distribution of personal data under article 10.1 of 152-FZ, which requires its own consent with the categories of data. -No new problem code is added: the contract reuses `validation_failed` and `unauthenticated`. `TestConsentSchemaValidationPrecedesImplementation`, `TestConsentAccessBeforeImplementation`, and `TestConsentDTOsCarryNoHashSubjectOrContact` pin the generated server, and `frontend/src/shared/api/consent-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of hash, subject, and contact fields. +No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, and `csrf_check_failed`. Contract tests pin the security schemes and validation order, `TestConsentSettingsOverHTTP` exercises consent behavior with real PostgreSQL and Redis, and `frontend/src/shared/api/consent-contract.test.ts` pins generated Zod rules and the absence of hashes, subjects, and contacts from the DTOs. ### Organizations diff --git a/api/README.md b/api/README.md index 19502a6..e3a2c83 100644 --- a/api/README.md +++ b/api/README.md @@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Identity: сессии, cookie и CSRF -Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Остальные защищенные операции проходят эту границу, но отвечают 501 `not_implemented` после проверки запроса, пока для них нет бизнес-обработчиков. Экраны регистрации и подтверждения во frontend остаются заглушками. +Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Помимо identity и перечисленных ниже операций согласий, защищенные бизнес-операции пока проходят security boundary и отвечают 501 `not_implemented` после проверки запроса. Экраны регистрации и подтверждения во frontend остаются заглушками. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -530,21 +530,30 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Согласия -Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Операция чтения есть в контракте, но ее обработчик еще не реализован: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented`. Хранение за ней уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#журнал-согласий)). +Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Реализованы публичное чтение C1, чтение текущих текстов настроек и собственной истории, выдача C1/C2/C3/C5, отзыв C2/C3/C5 и отзыв C4 в области одной организации. Запрос C1 создает долговечный запрос на удаление аккаунта; сама запись аккаунта не удаляется синхронно. Эти обработчики требуют действующую подтвержденную PostgreSQL-сессию, а изменяющие операции также требуют session-bound CSRF и единственный `Origin`, совпадающий с `APP_PUBLIC_URL`. Гость получает 401; неподходящая роль, неверный Origin или CSRF получают 403. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | +| `GET /api/v1/identity/consent-texts/c1` | `GetConsentText` | публичная | 200 `ConsentText` | 400 `validation_failed` | +| `GET /api/v1/me/consent-texts/{purpose}` | `GetMyConsentText` | сессия | 200 `ConsentText`, `Cache-Control: no-store` | 400, 401 | | `GET /api/v1/me/consents` | `ListMyConsents` | сессия | 200 `ConsentRecordList`, `Cache-Control: no-store` | 400, 401 | +| `PUT /api/v1/me/consents/{purpose}` | `GrantMyConsent` | сессия и CSRF | 200 `ConsentRecord`, `Cache-Control: no-store` | 400, 401, 403 | +| `DELETE /api/v1/me/consents/{purpose}` | `RevokeMyConsent` | сессия и CSRF | 204 | 401, 403 | +| `DELETE /api/v1/me/consents/c4/organizations/{org_id}` | `RevokeMyOrganizationContactConsent` | сессия и CSRF | 204 | 400, 401, 403 | +| `POST /api/v1/me/account-deletion-requests` | `RequestMyAccountDeletion` | сессия и CSRF | 202 `ConsentDeletionRequest`, `Cache-Control: no-store` | 401, 403 | -- Цели (`ConsentPurposeCode`): `c1` - обработка персональных данных, `c2` - публикация карточки кандидата, `c3` - автоматическая категоризация, `c4` - передача выбранных контактов одной организации, `c5` - импорт результатов ФСП. `ConsentPurpose` остается подмножеством, текст которого доступен до регистрации (`c1`), поэтому `GetConsentText` не расширяется. +- Цели (`ConsentPurposeCode`): `c1` - обработка персональных данных, `c2` - публикация карточки кандидата, `c3` - автоматическая категоризация, `c4` - передача выбранных контактов одной организации, `c5` - импорт результатов ФСП. Публичный `GetConsentText` остается доступен только для C1; `GetMyConsentText` возвращает текущий текст C1/C2/C3/C5 перед выдачей в настройках. Текст C4 остается частью приглашения с его конкретной областью. - Субъект берется из сессии; ни один параметр не называет аккаунт, поэтому ответ содержит только собственные записи вызывающего. Страница перечисляет записи от новой выдачи к старой с курсорной пагинацией; необязательный фильтр `state` принимает `active`, `superseded` или `revoked`, а неизвестное значение отвечает 400 с указателем `/state`. - `ConsentRecord` содержит цель, принятую `text_version`, `source` (`registration`, `consent_settings` или `invitation_acceptance`), `granted_at`, вычисленное `state`, а также `revoked_at` и `revocation_source` (`consent_settings` или `support_request`). Запись `c4` дополнительно называет `organization` (`ConsentOrganization`, где `name` - снимок названия из текста согласия, поэтому последующее переименование его не меняет), поля контакта `fields` (`ContactFieldKind`), `invitation_id` и `invitation_terms_version`; для остальных целей они равны null. Запись `c2` доказывает согласие с текстом публикации; какие поля и когда опубликованы - доказательства истории публикации ([Видимость кандидата](#видимость-кандидата)), а scope полей в записях `c2` был бы аддитивным изменением. Запись никогда не содержит значения контакта, субъекта или хэш текста: сервер хранит SHA-256 ровно того текста, который видел субъект, а клиент его не отправляет и не получает, как и для C1 при регистрации. -- Журнал только дополняется. Новая версия текста цели - новая запись, а прежняя становится `superseded` без изменений; отзыв один раз ставит отметку на неотозванные записи цели, а для `c4` - одной организации; последующая выдача - новая запись, и отозванное `c4` приглашения не возвращается. Цели независимы. -- Запланировано, аддитивно: выдача C1, C2, C3 и C5 в настройках согласий и отзыв любой цели с последствиями новыми операциями этого тега; у C1 при регистрации и C4 в `AcceptMyInvitation` уже есть свои операции. Разрешение C4 на передачу данных в ATS и C4 при отклике (Q9 в PRD) запланированы как аддитивный флаг и дополнительное значение `source`. +- Выдача в настройках требует явного `accepted: true` и текущую версию прочитанного текста. C1 можно выдать аккаунту кандидата или работодателя; C2/C3/C5 доступны только кандидату. C4 нельзя выдать общей операцией настроек: он выдается только принятием конкретного приглашения. +- Журнал только дополняется. Новая версия текста цели - новая запись, а прежняя становится `superseded` без изменений; отзыв ставит отметку на все неотозванные записи цели, включая прежние версии. Отзыв C4 действует только для одной организации и берет набор полей из сохраненных записей, не из запроса. Повтор отзыва безопасен и не создает второе событие. +- Отзыв C2 в одной транзакции закрывает действующую публикацию, очищает ее поля, добавляет запись privacy history и пишет ограниченный по размеру outbox intent. Новая выдача C2 не открывает прежнюю публикацию. Отзыв C3 не блокирует ручной путь оценки. Отзыв C5 немедленно закрывает consent gate для будущего импорта и пишет stop/delete intent; внешнего адаптера ФСП нет, поэтому фактическое удаление данных во ФСП не заявляется. +- Запрос удаления C1 отзывает C1 и создает или возвращает активный запрос удаления и outbox intent в одной транзакции. Повтор возвращает тот же запрос; последующая выдача C1 его не отменяет. Обработчик будущего удаления аккаунта не синхронен и пока отсутствует. +- Разрешение C4 на передачу данных в ATS и C4 при отклике (Q9 в PRD) запланированы как аддитивный флаг и дополнительное значение `source`. Открытый юридический вопрос: является ли `c2` согласием на распространение персональных данных по статье 10.1 152-ФЗ, которое требует отдельного согласия с категориями данных. -Новый код problem не добавляется: контракт использует `validation_failed` и `unauthenticated`. `TestConsentSchemaValidationPrecedesImplementation`, `TestConsentAccessBeforeImplementation` и `TestConsentDTOsCarryNoHashSubjectOrContact` закрепляют сгенерированный сервер, а `frontend/src/shared/api/consent-contract.test.ts` - сгенерированные правила Zod и, на уровне типов, отсутствие полей хэша, субъекта и контактов. +Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden` и `csrf_check_failed`. Контрактные тесты закрепляют security-схемы и порядок валидации, `TestConsentSettingsOverHTTP` проверяет согласия с настоящими PostgreSQL и Redis, а `frontend/src/shared/api/consent-contract.test.ts` закрепляет сгенерированные правила Zod и отсутствие в DTO хэшей, субъекта и контактов. ### Организации diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index d0d4a8b..21ba511 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -2531,6 +2531,21 @@ ConsentPurposeCode: - c3 - c4 - c5 +ConsentSettingsPurpose: + type: string + description: Consent text that an authenticated account can read and accept in settings. C4 is scoped to an invitation and organization, so it is not available through the general settings flow. + enum: + - c1 + - c2 + - c3 + - c5 +ConsentSettingsRevokePurpose: + type: string + description: Consent that can be revoked through the general settings flow. C1 uses the account deletion request, and C4 must be revoked for one organization. + enum: + - c2 + - c3 + - c5 ConsentState: type: string description: 'State of a consent record, computed from the ledger. @@ -2676,6 +2691,42 @@ ConsentRecordList: $ref: '#/ConsentRecord' page: $ref: '#/PageInfo' +ConsentSettingsGrantRequest: + type: object + description: Accept the current published text shown by GetMyConsentText. The server checks its version again before recording the grant. + additionalProperties: false + required: + - text_version + - accepted + properties: + text_version: + $ref: '#/ConsentTextVersion' + accepted: + type: boolean + enum: + - true + description: Must be true to record an explicit acceptance. +ConsentDeletionRequest: + type: object + description: Durable request to delete the account and its personal data. The request is recorded before asynchronous processing starts; it does not mean deletion has completed. + additionalProperties: false + required: + - id + - status + - requested_at + properties: + id: + type: string + format: uuid + description: Identifier of the durable deletion request. + status: + type: string + enum: + - requested + - processing + description: Current state of the deletion request. + requested_at: + $ref: '#/Timestamp' ContactFieldKind: type: string description: 'Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another. @@ -2989,7 +3040,7 @@ ConsentText: - published_at properties: purpose: - $ref: '#/ConsentPurpose' + $ref: '#/ConsentPurposeCode' text_version: $ref: '#/ConsentTextVersion' text: diff --git a/api/core/components/schemas/consent_schemas.yml b/api/core/components/schemas/consent_schemas.yml index e9c12e3..f2d18fe 100644 --- a/api/core/components/schemas/consent_schemas.yml +++ b/api/core/components/schemas/consent_schemas.yml @@ -17,6 +17,27 @@ schemas: - c3 - c4 - c5 + ConsentSettingsPurpose: + type: string + description: >- + Consent text that an authenticated account can read and accept in + settings. C4 is scoped to an invitation and organization, so it is not + available through the general settings flow. + enum: + - c1 + - c2 + - c3 + - c5 + ConsentSettingsRevokePurpose: + type: string + description: >- + Consent that can be revoked through the general settings flow. C1 uses + the account deletion request, and C4 must be revoked for one + organization. + enum: + - c2 + - c3 + - c5 ConsentState: type: string description: |- @@ -180,3 +201,44 @@ schemas: $ref: "#/schemas/ConsentRecord" page: $ref: "./common_schemas.yml#/schemas/PageInfo" + ConsentSettingsGrantRequest: + type: object + description: >- + Accept the current published text shown by GetMyConsentText. The server + checks its version again before recording the grant. + additionalProperties: false + required: + - text_version + - accepted + properties: + text_version: + $ref: "./identity_schemas.yml#/schemas/ConsentTextVersion" + accepted: + type: boolean + enum: + - true + description: Must be true to record an explicit acceptance. + ConsentDeletionRequest: + type: object + description: >- + Durable request to delete the account and its personal data. The request + is recorded before asynchronous processing starts; it does not mean + deletion has completed. + additionalProperties: false + required: + - id + - status + - requested_at + properties: + id: + type: string + format: uuid + description: Identifier of the durable deletion request. + status: + type: string + enum: + - requested + - processing + description: Current state of the deletion request. + requested_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" diff --git a/api/core/components/schemas/identity_schemas.yml b/api/core/components/schemas/identity_schemas.yml index cbe5c86..064cbf7 100644 --- a/api/core/components/schemas/identity_schemas.yml +++ b/api/core/components/schemas/identity_schemas.yml @@ -89,7 +89,7 @@ schemas: - published_at properties: purpose: - $ref: "#/schemas/ConsentPurpose" + $ref: "./consent_schemas.yml#/schemas/ConsentPurposeCode" text_version: $ref: "#/schemas/ConsentTextVersion" text: diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index ec45354..cc42005 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -88,6 +88,38 @@ paths: $ref: '#/components/responses/ValidationFailed' default: $ref: '#/components/responses/Problem' + /api/v1/me/consent-texts/{purpose}: + get: + operationId: GetMyConsentText + summary: Read a current consent text for account settings. + description: 'Requires a verified session. Returns the current published text and version of c1, c2, c3, or c5 so the user can read the exact text before an explicit settings grant. C4 is excluded: its text includes an organization snapshot and it is granted only during invitation acceptance. The response is private and is not cached.' + security: + - sessionCookie: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Consent whose current text is requested. + schema: + $ref: '#/components/schemas/ConsentSettingsPurpose' + responses: + '200': + description: The current published consent text. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentText' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + default: + $ref: '#/components/responses/Problem' /api/v1/identity/registrations: post: operationId: RegisterAccount @@ -2212,7 +2244,7 @@ paths: Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history. - Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. + Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation. Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit`, `cursor`, or `state` answers 400 validation_failed. security: @@ -2247,6 +2279,159 @@ paths: $ref: '#/components/responses/Unauthenticated' default: $ref: '#/components/responses/Problem' + /api/v1/me/consents/{purpose}: + put: + operationId: GrantMyConsent + summary: Record an explicit consent grant from settings. + description: |- + Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. The body names the current text version the user read and requires `accepted: true`; the server verifies that version is still current and stores the hash of the exact text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant. + + C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the same current version returns the existing record; after revocation a grant creates a new record and never reopens a publication or restores an older grant. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Independent consent being granted. C4 is not available here. + schema: + $ref: '#/components/schemas/ConsentSettingsPurpose' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentSettingsGrantRequest' + responses: + '200': + description: The created or existing consent record. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentRecord' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + description: CSRF or Origin validation failed, or an employer tried to grant a candidate-only purpose. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + csrf: + $ref: '#/components/examples/CsrfCheckFailed' + forbidden: + $ref: '#/components/examples/Forbidden' + default: + $ref: '#/components/responses/Problem' + delete: + operationId: RevokeMyConsent + summary: Revoke a non-scoped consent from settings. + description: |- + Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5, including superseded records, and never changes another purpose. Repeating a revocation is harmless and creates no duplicate event. + + Revoking c2 immediately closes the stored publication and records privacy history in the same transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not reopen publication or restore old grants. Revoking c3 does not block the manual assessment path. Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent; an external FSP deletion adapter is not available yet. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Consent being revoked. C1 has a deletion-request operation and C4 requires an organization scope. + schema: + $ref: '#/components/schemas/ConsentSettingsRevokePurpose' + responses: + '204': + description: Consent revoked, or it was already revoked. + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + description: CSRF or Origin validation failed, or an employer account tried to revoke candidate consent. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + csrf: + $ref: '#/components/examples/CsrfCheckFailed' + forbidden: + $ref: '#/components/examples/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/consents/c4/organizations/{org_id}: + delete: + operationId: RevokeMyOrganizationContactConsent + summary: Revoke C4 for one organization. + description: Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The server revokes every unrevoked C4 record for this subject and organization, using the fields stored on those records to request downstream grant revocation. It does not affect another organization. Repeating the request is harmless and creates no duplicate event. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: org_id + in: path + required: true + description: Organization whose stored C4 grants this account revokes. A well-formed identifier outside the account's stored records changes nothing and does not reveal whether that organization exists. + schema: + type: string + format: uuid + responses: + '204': + description: C4 revoked for this organization, or no active C4 was present. + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + description: CSRF or Origin validation failed, or the caller is not a candidate. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + csrf: + $ref: '#/components/examples/CsrfCheckFailed' + forbidden: + $ref: '#/components/examples/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/account-deletion-requests: + post: + operationId: RequestMyAccountDeletion + summary: Revoke C1 and request account deletion. + description: Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. In one transaction, revokes any active C1 record, creates or returns the subject's active durable deletion request, and writes the outbox intent. The API does not delete the account synchronously. Repeating the request returns the same active request; a later C1 grant never cancels it. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + responses: + '202': + description: The durable account-deletion request is queued for processing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentDeletionRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + description: CSRF or Origin validation failed. + $ref: '#/components/responses/CsrfCheckFailed' + default: + $ref: '#/components/responses/Problem' /api/v1/me/privacy: get: operationId: GetMyPrivacySettings @@ -2990,6 +3175,21 @@ components: description: 'Consent whose text the client may read before an account exists. Only the consents given at registration are listed: `c1` is the consent to the processing of personal data.' enum: - c1 + ConsentSettingsPurpose: + type: string + description: Consent text that an authenticated account can read and accept in settings. C4 is scoped to an invitation and organization, so it is not available through the general settings flow. + enum: + - c1 + - c2 + - c3 + - c5 + ConsentSettingsRevokePurpose: + type: string + description: Consent that can be revoked through the general settings flow. C1 uses the account deletion request, and C4 must be revoked for one organization. + enum: + - c2 + - c3 + - c5 ConsentText: type: object description: Currently published consent text. The server stores an acceptance with `text_version` and the hash of exactly this text. @@ -3001,7 +3201,7 @@ components: - published_at properties: purpose: - $ref: '#/components/schemas/ConsentPurpose' + $ref: '#/components/schemas/ConsentPurposeCode' text_version: $ref: '#/components/schemas/ConsentTextVersion' text: @@ -7785,6 +7985,42 @@ components: $ref: '#/components/schemas/ConsentRecord' page: $ref: '#/components/schemas/PageInfo' + ConsentSettingsGrantRequest: + type: object + description: Accept the current published text shown by GetMyConsentText. The server checks its version again before recording the grant. + additionalProperties: false + required: + - text_version + - accepted + properties: + text_version: + $ref: '#/components/schemas/ConsentTextVersion' + accepted: + type: boolean + enum: + - true + description: Must be true to record an explicit acceptance. + ConsentDeletionRequest: + type: object + description: Durable request to delete the account and its personal data. The request is recorded before asynchronous processing starts; it does not mean deletion has completed. + additionalProperties: false + required: + - id + - status + - requested_at + properties: + id: + type: string + format: uuid + description: Identifier of the durable deletion request. + status: + type: string + enum: + - requested + - processing + description: Current state of the deletion request. + requested_at: + $ref: '#/components/schemas/Timestamp' OrganizationVersion: type: integer format: int64 @@ -9864,6 +10100,15 @@ components: pointer: /salary_from code: invalid message: The value does not match the contract. + Unauthenticated: + summary: No valid session + value: + type: urn:lincodex:problem:unauthenticated + title: Authentication required + status: 401 + code: unauthenticated + detail: Sign in and repeat the request. + trace_id: 4f2d1c3b-6a5e-4d7f-8b9a-0c1d2e3f4a5b RegistrationValidationFailed: summary: The password is too short and the consent text is outdated value: @@ -9979,15 +10224,6 @@ components: code: email_not_verified detail: Confirm the email address with the link from the verification message. trace_id: 7f8a9b0c-1d2e-4f3a-8b4c-5d6e7f8a9b0c - Unauthenticated: - summary: No valid session - value: - type: urn:lincodex:problem:unauthenticated - title: Authentication required - status: 401 - code: unauthenticated - detail: Sign in and repeat the request. - trace_id: 4f2d1c3b-6a5e-4d7f-8b9a-0c1d2e3f4a5b CandidateAccount: summary: A verified candidate on the questionnaire step value: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 875a4fe..0bbcfa3 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -81,6 +81,8 @@ paths: $ref: ./routes/healthz.yml /api/v1/identity/consent-texts/{purpose}: $ref: ./routes/identity_consent_texts.yml + /api/v1/me/consent-texts/{purpose}: + $ref: ./routes/my_consent_texts.yml /api/v1/identity/registrations: $ref: ./routes/identity_registrations.yml /api/v1/identity/email-verification-requests: @@ -149,6 +151,12 @@ paths: $ref: ./routes/candidate_invitation_cancel.yml /api/v1/me/consents: $ref: ./routes/consents.yml + /api/v1/me/consents/{purpose}: + $ref: ./routes/my_consent.yml + /api/v1/me/consents/c4/organizations/{org_id}: + $ref: ./routes/my_consent_c4.yml + /api/v1/me/account-deletion-requests: + $ref: ./routes/account_deletion_requests.yml /api/v1/me/privacy: $ref: ./routes/candidate_privacy.yml /api/v1/me/privacy/publication: @@ -195,6 +203,10 @@ components: $ref: ./components/schemas.yml#/OnboardingStep ConsentPurpose: $ref: ./components/schemas.yml#/ConsentPurpose + ConsentSettingsPurpose: + $ref: ./components/schemas.yml#/ConsentSettingsPurpose + ConsentSettingsRevokePurpose: + $ref: ./components/schemas.yml#/ConsentSettingsRevokePurpose ConsentText: $ref: ./components/schemas.yml#/ConsentText ConsentTextVersion: @@ -731,6 +743,10 @@ components: $ref: ./components/schemas.yml#/ConsentRecord ConsentRecordList: $ref: ./components/schemas.yml#/ConsentRecordList + ConsentSettingsGrantRequest: + $ref: ./components/schemas.yml#/ConsentSettingsGrantRequest + ConsentDeletionRequest: + $ref: ./components/schemas.yml#/ConsentDeletionRequest OrganizationVersion: $ref: ./components/schemas.yml#/OrganizationVersion OrganizationName: diff --git a/api/core/routes/account_deletion_requests.yml b/api/core/routes/account_deletion_requests.yml new file mode 100644 index 0000000..53ae8a5 --- /dev/null +++ b/api/core/routes/account_deletion_requests.yml @@ -0,0 +1,27 @@ +post: + operationId: RequestMyAccountDeletion + summary: Revoke C1 and request account deletion. + description: |- + Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. In one transaction, revokes any active C1 record, creates or returns the subject's active durable deletion request, and writes the outbox intent. The API does not delete the account synchronously. Repeating the request returns the same active request; a later C1 grant never cancels it. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + responses: + "202": + description: The durable account-deletion request is queued for processing. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentDeletionRequest + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + description: CSRF or Origin validation failed. + $ref: ../components/responses.yml#/CsrfCheckFailed + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/consents.yml b/api/core/routes/consents.yml index cbaeb15..d707f6a 100644 --- a/api/core/routes/consents.yml +++ b/api/core/routes/consents.yml @@ -8,7 +8,7 @@ get: Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history. - Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. + Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation. Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit`, `cursor`, or `state` answers 400 validation_failed. security: diff --git a/api/core/routes/my_consent.yml b/api/core/routes/my_consent.yml new file mode 100644 index 0000000..03ff33c --- /dev/null +++ b/api/core/routes/my_consent.yml @@ -0,0 +1,89 @@ +put: + operationId: GrantMyConsent + summary: Record an explicit consent grant from settings. + description: |- + Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. The body names the current text version the user read and requires `accepted: true`; the server verifies that version is still current and stores the hash of the exact text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant. + + C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the same current version returns the existing record; after revocation a grant creates a new record and never reopens a publication or restores an older grant. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Independent consent being granted. C4 is not available here. + schema: + $ref: ../components/schemas.yml#/ConsentSettingsPurpose + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentSettingsGrantRequest + responses: + "200": + description: The created or existing consent record. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentRecord + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + description: CSRF or Origin validation failed, or an employer tried to grant a candidate-only purpose. + content: + application/problem+json: + schema: + $ref: ../components/schemas.yml#/Problem + examples: + csrf: + $ref: ../components/examples.yml#/CsrfCheckFailed + forbidden: + $ref: ../components/examples.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem +delete: + operationId: RevokeMyConsent + summary: Revoke a non-scoped consent from settings. + description: |- + Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5, including superseded records, and never changes another purpose. Repeating a revocation is harmless and creates no duplicate event. + + Revoking c2 immediately closes the stored publication and records privacy history in the same transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not reopen publication or restore old grants. Revoking c3 does not block the manual assessment path. Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent; an external FSP deletion adapter is not available yet. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Consent being revoked. C1 has a deletion-request operation and C4 requires an organization scope. + schema: + $ref: ../components/schemas.yml#/ConsentSettingsRevokePurpose + responses: + "204": + description: Consent revoked, or it was already revoked. + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + description: CSRF or Origin validation failed, or an employer account tried to revoke candidate consent. + content: + application/problem+json: + schema: + $ref: ../components/schemas.yml#/Problem + examples: + csrf: + $ref: ../components/examples.yml#/CsrfCheckFailed + forbidden: + $ref: ../components/examples.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/my_consent_c4.yml b/api/core/routes/my_consent_c4.yml new file mode 100644 index 0000000..2968c43 --- /dev/null +++ b/api/core/routes/my_consent_c4.yml @@ -0,0 +1,39 @@ +delete: + operationId: RevokeMyOrganizationContactConsent + summary: Revoke C4 for one organization. + description: |- + Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The server revokes every unrevoked C4 record for this subject and organization, using the fields stored on those records to request downstream grant revocation. It does not affect another organization. Repeating the request is harmless and creates no duplicate event. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: org_id + in: path + required: true + description: >- + Organization whose stored C4 grants this account revokes. A well-formed + identifier outside the account's stored records changes nothing and + does not reveal whether that organization exists. + schema: + type: string + format: uuid + responses: + "204": + description: C4 revoked for this organization, or no active C4 was present. + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + description: CSRF or Origin validation failed, or the caller is not a candidate. + content: + application/problem+json: + schema: + $ref: ../components/schemas.yml#/Problem + examples: + csrf: + $ref: ../components/examples.yml#/CsrfCheckFailed + forbidden: + $ref: ../components/examples.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/my_consent_texts.yml b/api/core/routes/my_consent_texts.yml new file mode 100644 index 0000000..5828cd9 --- /dev/null +++ b/api/core/routes/my_consent_texts.yml @@ -0,0 +1,36 @@ +get: + operationId: GetMyConsentText + summary: Read a current consent text for account settings. + description: >- + Requires a verified session. Returns the current published text and version + of c1, c2, c3, or c5 so the user can read the exact text before an explicit + settings grant. C4 is excluded: its text includes an organization snapshot + and it is granted only during invitation acceptance. The response is + private and is not cached. + security: + - sessionCookie: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Consent whose current text is requested. + schema: + $ref: ../components/schemas.yml#/ConsentSettingsPurpose + responses: + "200": + description: The current published consent text. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentText + "401": + $ref: ../components/responses.yml#/Unauthenticated + "400": + $ref: ../components/responses.yml#/ValidationFailed + default: + $ref: ../components/responses.yml#/Problem diff --git a/backend/README.en.md b/backend/README.en.md index 8c13be5..bd22876 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -2,7 +2,7 @@ [Русский](README.md) | English -The main service uses Go, chi, and Clean Architecture. It currently provides health checks, registration and email verification, server-side sessions, and PostgreSQL, Redis, and SeaweedFS adapters; hiring workflows are still to be implemented. +The main service uses Go, chi, and Clean Architecture. It currently provides health checks, identity and server-side sessions, the consent ledger and settings, and PostgreSQL, Redis, and SeaweedFS adapters; the remaining hiring workflows are still to be implemented. - `cmd/app/` is the entry point; `internal/bootstrap/` wires dependencies and manages startup. - `internal/` contains domain types, use cases, ports, and primary/secondary adapters. @@ -14,7 +14,7 @@ From the repository root, `make -C backend check` runs the main checks and `make ## Server sessions -Registration, email confirmation, login, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current`, and `DELETE /api/v1/identity/sessions/current` are implemented. The session boundary authenticates every operation protected by the OpenAPI contract; handwritten handlers can read a principal containing the user ID and verified-email state resolved from the PostgreSQL session. Unknown, expired, revoked, or unverified sessions answer `401 unauthenticated`. Other protected business operations currently answer 501 after the security boundary and request validation succeed. An unknown email and an incorrect password return the same `401 invalid_credentials`; correct credentials for an unverified account return `403 email_not_verified` at login. +Registration, email confirmation, login, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current`, and `DELETE /api/v1/identity/sessions/current` are implemented. The session boundary authenticates every operation protected by the OpenAPI contract; handwritten handlers can read a principal containing the user ID and verified-email state resolved from the PostgreSQL session. Unknown, expired, revoked, or unverified sessions answer `401 unauthenticated`. Contract operations without an implemented business handler answer 501 after the security boundary and request validation succeed. An unknown email and an incorrect password return the same `401 invalid_credentials`; correct credentials for an unverified account return `403 email_not_verified` at login. Sessions are stored in PostgreSQL. The browser receives a `__Host-lincodex_session` cookie with `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/`, and no `Domain`; the database stores only the token hash. The default idle timeout is 24 hours and the absolute lifetime is 168 hours. Configure them with `IDENTITY_SESSION_IDLE_TIMEOUT` and `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; the idle timeout cannot exceed the absolute lifetime. @@ -22,4 +22,20 @@ Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerificat HTTP-flow tests with PostgreSQL and Redis are part of `make -C backend test-int`; compile the integration suite without starting containers with `make -C backend test-int-compile`. +## Consent ledger and settings + +Only the current C1 text is public for registration. A verified user can read current C1/C2/C3/C5 texts before granting them in settings and can page through their own consent history. C1 can be granted by either account scenario; C2, C3, and C5 are candidate-only. Mutations require explicit acceptance, the exact Origin, and session-bound CSRF. + +Revoking C2 makes the publication effectively closed and hides its fields through the ledger-backed read in the same transaction; the stored publication stays linked to the revoked record, so a later C2 grant cannot reopen it. Revoking C3 does not block account or profile use. A separate manual-assessment request is planned, but its endpoint is not implemented. Revoking C5 immediately closes the gate for future imports and writes an outbox intent; there is no external FSP adapter yet. C4 revocation is limited to one organization and uses the stored contact scope. A C1 request revokes consent and creates a durable deletion-request record with an outbox intent; repeats return the same active record, and the account is not deleted synchronously. + +`make -C backend test-int` runs the full HTTP flow with PostgreSQL and Redis. `TestConsentSettingsOverHTTP` covers texts, history, grants, revocation effects, and the C1 deletion request. + +## Organizations + +`POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}`, and `PATCH /api/v1/organizations/{org_id}` are implemented. A verified employer creates the organization and its active owner membership in one transaction, starting at `e0` with basis `confirmed_email`. Every read checks active membership. Only the active owner can edit; the version advances on change and the verification level is preserved. + +The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `ListMyOrganizations`, needs, and invitations remain unimplemented. + +`TestOrganizationCreationAndOwnerEditingOverHTTP` checks concurrent replay, rollback on owner insertion failure, cross-account denial, persisted reads after rebuilding the API, and reuse of an expired key against PostgreSQL. + See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md). diff --git a/backend/README.md b/backend/README.md index 5a9c719..8714ce9 100644 --- a/backend/README.md +++ b/backend/README.md @@ -2,7 +2,7 @@ Русский | [English](README.en.md) -Основной сервис на Go и chi с Clean Architecture. Сейчас реализованы проверки состояния, регистрация и подтверждение email, серверные сессии, а также адаптеры PostgreSQL, Redis и SeaweedFS; продуктовые сценарии найма еще предстоит добавить. +Основной сервис на Go и chi с Clean Architecture. Сейчас реализованы проверки состояния, identity и серверные сессии, журнал и настройки согласий, а также адаптеры PostgreSQL, Redis и SeaweedFS; остальные продуктовые сценарии найма еще предстоит добавить. - `cmd/app/` - точка входа; `internal/bootstrap/` собирает зависимости и управляет запуском. - `internal/` - доменные типы, use case, порты и primary/secondary адаптеры. @@ -14,7 +14,7 @@ ## Серверные сессии -Реализованы регистрация, подтверждение email, вход, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current` и `DELETE /api/v1/identity/sessions/current`. Session boundary аутентифицирует каждую операцию, для которой OpenAPI требует сессию; principal для handwritten handlers содержит ID и подтвержденный email из PostgreSQL-сессии. Неизвестная, истекшая, отозванная сессия и аккаунт без подтвержденного email получают `401 unauthenticated`. Остальные защищенные бизнес-операции пока отвечают 501 после успешной проверки security и запроса. Неизвестный email и неверный пароль возвращают одинаковый `401 invalid_credentials`; правильный пароль неподтвержденной учетной записи при входе дает `403 email_not_verified`. +Реализованы регистрация, подтверждение email, вход, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current` и `DELETE /api/v1/identity/sessions/current`. Session boundary аутентифицирует каждую операцию, для которой OpenAPI требует сессию; principal для handwritten handlers содержит ID и подтвержденный email из PostgreSQL-сессии. Неизвестная, истекшая, отозванная сессия и аккаунт без подтвержденного email получают `401 unauthenticated`. Защищенные бизнес-операции, для которых еще нет handler, отвечают 501 после успешной проверки security и запроса. Неизвестный email и неверный пароль возвращают одинаковый `401 invalid_credentials`; правильный пароль неподтвержденной учетной записи при входе дает `403 email_not_verified`. Сессия хранится в PostgreSQL. Браузер получает cookie `__Host-lincodex_session` с атрибутами `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/` и без `Domain`; в базе хранится только хеш токена. Время бездействия по умолчанию - 24 часа, абсолютный срок - 168 часов. Эти значения задаются через `IDENTITY_SESSION_IDLE_TIMEOUT` и `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; время бездействия не может превышать абсолютный срок. @@ -22,4 +22,20 @@ Проверки HTTP-сценариев с PostgreSQL и Redis входят в `make -C backend test-int`; компиляция integration suite без запуска контейнеров выполняется через `make -C backend test-int-compile`. +## Журнал и настройки согласий + +Публично доступен только текущий текст C1 для регистрации. Подтвержденный пользователь может прочитать текущие тексты C1/C2/C3/C5 перед выдачей в настройках и постранично получить только собственный журнал согласий. C1 можно выдать аккаунту любого сценария; C2, C3 и C5 доступны кандидату. Изменения требуют явного подтверждения, exact Origin и session-bound CSRF. + +Отзыв C2 закрывает публикацию в модели чтения и скрывает поля в той же транзакции; сохраненная публикация остается связанной с отозванной записью, поэтому повторная выдача C2 не открывает ее снова. Отзыв C3 не блокирует аккаунт или профиль. Отдельный запрос ручной оценки запланирован, но его endpoint пока не реализован. Отзыв C5 немедленно закрывает gate будущего импорта и пишет intent в outbox; внешнего адаптера ФСП пока нет. Отзыв C4 ограничен одной организацией и использует сохраненную область контактов. Запрос C1 отзывает согласие и создает долговечную запись запроса удаления с outbox intent; повтор возвращает ту же активную запись, а сама учетная запись не удаляется синхронно. + +Проверку полного HTTP-пути с PostgreSQL и Redis запускает `make -C backend test-int`; тест `TestConsentSettingsOverHTTP` покрывает тексты, журнал, grants, revocation effects и C1 deletion request. + +## Организации + +Реализованы `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}` и `PATCH /api/v1/organizations/{org_id}`. Подтвержденный работодатель создает организацию и активное членство владельца одной транзакцией; начальный уровень - `e0` с основанием `confirmed_email`. Каждое чтение проверяет активное членство. Изменять профиль может только активный владелец; версия повышается при изменении, уровень проверки сохраняется. + +Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `ListMyOrganizations`, потребности и приглашения пока не реализованы. + +`TestOrganizationCreationAndOwnerEditingOverHTTP` проверяет в PostgreSQL параллельный повтор, откат при ошибке вставки владельца, запрет чужого доступа, сохранение данных после пересоздания API и повторное использование истекшего ключа. + Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md). diff --git a/backend/db/migrations/00018_create_account_deletion_requests.sql b/backend/db/migrations/00018_create_account_deletion_requests.sql new file mode 100644 index 0000000..d993021 --- /dev/null +++ b/backend/db/migrations/00018_create_account_deletion_requests.sql @@ -0,0 +1,37 @@ +-- A C1 revocation creates a durable request for the account-deletion workflow. +-- The API records the request and its outbox intent atomically; processing and +-- deleting the account are separate operations. +-- +goose Up +CREATE TABLE account_deletion_requests ( + id uuid NOT NULL, + subject_id uuid, + status text NOT NULL, + requested_at timestamptz NOT NULL, + completed_at timestamptz, + CONSTRAINT account_deletion_requests_pkey PRIMARY KEY (id), + CONSTRAINT account_deletion_requests_subject_id_fkey FOREIGN KEY (subject_id) + REFERENCES users (id) ON DELETE SET NULL, + CONSTRAINT account_deletion_requests_status_known CHECK ( + status IN ('requested', 'processing', 'completed') + ), + CONSTRAINT account_deletion_requests_state_shape CHECK ( + (status = 'completed') = (completed_at IS NOT NULL) + ), + CONSTRAINT account_deletion_requests_subject_retained_until_complete CHECK ( + subject_id IS NOT NULL OR status = 'completed' + ), + CONSTRAINT account_deletion_requests_completed_after_request CHECK ( + completed_at IS NULL OR completed_at >= requested_at + ) +); + +CREATE UNIQUE INDEX account_deletion_requests_one_active_per_subject +ON account_deletion_requests (subject_id) +WHERE subject_id IS NOT NULL AND status IN ('requested', 'processing'); + +CREATE INDEX account_deletion_requests_processing_idx +ON account_deletion_requests (requested_at, id) +WHERE status IN ('requested', 'processing'); + +-- +goose Down +DROP TABLE account_deletion_requests; diff --git a/backend/db/migrations/00019_create_organization_creation_results.sql b/backend/db/migrations/00019_create_organization_creation_results.sql new file mode 100644 index 0000000..69aeaf8 --- /dev/null +++ b/backend/db/migrations/00019_create_organization_creation_results.sql @@ -0,0 +1,25 @@ +-- +goose Up +-- Replay follows the generic record's 24-hour retention. Expired records are +-- removed by bounded opportunistic purges, so physical deletion may happen +-- later; this foreign key removes the snapshot with its record. The snapshot +-- is separate from the live organization so later profile edits cannot change +-- a replay. It contains bounded profile and owner-membership data, never a +-- request key. +CREATE TABLE organization_creation_results ( + scope_hash bytea NOT NULL, + snapshot jsonb NOT NULL, + CONSTRAINT organization_creation_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT organization_creation_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT organization_creation_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT organization_creation_results_snapshot_bounded CHECK ( + jsonb_typeof(snapshot) = 'object' + AND octet_length(snapshot::text) <= 65536 + ) +); + +-- +goose Down +DROP TABLE organization_creation_results; diff --git a/backend/db/privacy_queries_test.go b/backend/db/privacy_queries_test.go index 54e3f54..f31d16d 100644 --- a/backend/db/privacy_queries_test.go +++ b/backend/db/privacy_queries_test.go @@ -25,6 +25,10 @@ var directPublicationReaders = []string{ "UpdateCandidatePublication", } +var ownerScopedPublicationQueries = []string{ + "LockCandidatePublicationForConsentRevocation", +} + var ( // sqlc accepts both comment forms and tolerates trailing whitespace. queryHeaderPattern = regexp.MustCompile(`(?m)^(?:--|/\*)[ \t]*name:[ \t]+(\w+)[ \t]+:\w+[ \t]*(?:\*/)?[ \t]*$`) @@ -43,6 +47,7 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) { t.Fatalf("list the query files = %v, %v", files, err) } var found []string + statements := make(map[string]string) for _, file := range files { content, err := os.ReadFile(file) if err != nil { @@ -63,6 +68,7 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) { name := text[header[2]:header[3]] if publicationTableName.MatchString(statement) { found = append(found, name) + statements[name] = strings.Join(strings.Fields(statement), " ") } if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) { t.Errorf("%s reads candidate_effective_publications without excluding candidate_hidden_organizations", name) @@ -70,12 +76,31 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) { } } slices.Sort(found) - want := slices.Clone(directPublicationReaders) + want := slices.Concat(slices.Clone(directPublicationReaders), ownerScopedPublicationQueries) slices.Sort(want) if !slices.Equal(found, want) { - t.Fatalf("queries that name candidate_publications = %v, want only %v: organization-facing reads use candidate_effective_publications", found, want) + t.Fatalf("queries that name candidate_publications = %v, want only settings queries and owner-scoped consent revocation: %v", found, want) } if strings.Contains(strings.Join(found, ","), "Visible") { t.Fatal("the organization-facing read names the table directly") } + closeQuery := strings.ToLower(statements["LockCandidatePublicationForConsentRevocation"]) + for _, required := range []string{ + "select greatest(candidate_publications.published_at, consent_records.revoked_at)", + "inner join consent_records", + "candidate_publications.user_id = sqlc.arg(user_id)", + "candidate_publications.state = 'published'", + "consent_records.id = any(sqlc.arg(consent_record_ids)::uuid [])", + "consent_records.subject_id = candidate_publications.user_id", + "consent_records.purpose = 'c2'", + "consent_records.revoked_at is not null", + "for update of candidate_publications", + } { + if !strings.Contains(closeQuery, required) { + t.Errorf("consent revocation query lacks %q: %s", required, closeQuery) + } + } + if strings.Contains(closeQuery, "update candidate_publications") || strings.Contains(closeQuery, "set state = 'closed'") { + t.Fatalf("consent revocation query rewrites the stored publication instead of preserving its ledger link: %s", closeQuery) + } } diff --git a/backend/db/queries/consents.sql b/backend/db/queries/consents.sql index bdb80cf..976187c 100644 --- a/backend/db/queries/consents.sql +++ b/backend/db/queries/consents.sql @@ -417,3 +417,33 @@ WHERE ) ORDER BY ledger.granted_at DESC, ledger.id DESC LIMIT sqlc.arg(row_limit); + +-- Creates one durable deletion request per subject until a worker completes it. +-- The caller appends the matching outbox intent in the same transaction only +-- when this insert returns a row. +-- name: CreateAccountDeletionRequest :one +INSERT INTO account_deletion_requests ( + id, + subject_id, + status, + requested_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(subject_id), + 'requested', + sqlc.arg(requested_at) +) +ON CONFLICT (subject_id) +WHERE subject_id IS NOT NULL AND status IN ('requested', 'processing') +DO NOTHING +RETURNING id, subject_id, status, requested_at; + +-- Reads the durable active deletion request when an earlier request already +-- exists. A completed request does not suppress a later explicit request. +-- name: GetActiveAccountDeletionRequest :one +SELECT id, subject_id, status, requested_at +FROM account_deletion_requests +WHERE subject_id = sqlc.arg(subject_id) + AND status IN ('requested', 'processing') +ORDER BY requested_at, id +LIMIT 1; diff --git a/backend/db/queries/organizations.sql b/backend/db/queries/organizations.sql index a19a46d..f7d9528 100644 --- a/backend/db/queries/organizations.sql +++ b/backend/db/queries/organizations.sql @@ -222,3 +222,20 @@ FROM memberships WHERE organization_id = sqlc.arg(organization_id) AND user_id = sqlc.arg(user_id); + +-- Stores the immutable domain snapshot of a successful create command. The +-- generic idempotency row and this result are committed with the organization +-- and owner membership. A reused expired scope replaces the snapshot in the +-- same transaction as the new organization. +-- name: SaveOrganizationCreationResult :exec +INSERT INTO organization_creation_results (scope_hash, snapshot) +VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot)) +ON CONFLICT (scope_hash) DO UPDATE +SET snapshot = excluded.snapshot; + +-- Reads only the historical result. It intentionally does not join the live +-- organization or membership, whose profile and state may have since changed. +-- name: GetOrganizationCreationResult :one +SELECT snapshot +FROM organization_creation_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/db/queries/privacy.sql b/backend/db/queries/privacy.sql index 71e7a8a..618b522 100644 --- a/backend/db/queries/privacy.sql +++ b/backend/db/queries/privacy.sql @@ -280,6 +280,25 @@ ORDER BY granted_at DESC, id DESC LIMIT 1 FOR SHARE; +-- Locks the candidate's published row only when it refers to a C2 record +-- revoked by this transaction. The setting remains linked to that immutable +-- record; ReadCandidatePublication computes the effective closed state and +-- keeps the consent-revoked reason after later grants. The returned time is +-- the effective close time used by the privacy history event. +-- name: LockCandidatePublicationForConsentRevocation :one +SELECT greatest(candidate_publications.published_at, consent_records.revoked_at)::timestamptz AS closed_at +FROM candidate_publications +INNER JOIN consent_records + ON consent_records.id = candidate_publications.consent_record_id +WHERE + candidate_publications.user_id = sqlc.arg(user_id) + AND candidate_publications.state = 'published' + AND consent_records.id = ANY(sqlc.arg(consent_record_ids)::uuid []) + AND consent_records.subject_id = candidate_publications.user_id + AND consent_records.purpose = 'c2' + AND consent_records.revoked_at IS NOT NULL +FOR UPDATE OF candidate_publications; + -- The organization-facing read of a candidate's publication: the effective -- view (published and backed by an unrevoked C2) and no hiding of the reading -- organization. No row means the organization reads nothing, whichever of diff --git a/backend/integration_test/consent_http_test.go b/backend/integration_test/consent_http_test.go new file mode 100644 index 0000000..2b86108 --- /dev/null +++ b/backend/integration_test/consent_http_test.go @@ -0,0 +1,500 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" +) + +const consentHTTPTestTimeout = 5 * time.Minute + +func TestConsentSettingsOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), consentHTTPTestTimeout) + defer cancel() + harness := newConsentHTTPHarness(ctx, t, env) + truncateTables(ctx, t, harness.pool, usersDependentTables...) + + now := harness.clock.Now() + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness, "consent-candidate@example.test", passwordHash, true) + createConsentHTTPEmployer(ctx, t, harness, "consent-employer@example.test", passwordHash) + candidateCookie, candidateCSRF := loginConsentHTTP(t, harness, "consent-candidate@example.test", "192.0.2.50:1234") + employerCookie, employerCSRF := loginConsentHTTP(t, harness, "consent-employer@example.test", "192.0.2.51:1234") + store := postgresadapter.NewConsentStore(harness.pool) + reader := consent.NewQueryService(store, time.Now) + + guestList := harness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", "", "", "192.0.2.52:1234") + requireSessionProblem(t, guestList, http.StatusUnauthorized, "unauthenticated") + guestDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", "", "", "", "192.0.2.53:1234") + requireSessionProblem(t, guestDeletion, http.StatusUnauthorized, "unauthenticated") + assertRowCount(ctx, t, harness.pool, consentTables[0], 0) + assertRowCount(ctx, t, harness.pool, accountDeletionRequestsTable, 0) + + publicText := harness.request(t, http.MethodGet, "/api/v1/identity/consent-texts/c1", "", "", "", "", "192.0.2.54:1234") + if publicText.Code != http.StatusOK { + t.Fatalf("public C1 text = %d %s", publicText.Code, publicText.Body.String()) + } + myC2Text := harness.request(t, http.MethodGet, "/api/v1/me/consent-texts/c2", "", "", candidateCookie.Value, "", "192.0.2.55:1234") + if myC2Text.Code != http.StatusOK || myC2Text.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("current C2 text = %d, Cache-Control=%q, body=%s", myC2Text.Code, myC2Text.Header().Get("Cache-Control"), myC2Text.Body.String()) + } + var c2Text struct { + Purpose string `json:"purpose"` + TextVersion string `json:"text_version"` + Text string `json:"text"` + } + if err := json.Unmarshal(myC2Text.Body.Bytes(), &c2Text); err != nil || c2Text.Purpose != "c2" || c2Text.TextVersion == "" || c2Text.Text == "" { + t.Fatalf("decode current C2 text = %+v, %v", c2Text, err) + } + publicC2 := harness.request(t, http.MethodGet, "/api/v1/identity/consent-texts/c2", "", "", "", "", "192.0.2.56:1234") + requireSessionProblem(t, publicC2, http.StatusBadRequest, "validation_failed") + + // A newer publication makes the version already shown to the candidate stale. + newC2Body := "I consent to publication of my candidate card, consent HTTP test revision." + newC2Version := "c2-consent-http-revision" + if _, err := harness.pool.Exec(ctx, ` + INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at) + VALUES ('c2', $1, $2, sha256(convert_to($2, 'UTF8')), 'demo', $3)`, + newC2Version, newC2Body, now.Add(-time.Second)); err != nil { + t.Fatalf("publish a newer C2 text: %v", err) + } + staleGrant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", c2Text.TextVersion, sessionHTTPTestOrigin) + requireSessionProblem(t, staleGrant, http.StatusBadRequest, "validation_failed") + assertRowCount(ctx, t, harness.pool, consentRecordsTable, 0) + + missingOriginGrant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", newC2Version, "") + requireSessionProblem(t, missingOriginGrant, http.StatusForbidden, "csrf_check_failed") + wrongCSRFGrant := consentGrantHTTP(t, harness, candidateCookie, "wrong-token", "c2", newC2Version, sessionHTTPTestOrigin) + requireSessionProblem(t, wrongCSRFGrant, http.StatusForbidden, "csrf_check_failed") + assertRowCount(ctx, t, harness.pool, consentRecordsTable, 0) + + employerGrant := consentGrantHTTP(t, harness, employerCookie, employerCSRF, "c2", newC2Version, sessionHTTPTestOrigin) + requireSessionProblem(t, employerGrant, http.StatusForbidden, "forbidden") + assertRowCount(ctx, t, harness.pool, consentRecordsTable, 0) + + c2Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", newC2Version, sessionHTTPTestOrigin) + if c2Grant.Code != http.StatusOK || c2Grant.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("C2 grant = %d, Cache-Control=%q, body=%s", c2Grant.Code, c2Grant.Header().Get("Cache-Control"), c2Grant.Body.String()) + } + c2Record, err := store.ConsentLedger().Current(ctx, candidate.ID, domain.ConsentPurposePublication) + if err != nil || c2Record.TextVersion() != domain.ConsentTextVersion(newC2Version) { + t.Fatalf("current C2 record = %s, %v", c2Record, err) + } + + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), + identity: identityFixture{ctx: ctx, pool: harness.pool, store: postgresadapter.NewIdentityStore(harness.pool), now: now}, + ledger: store, now: now, + } + privacy.publish(t, candidate.ID, c2Record.ID(), 0, domain.CardFieldStack) + var privacyEventsBefore int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM candidate_privacy_events WHERE user_id = $1`, candidate.ID).Scan(&privacyEventsBefore); err != nil { + t.Fatalf("count candidate privacy events before C2 revoke: %v", err) + } + var c2EventsBefore int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c2' AND payload->>'subject_id' = $1`, candidate.ID.String()).Scan(&c2EventsBefore); err != nil { + t.Fatalf("count C2 revocation events before revoke: %v", err) + } + wrongOriginRevoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", "https://attacker.example", candidateCookie.Value, candidateCSRF, "192.0.2.57:1234") + requireSessionProblem(t, wrongOriginRevoke, http.StatusForbidden, "csrf_check_failed") + if publication := privacy.loadPublication(t, candidate.ID); publication.State() != domain.PublicationPublished { + t.Fatalf("bad-Origin revoke changed publication to %s", publication.State()) + } + current, err := reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposePublication) + if err != nil || !current { + t.Fatalf("bad-Origin revoke changed the C2 gate: %v, %v", current, err) + } + + revokedC2 := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.58:1234") + if revokedC2.Code != http.StatusNoContent { + t.Fatalf("C2 revoke = %d %s", revokedC2.Code, revokedC2.Body.String()) + } + current, err = reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposePublication) + if err != nil || current { + t.Fatalf("revoked C2 gate = %v, %v; want fail closed", current, err) + } + if publication := privacy.loadPublication(t, candidate.ID); publication.State() != domain.PublicationClosed || + publication.ClosedReason() != domain.ClosedConsentRevoked || !publication.Fields().IsEmpty() { + t.Fatalf("revoked C2 publication = %s/%s, want closed and empty", publication.State(), publication.ClosedReason()) + } + var storedPublicationState string + var storedPublicationFields []string + var storedPublicationConsentID uuid.UUID + if err := harness.pool.QueryRow(ctx, ` + SELECT state, fields, consent_record_id + FROM candidate_publications + WHERE user_id = $1`, candidate.ID).Scan(&storedPublicationState, &storedPublicationFields, &storedPublicationConsentID); err != nil { + t.Fatalf("read stored publication after C2 revoke: %v", err) + } + if storedPublicationState != "published" || len(storedPublicationFields) != 1 || storedPublicationFields[0] != string(domain.CardFieldStack) || storedPublicationConsentID != c2Record.ID() { + t.Fatalf("revocation rewrote publication source row: state=%s fields=%v consent=%s", storedPublicationState, storedPublicationFields, storedPublicationConsentID) + } + var privacyEventsAfter, c2EventsAfter int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM candidate_privacy_events WHERE user_id = $1`, candidate.ID).Scan(&privacyEventsAfter); err != nil { + t.Fatalf("count candidate privacy events after C2 revoke: %v", err) + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c2' AND payload->>'subject_id' = $1`, candidate.ID.String()).Scan(&c2EventsAfter); err != nil { + t.Fatalf("count C2 revocation events after revoke: %v", err) + } + if privacyEventsAfter != privacyEventsBefore+1 || c2EventsAfter != c2EventsBefore+1 { + t.Fatalf("C2 revoke effects changed by privacy=%d and outbox=%d, want one each", privacyEventsAfter-privacyEventsBefore, c2EventsAfter-c2EventsBefore) + } + repeatedC2 := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.59:1234") + if repeatedC2.Code != http.StatusNoContent { + t.Fatalf("repeat C2 revoke = %d %s", repeatedC2.Code, repeatedC2.Body.String()) + } + var c2EventsRepeated int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c2' AND payload->>'subject_id' = $1`, candidate.ID.String()).Scan(&c2EventsRepeated); err != nil { + t.Fatalf("count C2 revocation events after repeat: %v", err) + } + if c2EventsRepeated != c2EventsAfter { + t.Fatalf("repeat C2 revoke duplicated an outbox event: %d -> %d", c2EventsAfter, c2EventsRepeated) + } + newC2Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", newC2Version, sessionHTTPTestOrigin) + revokedPublication := privacy.loadPublication(t, candidate.ID) + if newC2Grant.Code != http.StatusOK || revokedPublication.State() != domain.PublicationClosed || + revokedPublication.ClosedReason() != domain.ClosedConsentRevoked || !revokedPublication.Fields().IsEmpty() { + t.Fatalf("new C2 grant reopened the old publication: status=%d publication=%s", newC2Grant.Code, privacy.loadPublication(t, candidate.ID).State()) + } + newerC2Revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.74:1234") + if newerC2Revoke.Code != http.StatusNoContent { + t.Fatalf("revoke newer C2 record = %d %s", newerC2Revoke.Code, newerC2Revoke.Body.String()) + } + var privacyEventsAfterNewerRevoke int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM candidate_privacy_events WHERE user_id = $1`, candidate.ID).Scan(&privacyEventsAfterNewerRevoke); err != nil { + t.Fatalf("count privacy events after newer C2 revoke: %v", err) + } + if privacyEventsAfterNewerRevoke != privacyEventsAfter { + t.Fatalf("revoking newer C2 record duplicated the old publication event: %d -> %d", privacyEventsAfter, privacyEventsAfterNewerRevoke) + } + + // C5 has a real current-consent reader; after revocation future import work denies. + c5Text := harness.request(t, http.MethodGet, "/api/v1/me/consent-texts/c5", "", "", candidateCookie.Value, "", "192.0.2.60:1234") + var c5Current struct { + TextVersion string `json:"text_version"` + } + if c5Text.Code != http.StatusOK || json.Unmarshal(c5Text.Body.Bytes(), &c5Current) != nil { + t.Fatalf("read C5 text = %d %s", c5Text.Code, c5Text.Body.String()) + } + c5Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c5", c5Current.TextVersion, sessionHTTPTestOrigin) + if c5Grant.Code != http.StatusOK { + t.Fatalf("C5 grant = %d %s", c5Grant.Code, c5Grant.Body.String()) + } + if allowed, err := reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposeFSPImport); err != nil || !allowed { + t.Fatalf("current C5 gate = %v, %v; want allow", allowed, err) + } + c5Revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c5", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.61:1234") + if c5Revoke.Code != http.StatusNoContent { + t.Fatalf("C5 revoke = %d %s", c5Revoke.Code, c5Revoke.Body.String()) + } + if allowed, err := reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposeFSPImport); err != nil || allowed { + t.Fatalf("revoked C5 gate = %v, %v; want deny", allowed, err) + } + + // C4 revocation takes its target from the path and its fields from the stored records. + contactText, err := store.ConsentTexts().Current(ctx, domain.ConsentPurposeContactDisclosure, now) + if err != nil { + t.Fatalf("read current C4 text: %v", err) + } + organizationA, organizationB := uuid.New(), uuid.New() + for _, organizationID := range []uuid.UUID{organizationA, organizationB} { + invitationID := uuid.New() + fieldSet, err := domain.NewContactFieldSet(domain.ContactFieldPhone, domain.ContactFieldEmail) + if err != nil { + t.Fatal(err) + } + grant, err := domain.NewContactConsentGrant(domain.ContactConsentGrantInput{ + SubjectID: candidate.ID, OrganizationID: organizationID, OrganizationName: consentOrganizationName, + Fields: fieldSet, InvitationID: invitationID, InvitationTermsVersion: 2, Text: contactText, GrantedAt: now, + }) + if err != nil { + t.Fatalf("build C4 grant: %v", err) + } + if _, created, err := store.ConsentLedger().GrantContact(ctx, grant); err != nil || !created { + t.Fatalf("store C4 grant = %v, %v", created, err) + } + } + c4Revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c4/organizations/"+organizationA.String(), "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.62:1234") + if c4Revoke.Code != http.StatusNoContent { + t.Fatalf("C4 revoke = %d %s", c4Revoke.Code, c4Revoke.Body.String()) + } + remainingC4, err := store.ConsentLedger().CurrentContact(ctx, candidate.ID, organizationB) + if err != nil || len(remainingC4) != 1 || remainingC4[0].State() != domain.ConsentStateActive { + t.Fatalf("C4 for another organization = %v, %v; want one unchanged active record", remainingC4, err) + } + var c4Payload struct { + OrganizationID string `json:"organization_id"` + Fields []string `json:"fields"` + } + var c4PayloadJSON []byte + if err := harness.pool.QueryRow(ctx, ` + SELECT payload FROM outbox_events + WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c4' AND payload->>'subject_id' = $1 + ORDER BY position DESC LIMIT 1`, candidate.ID.String()).Scan(&c4PayloadJSON); err != nil { + t.Fatalf("read C4 revocation intent: %v", err) + } + if err := json.Unmarshal(c4PayloadJSON, &c4Payload); err != nil { + t.Fatalf("decode C4 revocation intent: %v", err) + } + if c4Payload.OrganizationID != organizationA.String() || len(c4Payload.Fields) != 2 || + c4Payload.Fields[0] != string(domain.ContactFieldEmail) || c4Payload.Fields[1] != string(domain.ContactFieldPhone) { + t.Fatalf("C4 revocation intent = %+v; want stored organization and field scope", c4Payload) + } + + // The history cursor is opaque and tied to the current subject and state filter. + firstPage := harness.request(t, http.MethodGet, "/api/v1/me/consents?limit=1", "", "", candidateCookie.Value, "", "192.0.2.63:1234") + if firstPage.Code != http.StatusOK || firstPage.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("first consent page = %d, Cache-Control=%q, body=%s", firstPage.Code, firstPage.Header().Get("Cache-Control"), firstPage.Body.String()) + } + var page struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor string `json:"next_cursor"` + } `json:"page"` + } + if err := json.Unmarshal(firstPage.Body.Bytes(), &page); err != nil || len(page.Items) != 1 || !page.Page.HasMore || page.Page.NextCursor == "" { + t.Fatalf("first consent page = %+v, %v", page, err) + } + secondPage := harness.request(t, http.MethodGet, "/api/v1/me/consents?limit=1&cursor="+page.Page.NextCursor, "", "", candidateCookie.Value, "", "192.0.2.64:1234") + var next struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + } + if secondPage.Code != http.StatusOK || json.Unmarshal(secondPage.Body.Bytes(), &next) != nil || len(next.Items) != 1 || next.Items[0].ID == page.Items[0].ID { + t.Fatalf("second consent page = %d %s", secondPage.Code, secondPage.Body.String()) + } + foreignCursor := harness.request(t, http.MethodGet, "/api/v1/me/consents?cursor="+page.Page.NextCursor, "", "", employerCookie.Value, "", "192.0.2.65:1234") + requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed") + employerList := harness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", employerCookie.Value, "", "192.0.2.66:1234") + var employerHistory struct { + Items []json.RawMessage `json:"items"` + } + if employerList.Code != http.StatusOK || json.Unmarshal(employerList.Body.Bytes(), &employerHistory) != nil || len(employerHistory.Items) != 0 { + t.Fatalf("employer consent history = %d %s", employerList.Code, employerList.Body.String()) + } + + // C1 deletion is durable, idempotent, and independent of a later consent grant. + c1Text := harness.request(t, http.MethodGet, "/api/v1/identity/consent-texts/c1", "", "", "", "", "192.0.2.67:1234") + var c1Current struct { + TextVersion string `json:"text_version"` + } + if c1Text.Code != http.StatusOK || json.Unmarshal(c1Text.Body.Bytes(), &c1Current) != nil { + t.Fatalf("read C1 text = %d %s", c1Text.Code, c1Text.Body.String()) + } + c1Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c1", c1Current.TextVersion, sessionHTTPTestOrigin) + if c1Grant.Code != http.StatusOK { + t.Fatalf("C1 grant = %d %s", c1Grant.Code, c1Grant.Body.String()) + } + var deletionEventsBefore int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsBefore); err != nil { + t.Fatalf("count deletion events before request: %v", err) + } + badDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, "wrong-token", "192.0.2.68:1234") + requireSessionProblem(t, badDeletion, http.StatusForbidden, "csrf_check_failed") + assertRowCount(ctx, t, harness.pool, accountDeletionRequestsTable, 0) + requestDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.69:1234") + if requestDeletion.Code != http.StatusAccepted || requestDeletion.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("account deletion request = %d %s", requestDeletion.Code, requestDeletion.Body.String()) + } + var firstDeletion struct { + ID string `json:"id"` + Status string `json:"status"` + } + if err := json.Unmarshal(requestDeletion.Body.Bytes(), &firstDeletion); err != nil || firstDeletion.ID == "" || firstDeletion.Status != "requested" { + t.Fatalf("decode deletion request = %+v, %v", firstDeletion, err) + } + repeatedDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.70:1234") + var repeatedBody struct { + ID string `json:"id"` + } + if repeatedDeletion.Code != http.StatusAccepted || json.Unmarshal(repeatedDeletion.Body.Bytes(), &repeatedBody) != nil || repeatedBody.ID != firstDeletion.ID { + t.Fatalf("repeated deletion request = %d %s", repeatedDeletion.Code, repeatedDeletion.Body.String()) + } + assertRowCount(ctx, t, harness.pool, accountDeletionRequestsTable, 1) + var deletionEventsAfter int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsAfter); err != nil { + t.Fatalf("count deletion events after request: %v", err) + } + if deletionEventsAfter != deletionEventsBefore+1 { + t.Fatalf("deletion event count changed by %d, want one", deletionEventsAfter-deletionEventsBefore) + } + if _, err := store.ConsentLedger().Current(ctx, candidate.ID, domain.ConsentPurposePersonalData); err == nil { + t.Fatal("C1 remained active after its deletion request") + } + laterC1 := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c1", c1Current.TextVersion, sessionHTTPTestOrigin) + if laterC1.Code != http.StatusOK { + t.Fatalf("later C1 grant = %d %s", laterC1.Code, laterC1.Body.String()) + } + var activeDeletionID string + if err := harness.pool.QueryRow(ctx, `SELECT id FROM account_deletion_requests WHERE subject_id = $1 AND status IN ('requested','processing')`, candidate.ID).Scan(&activeDeletionID); err != nil || activeDeletionID != firstDeletion.ID { + t.Fatalf("active deletion request after later C1 grant = %q, %v", activeDeletionID, err) + } + listBeforeRestart := harness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", candidateCookie.Value, "", "192.0.2.71:1234") + if listBeforeRestart.Code != http.StatusOK { + t.Fatalf("consent history before API restart = %d %s", listBeforeRestart.Code, listBeforeRestart.Body.String()) + } + var deletionRowsBeforeRestart, deletionEventsBeforeRestart int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM account_deletion_requests WHERE subject_id = $1`, candidate.ID).Scan(&deletionRowsBeforeRestart); err != nil { + t.Fatalf("count deletion requests before API restart: %v", err) + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsBeforeRestart); err != nil { + t.Fatalf("count deletion events before API restart: %v", err) + } + + // Reconstruct the API and session services over the same database and reuse + // the existing cookie. History and the durable deletion request survive. + restartedHarness := newConsentHTTPHarness(ctx, t, env) + listAfterRestart := restartedHarness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", candidateCookie.Value, "", "192.0.2.72:1234") + if listAfterRestart.Code != http.StatusOK || listAfterRestart.Body.String() != listBeforeRestart.Body.String() { + t.Fatalf("consent history after API restart = %d %s; before=%s", listAfterRestart.Code, listAfterRestart.Body.String(), listBeforeRestart.Body.String()) + } + deletionAfterRestart := restartedHarness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.73:1234") + var deletionAfterRestartBody struct { + ID string `json:"id"` + } + if deletionAfterRestart.Code != http.StatusAccepted || json.Unmarshal(deletionAfterRestart.Body.Bytes(), &deletionAfterRestartBody) != nil || deletionAfterRestartBody.ID != firstDeletion.ID { + t.Fatalf("deletion request after API restart = %d %s, want durable request %s", deletionAfterRestart.Code, deletionAfterRestart.Body.String(), firstDeletion.ID) + } + var deletionRowsAfterRestart, deletionEventsAfterRestart int64 + if err := restartedHarness.pool.QueryRow(ctx, `SELECT count(*) FROM account_deletion_requests WHERE subject_id = $1`, candidate.ID).Scan(&deletionRowsAfterRestart); err != nil { + t.Fatalf("count deletion requests after API restart: %v", err) + } + if err := restartedHarness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsAfterRestart); err != nil { + t.Fatalf("count deletion events after API restart: %v", err) + } + if deletionRowsAfterRestart != deletionRowsBeforeRestart || deletionEventsAfterRestart != deletionEventsBeforeRestart { + t.Fatalf("API reconstruction duplicated deletion state: rows %d->%d, events %d->%d", deletionRowsBeforeRestart, deletionRowsAfterRestart, deletionEventsBeforeRestart, deletionEventsAfterRestart) + } + + if strings.Contains(harness.logs.String(), candidateCookie.Value) || strings.Contains(harness.logs.String(), employerCookie.Value) || + strings.Contains(restartedHarness.logs.String(), candidateCookie.Value) { + t.Fatal("a session token reached request logs") + } +} + +func createConsentHTTPEmployer( + ctx context.Context, + t *testing.T, + harness *sessionHTTPHarness, + email string, + passwordHash domain.PasswordHash, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + now := harness.clock.Now().Truncate(time.Microsecond) + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: now, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(%s) error = %v", email, err) + } + verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified(%s) error = %v", email, err) + } + return verified +} + +func newConsentHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: postgresadapter.NewTransactor(pool), Users: store.Users(), Sessions: store.Sessions(), + Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + consentStore := postgresadapter.NewConsentStore(pool) + consentReader := consent.NewQueryService(consentStore, time.Now) + consentCommands := consent.NewService(postgresadapter.NewTransactor(pool), time.Now) + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL)) + consentHandler := v1.NewConsentHandler(consentReader, consentCommands) + handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler)) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} +} + +func loginConsentHTTP(t *testing.T, harness *sessionHTTPHarness, email, remoteAddr string) (*http.Cookie, string) { + t.Helper() + response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", remoteAddr) + if response.Code != http.StatusCreated { + t.Fatalf("login %s = %d %s", email, response.Code, response.Body.String()) + } + cookie := requireSessionCookie(t, response) + var body struct { + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" { + t.Fatalf("decode login CSRF token: %v", err) + } + return cookie, body.CSRFToken +} + +func consentGrantHTTP(t *testing.T, harness *sessionHTTPHarness, cookie *http.Cookie, csrf, purpose, version, origin string) *httptest.ResponseRecorder { + t.Helper() + body, err := json.Marshal(struct { + TextVersion string `json:"text_version"` + Accepted bool `json:"accepted"` + }{TextVersion: version, Accepted: true}) + if err != nil { + t.Fatalf("marshal consent grant: %v", err) + } + return harness.request(t, http.MethodPut, "/api/v1/me/consents/"+purpose, string(body), origin, cookie.Value, csrf, "192.0.2.80:1234") +} diff --git a/backend/integration_test/consent_ledger_test.go b/backend/integration_test/consent_ledger_test.go index 6e8c29c..c878644 100644 --- a/backend/integration_test/consent_ledger_test.go +++ b/backend/integration_test/consent_ledger_test.go @@ -45,9 +45,10 @@ const ( const consentSecondC1Version domain.ConsentTextVersion = "c1-2026-10-05" var ( - consentRecordsTable = pgx.Identifier{"consent_records"} + consentRecordsTable = pgx.Identifier{"consent_records"} + accountDeletionRequestsTable = pgx.Identifier{"account_deletion_requests"} // consentTables reference users, so every TRUNCATE of users names them. - consentTables = []pgx.Identifier{consentRecordsTable} + consentTables = []pgx.Identifier{consentRecordsTable, accountDeletionRequestsTable} ) // consentFixture works on the bootstrap database. The ledger rows are diff --git a/backend/integration_test/mail_retry_migration_test.go b/backend/integration_test/mail_retry_migration_test.go index 25db9b3..3c8ca1f 100644 --- a/backend/integration_test/mail_retry_migration_test.go +++ b/backend/integration_test/mail_retry_migration_test.go @@ -9,6 +9,8 @@ import ( "time" "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" ) const mailRetryMigrationVersion = 17 @@ -23,6 +25,7 @@ func TestMailRetryMigrationKeepsAnAppendOnlyAudit(t *testing.T) { if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() error = %v", err) } + rollBackToMailRetryVersion(ctx, t, migrator) deliveryID := uuid.New() decidedAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) @@ -62,6 +65,42 @@ func TestMailRetryMigrationKeepsAnAppendOnlyAudit(t *testing.T) { } } +func rollBackToMailRetryVersion(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) { + t.Helper() + for { + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() while preparing migration %d: %v", mailRetryMigrationVersion, err) + } + mailRetryApplied := false + laterMigrationApplied := false + for _, status := range statuses { + if !status.Applied { + continue + } + if status.Version == mailRetryMigrationVersion { + mailRetryApplied = true + } + if status.Version > mailRetryMigrationVersion { + laterMigrationApplied = true + } + } + if !mailRetryApplied { + t.Fatalf("migration %d is not applied", mailRetryMigrationVersion) + } + if !laterMigrationApplied { + return + } + result, err := migrator.DownOne(ctx) + if err != nil { + t.Fatalf("DownOne() while preparing migration %d: %v", mailRetryMigrationVersion, err) + } + if result.Version <= mailRetryMigrationVersion { + t.Fatalf("DownOne() rolled back migration %d while preparing migration %d", result.Version, mailRetryMigrationVersion) + } + } +} + func containsAll(value string, fragments ...string) bool { for _, fragment := range fragments { if !strings.Contains(value, fragment) { diff --git a/backend/integration_test/organization_http_test.go b/backend/integration_test/organization_http_test.go new file mode 100644 index 0000000..fa8363e --- /dev/null +++ b/backend/integration_test/organization_http_test.go @@ -0,0 +1,434 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/organization" +) + +const organizationHTTPTestTimeout = 5 * time.Minute + +type organizationHTTPSession struct { + cookie *http.Cookie + csrf string +} + +func TestOrganizationCreationAndOwnerEditingOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout) + defer cancel() + harness := newOrganizationHTTPHarness(ctx, t, env) + initialLogs := harness.logs + resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"}) + truncateTables(ctx, t, harness.pool, resetTables...) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + owner := createOrganizationHTTPUser(ctx, t, harness, "owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) + foreign := createOrganizationHTTPUser(ctx, t, harness, "foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now) + candidate := createOrganizationHTTPUser(ctx, t, harness, "candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + unverified := createOrganizationHTTPUser(ctx, t, harness, "unverified@example.test", passwordHash, domain.ScenarioEmployer, false, now) + + ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address()) + foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address()) + candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address()) + unverifiedLogin := loginSessionHTTP(t, harness, unverified.Email.Address(), sessionHTTPTestPass, + env.Config.AppPublicURL, "", "192.0.2.44:1234") + requireSessionProblem(t, unverifiedLogin, http.StatusForbidden, "email_not_verified") + if len(unverifiedLogin.Header().Values("Set-Cookie")) != 0 { + t.Fatal("unverified account received a session cookie") + } + + createBody := "{\"name\":\"ООО Тестовая компания\",\"description\":\"Профиль компании\",\"contacts\":{\"website\":\"https://company.example.test\",\"email\":\"careers@example.test\",\"phone\":\"+74950000000\",\"telegram\":\"@company_careers\"},\"representatives\":[{\"name\":\"Ирина Проверочная\",\"job_title\":\"Руководитель найма\"}]}" + createResponses := make(chan *httptest.ResponseRecorder, 2) + for range 2 { + go func() { + createResponses <- organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, + env.Config.AppPublicURL, ownerSession, "organization-http-create-1") + }() + } + created := <-createResponses + concurrentReplay := <-createResponses + if created.Code != http.StatusCreated || created.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("create response = %d %s, Cache-Control=%q, want 201 no-store", created.Code, created.Body.String(), created.Header().Get("Cache-Control")) + } + originalBody := append([]byte(nil), created.Body.Bytes()...) + if concurrentReplay.Code != http.StatusCreated || string(concurrentReplay.Body.Bytes()) != string(originalBody) { + t.Fatalf("concurrent create = %d %s, want the same 201 body %s", concurrentReplay.Code, concurrentReplay.Body.String(), originalBody) + } + var creation struct { + ID string `json:"id"` + Version int64 `json:"version"` + Name string `json:"name"` + Verification struct { + Level string `json:"level"` + Basis string `json:"basis"` + } `json:"verification"` + CandidateCard map[string]json.RawMessage `json:"candidate_card"` + } + if err := json.Unmarshal(originalBody, &creation); err != nil { + t.Fatalf("decode created organization: %v", err) + } + if creation.ID == "" || creation.Version != 1 || creation.Name != "ООО Тестовая компания" || + creation.Verification.Level != "e0" || creation.Verification.Basis != "confirmed_email" { + t.Fatalf("created company has unexpected identity or verification: %+v", creation) + } + for _, key := range []string{"id", "name", "description", "sphere", "contacts", "representatives", "verification_level"} { + if _, ok := creation.CandidateCard[key]; !ok { + t.Fatalf("candidate card has no %q field: %v", key, creation.CandidateCard) + } + } + for _, key := range []string{"owner", "membership", "role", "email_verified", "user_id", "password"} { + if _, ok := creation.CandidateCard[key]; ok { + t.Fatalf("candidate card exposes private %q field", key) + } + } + assertOrganizationHTTPCounts(ctx, t, harness.pool, 1, 1, 1, 1) + organizationID := creation.ID + + var storedRole, storedState string + if err := harness.pool.QueryRow(ctx, + "SELECT role, state FROM memberships WHERE organization_id = $1 AND user_id = $2", organizationID, owner.ID, + ).Scan(&storedRole, &storedState); err != nil { + t.Fatalf("read creator membership: %v", err) + } + if storedRole != "owner" || storedState != "active" { + t.Fatalf("stored creator membership = %s/%s, want active owner", storedRole, storedState) + } + + updated := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID, + "{\"expected_version\":1,\"name\":\"ООО Обновленная компания\",\"description\":null}", + env.Config.AppPublicURL, ownerSession, "") + if updated.Code != http.StatusOK { + t.Fatalf("owner update = %d %s, want 200", updated.Code, updated.Body.String()) + } + var updatedBody struct { + Version int64 `json:"version"` + Name string `json:"name"` + Description *string `json:"description"` + Verification struct { + Level string `json:"level"` + Basis string `json:"basis"` + } `json:"verification"` + } + if err := json.Unmarshal(updated.Body.Bytes(), &updatedBody); err != nil { + t.Fatalf("decode updated organization: %v", err) + } + if updatedBody.Version != 2 || updatedBody.Name != "ООО Обновленная компания" || updatedBody.Description != nil || + updatedBody.Verification.Level != "e0" || updatedBody.Verification.Basis != "confirmed_email" { + t.Fatalf("updated organization = %+v, want edited profile and unchanged E0", updatedBody) + } + harness.pool.Close() + harness = newOrganizationHTTPHarness(ctx, t, env) + restartedRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationID, "", + "", ownerSession, "") + if restartedRead.Code != http.StatusOK { + t.Fatalf("read with a new handler and pool = %d %s, want 200", restartedRead.Code, restartedRead.Body.String()) + } + var restartedBody struct { + Version int64 `json:"version"` + Name string `json:"name"` + } + if err := json.Unmarshal(restartedRead.Body.Bytes(), &restartedBody); err != nil { + t.Fatalf("decode organization after handler restart: %v", err) + } + if restartedBody.Version != 2 || restartedBody.Name != "ООО Обновленная компания" { + t.Fatalf("organization after handler restart = %+v, want the persisted owner update", restartedBody) + } + staleUpdate := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID, + "{\"expected_version\":1,\"name\":\"ООО Устаревшее изменение\"}", + env.Config.AppPublicURL, ownerSession, "") + requireSessionProblem(t, staleUpdate, http.StatusPreconditionFailed, "version_conflict") + + replay := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, + env.Config.AppPublicURL, ownerSession, "organization-http-create-1") + if replay.Code != http.StatusCreated || replay.Header().Get("Cache-Control") != "no-store" || + string(replay.Body.Bytes()) != string(originalBody) { + t.Fatalf("same-key replay = %d %s, want the exact original 201 body %s", replay.Code, replay.Body.String(), originalBody) + } + changed := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", + "{\"name\":\"ООО Другой запрос\"}", + env.Config.AppPublicURL, ownerSession, "organization-http-create-1") + requireSessionProblem(t, changed, http.StatusUnprocessableEntity, "idempotency_key_reused") + replayTime := harness.clock.Now() + expired, err := harness.pool.Exec(ctx, "UPDATE idempotency_records SET created_at = $1, expires_at = $2", + replayTime.Add(-2*time.Second), replayTime.Add(-time.Second)) + if err != nil { + t.Fatalf("expire the original create key: %v", err) + } + if expired.RowsAffected() != 1 { + t.Fatalf("expired idempotency rows = %d, want 1", expired.RowsAffected()) + } + reused := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, + env.Config.AppPublicURL, ownerSession, "organization-http-create-1") + if reused.Code != http.StatusCreated { + t.Fatalf("create with an expired key = %d %s, want 201", reused.Code, reused.Body.String()) + } + var reusedBody struct { + ID string `json:"id"` + } + if err := json.Unmarshal(reused.Body.Bytes(), &reusedBody); err != nil { + t.Fatalf("decode organization created after key expiration: %v", err) + } + if reusedBody.ID == organizationID { + t.Fatal("expired key replayed the old company instead of creating a new one") + } + reusedReplay := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, + env.Config.AppPublicURL, ownerSession, "organization-http-create-1") + if reusedReplay.Code != http.StatusCreated || string(reusedReplay.Body.Bytes()) != string(reused.Body.Bytes()) { + t.Fatalf("replay after key reuse = %d %s, want the replacement snapshot %s", + reusedReplay.Code, reusedReplay.Body.String(), reused.Body.String()) + } + assertOrganizationHTTPCounts(ctx, t, harness.pool, 2, 2, 2, 1) + + foreignRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationID, "", + "", foreignSession, "") + requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found") + foreignUpdate := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID, + "{\"expected_version\":2,\"name\":\"Не владелец\"}", + env.Config.AppPublicURL, foreignSession, "") + requireSessionProblem(t, foreignUpdate, http.StatusNotFound, "not_found") + candidateCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", + "{\"name\":\"Кандидат не может создать компанию\"}", + env.Config.AppPublicURL, candidateSession, "organization-http-candidate-create") + requireSessionProblem(t, candidateCreate, http.StatusForbidden, "forbidden") + + // The failed owner insert must roll back the organization and idempotency + // reservation together. Reusing the same key after removing the constraint + // proves the request left no partial state. + if _, err := harness.pool.Exec(ctx, "ALTER TABLE memberships ADD CONSTRAINT organization_http_reject_owner CHECK (role <> 'owner') NOT VALID"); err != nil { + t.Fatalf("install temporary owner failure constraint: %v", err) + } + t.Cleanup(func() { + _, _ = harness.pool.Exec(context.WithoutCancel(ctx), "ALTER TABLE memberships DROP CONSTRAINT IF EXISTS organization_http_reject_owner") + }) + beforeFailure := readOrganizationHTTPCounts(ctx, t, harness.pool) + rollbackBody := "{\"name\":\"ООО Повтор после отката\"}" + failedCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", rollbackBody, + env.Config.AppPublicURL, ownerSession, "organization-http-rollback-1") + if failedCreate.Code != http.StatusInternalServerError { + t.Fatalf("owner insert failure status = %d %s, want 500", failedCreate.Code, failedCreate.Body.String()) + } + assertOrganizationHTTPCountsEqual(ctx, t, harness.pool, beforeFailure) + if _, err := harness.pool.Exec(ctx, "ALTER TABLE memberships DROP CONSTRAINT organization_http_reject_owner"); err != nil { + t.Fatalf("remove temporary owner failure constraint: %v", err) + } + recoveredCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", rollbackBody, + env.Config.AppPublicURL, ownerSession, "organization-http-rollback-1") + if recoveredCreate.Code != http.StatusCreated { + t.Fatalf("create after rollback = %d %s, want 201 with the same idempotency key", recoveredCreate.Code, recoveredCreate.Body.String()) + } + + for _, marker := range []string{ + owner.Email.Address(), foreign.Email.Address(), candidate.Email.Address(), unverified.Email.Address(), + "Ирина Проверочная", "careers@example.test", "ООО Тестовая компания", "ООО Обновленная компания", + } { + if strings.Contains(initialLogs.String(), marker) || strings.Contains(harness.logs.String(), marker) { + t.Fatalf("organization HTTP logs contain profile or account data %q", marker) + } + } +} + +func newOrganizationHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + sessionService, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: postgresadapter.NewTransactor(pool), + Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials, + Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, + AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + organizationService, err := organization.NewService(organization.Dependencies{ + Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now, + }) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(sessionService), + v1.WithPublicOrigin(env.Config.AppPublicURL), + ) + organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{ + pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs, + } +} + +func createOrganizationHTTPUser( + ctx context.Context, + t *testing.T, + harness *sessionHTTPHarness, + email string, + passwordHash domain.PasswordHash, + scenario domain.Scenario, + verified bool, + now time.Time, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: scenario, RegisteredAt: now, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(%q) error = %v", email, err) + } + if !verified { + return user + } + user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + return user +} + +func loginOrganizationHTTP(t *testing.T, harness *sessionHTTPHarness, email string) organizationHTTPSession { + t.Helper() + response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.40:1234") + if response.Code != http.StatusCreated { + t.Fatalf("login status = %d %s, want 201", response.Code, response.Body.String()) + } + var body struct { + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode login response: %v", err) + } + if body.CSRFToken == "" { + t.Fatal("login response has no CSRF token") + } + return organizationHTTPSession{cookie: requireSessionCookie(t, response), csrf: body.CSRFToken} +} + +func organizationHTTPRequest( + t *testing.T, + harness *sessionHTTPHarness, + method, path, body, origin string, + session organizationHTTPSession, + idempotencyKey string, +) *httptest.ResponseRecorder { + t.Helper() + request := httptest.NewRequest(method, path, strings.NewReader(body)) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + if origin != "" { + request.Header.Set("Origin", origin) + } + if session.cookie != nil { + request.AddCookie(&http.Cookie{Name: "__Host-lincodex_session", Value: session.cookie.Value}) + } + if session.csrf != "" { + request.Header.Set("X-CSRF-Token", session.csrf) + } + if idempotencyKey != "" { + request.Header.Set("Idempotency-Key", idempotencyKey) + } + request.RemoteAddr = "192.0.2.41:1234" + recorder := httptest.NewRecorder() + harness.router.ServeHTTP(recorder, request) + return recorder +} + +type organizationHTTPRowCounts struct { + organizations int64 + representatives int64 + memberships int64 + results int64 + idempotency int64 +} + +func readOrganizationHTTPCounts(ctx context.Context, t *testing.T, pool *pgxpool.Pool) organizationHTTPRowCounts { + t.Helper() + var counts organizationHTTPRowCounts + if err := pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM organizations), + (SELECT count(*) FROM organization_representatives), + (SELECT count(*) FROM memberships), + (SELECT count(*) FROM organization_creation_results), + (SELECT count(*) FROM idempotency_records) + `).Scan(&counts.organizations, &counts.representatives, &counts.memberships, &counts.results, &counts.idempotency); err != nil { + t.Fatalf("read organization transaction counts: %v", err) + } + return counts +} + +func assertOrganizationHTTPCounts(ctx context.Context, t *testing.T, pool *pgxpool.Pool, + organizations, representatives, memberships, results int64, +) { + t.Helper() + counts := readOrganizationHTTPCounts(ctx, t, pool) + if counts.organizations != organizations || counts.representatives != representatives || + counts.memberships != memberships || counts.results != results { + t.Fatalf("organization rows = %+v, want org=%d representatives=%d memberships=%d snapshots=%d", + counts, organizations, representatives, memberships, results) + } +} + +func assertOrganizationHTTPCountsEqual(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want organizationHTTPRowCounts) { + t.Helper() + if got := readOrganizationHTTPCounts(ctx, t, pool); got != want { + t.Fatalf("failed organization create changed transactional rows: got %+v, want %+v", got, want) + } +} diff --git a/backend/integration_test/organizations_test.go b/backend/integration_test/organizations_test.go index f864322..21d4d1c 100644 --- a/backend/integration_test/organizations_test.go +++ b/backend/integration_test/organizations_test.go @@ -35,9 +35,12 @@ var ( organizationsTable = pgx.Identifier{"organizations"} organizationRepresentativesTable = pgx.Identifier{"organization_representatives"} membershipsTable = pgx.Identifier{"memberships"} + organizationCreationResultsTable = pgx.Identifier{"organization_creation_results"} // organizationTables are emptied together: memberships reference both - // users and organizations. - organizationTables = []pgx.Identifier{membershipsTable, organizationRepresentativesTable, organizationsTable} + // users and organizations. Creation snapshots reference idempotency records. + organizationTables = []pgx.Identifier{ + organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable, + } // usersDependentTables is every table that references users, directly or // through another table of the list. A TRUNCATE of users must name all of // them, so a migration that adds such a table adds it here. diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 256dba0..5e749e6 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -4257,6 +4257,209 @@ func (s *Server) handleGetMyCardPreviewRequest(args [0]string, argsEscaped bool, } } +// handleGetMyConsentTextRequest handles GetMyConsentText operation. +// +// Requires a verified session. Returns the current published text and version of c1, c2, c3, or c5 so +// the user can read the exact text before an explicit settings grant. C4 is excluded: its text +// includes an organization snapshot and it is granted only during invitation acceptance. The response +// is private and is not cached. +// +// GET /api/v1/me/consent-texts/{purpose} +func (s *Server) handleGetMyConsentTextRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyConsentText"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/consent-texts/{purpose}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyConsentTextOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetMyConsentTextOperation, + ID: "GetMyConsentText", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyConsentTextOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeGetMyConsentTextParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response GetMyConsentTextRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyConsentTextOperation, + OperationSummary: "Read a current consent text for account settings.", + OperationID: "GetMyConsentText", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "purpose", + In: "path", + }: params.Purpose, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetMyConsentTextParams + Response = GetMyConsentTextRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetMyConsentTextParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyConsentText(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetMyConsentText(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetMyConsentTextResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleGetMyInvitationRequest handles GetMyInvitation operation. // // Requires the session cookie of a candidate account. The candidate comes from the session; the @@ -6342,6 +6545,247 @@ func (s *Server) handleGetSpecializationCatalogRequest(args [0]string, argsEscap } } +// handleGrantMyConsentRequest handles GrantMyConsent operation. +// +// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The +// subject comes from the session. The body names the current text version the user read and requires +// `accepted: true`; the server verifies that version is still current and stores the hash of the exact +// text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant. +// +// C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate +// accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the +// same current version returns the existing record; after revocation a grant creates a new record and +// never reopens a publication or restores an older grant. +// +// PUT /api/v1/me/consents/{purpose} +func (s *Server) handleGrantMyConsentRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GrantMyConsent"), + semconv.HTTPRequestMethodKey.String("PUT"), + semconv.HTTPRouteKey.String("/api/v1/me/consents/{purpose}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GrantMyConsentOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GrantMyConsentOperation, + ID: "GrantMyConsent", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GrantMyConsentOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, GrantMyConsentOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeGrantMyConsentParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeGrantMyConsentRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response GrantMyConsentRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GrantMyConsentOperation, + OperationSummary: "Record an explicit consent grant from settings.", + OperationID: "GrantMyConsent", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "purpose", + In: "path", + }: params.Purpose, + }, + Raw: r, + } + + type ( + Request = *ConsentSettingsGrantRequest + Params = GrantMyConsentParams + Response = GrantMyConsentRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGrantMyConsentParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GrantMyConsent(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.GrantMyConsent(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGrantMyConsentResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleHideOrganizationRequest handles HideOrganization operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -6833,8 +7277,9 @@ func (s *Server) handleListMyCardAccessHistoryRequest(args [0]string, argsEscape // value. A c2 record proves the consent to the publication text; the published field set and its // changes are evidence of the publication history. // -// Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations -// of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. +// Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit +// acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion +// request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed // `limit`, `cursor`, or `state` answers 400 validation_failed. @@ -9437,6 +9882,213 @@ func (s *Server) handleRegisterAccountRequest(args [0]string, argsEscaped bool, } } +// handleRequestMyAccountDeletionRequest handles RequestMyAccountDeletion operation. +// +// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The +// subject comes from the session. In one transaction, revokes any active C1 record, creates or returns +// the subject's active durable deletion request, and writes the outbox intent. The API does not delete +// the account synchronously. Repeating the request returns the same active request; a later C1 grant +// never cancels it. +// +// POST /api/v1/me/account-deletion-requests +func (s *Server) handleRequestMyAccountDeletionRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("RequestMyAccountDeletion"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/account-deletion-requests"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), RequestMyAccountDeletionOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: RequestMyAccountDeletionOperation, + ID: "RequestMyAccountDeletion", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, RequestMyAccountDeletionOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, RequestMyAccountDeletionOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + + var response RequestMyAccountDeletionRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: RequestMyAccountDeletionOperation, + OperationSummary: "Revoke C1 and request account deletion.", + OperationID: "RequestMyAccountDeletion", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = RequestMyAccountDeletionRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.RequestMyAccountDeletion(ctx) + return response, err + }, + ) + } else { + response, err = s.h.RequestMyAccountDeletion(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeRequestMyAccountDeletionResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleResendEmailVerificationRequest handles ResendEmailVerification operation. // // Public operation without a session. The answer is the same 202 for an unknown email, a verified @@ -9601,6 +10253,455 @@ func (s *Server) handleResendEmailVerificationRequest(args [0]string, argsEscape } } +// handleRevokeMyConsentRequest handles RevokeMyConsent operation. +// +// Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured +// Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5, +// including superseded records, and never changes another purpose. Repeating a revocation is harmless +// and creates no duplicate event. +// +// Revoking c2 immediately closes the stored publication and records privacy history in the same +// transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not +// reopen publication or restore old grants. Revoking c3 does not block the manual assessment path. +// Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent; +// an external FSP deletion adapter is not available yet. +// +// DELETE /api/v1/me/consents/{purpose} +func (s *Server) handleRevokeMyConsentRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("RevokeMyConsent"), + semconv.HTTPRequestMethodKey.String("DELETE"), + semconv.HTTPRouteKey.String("/api/v1/me/consents/{purpose}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), RevokeMyConsentOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: RevokeMyConsentOperation, + ID: "RevokeMyConsent", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, RevokeMyConsentOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, RevokeMyConsentOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeRevokeMyConsentParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response RevokeMyConsentRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: RevokeMyConsentOperation, + OperationSummary: "Revoke a non-scoped consent from settings.", + OperationID: "RevokeMyConsent", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "purpose", + In: "path", + }: params.Purpose, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = RevokeMyConsentParams + Response = RevokeMyConsentRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackRevokeMyConsentParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.RevokeMyConsent(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.RevokeMyConsent(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeRevokeMyConsentResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleRevokeMyOrganizationContactConsentRequest handles RevokeMyOrganizationContactConsent operation. +// +// Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured +// Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The +// server revokes every unrevoked C4 record for this subject and organization, using the fields stored +// on those records to request downstream grant revocation. It does not affect another organization. +// Repeating the request is harmless and creates no duplicate event. +// +// DELETE /api/v1/me/consents/c4/organizations/{org_id} +func (s *Server) handleRevokeMyOrganizationContactConsentRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("RevokeMyOrganizationContactConsent"), + semconv.HTTPRequestMethodKey.String("DELETE"), + semconv.HTTPRouteKey.String("/api/v1/me/consents/c4/organizations/{org_id}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), RevokeMyOrganizationContactConsentOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: RevokeMyOrganizationContactConsentOperation, + ID: "RevokeMyOrganizationContactConsent", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, RevokeMyOrganizationContactConsentOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, RevokeMyOrganizationContactConsentOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeRevokeMyOrganizationContactConsentParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response RevokeMyOrganizationContactConsentRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: RevokeMyOrganizationContactConsentOperation, + OperationSummary: "Revoke C4 for one organization.", + OperationID: "RevokeMyOrganizationContactConsent", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = RevokeMyOrganizationContactConsentParams + Response = RevokeMyOrganizationContactConsentRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackRevokeMyOrganizationContactConsentParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.RevokeMyOrganizationContactConsent(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.RevokeMyOrganizationContactConsent(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeRevokeMyOrganizationContactConsentResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleSaveMyProfileRequest handles SaveMyProfile operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index 01abde0..1bb34f1 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -69,6 +69,10 @@ type GetMyCardPreviewRes interface { getMyCardPreviewRes() } +type GetMyConsentTextRes interface { + getMyConsentTextRes() +} + type GetMyInvitationRes interface { getMyInvitationRes() } @@ -105,6 +109,10 @@ type GetOrganizationRes interface { getOrganizationRes() } +type GrantMyConsentRes interface { + grantMyConsentRes() +} + type HideOrganizationRes interface { hideOrganizationRes() } @@ -161,10 +169,22 @@ type RegisterAccountRes interface { registerAccountRes() } +type RequestMyAccountDeletionRes interface { + requestMyAccountDeletionRes() +} + type ResendEmailVerificationRes interface { resendEmailVerificationRes() } +type RevokeMyConsentRes interface { + revokeMyConsentRes() +} + +type RevokeMyOrganizationContactConsentRes interface { + revokeMyOrganizationContactConsentRes() +} + type SaveMyProfileRes interface { saveMyProfileRes() } diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index 36bafc8..89034b4 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -12492,6 +12492,172 @@ func (s *ConfirmEmailForbidden) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *ConsentDeletionRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ConsentDeletionRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("requested_at") + s.RequestedAt.Encode(e) + } +} + +var jsonFieldsNameOfConsentDeletionRequest = [3]string{ + 0: "id", + 1: "status", + 2: "requested_at", +} + +// Decode decodes ConsentDeletionRequest from json. +func (s *ConsentDeletionRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentDeletionRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "requested_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.RequestedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"requested_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ConsentDeletionRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfConsentDeletionRequest) { + name = jsonFieldsNameOfConsentDeletionRequest[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ConsentDeletionRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentDeletionRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConsentDeletionRequestStatus as json. +func (s ConsentDeletionRequestStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ConsentDeletionRequestStatus from json. +func (s *ConsentDeletionRequestStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentDeletionRequestStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ConsentDeletionRequestStatus(v) { + case ConsentDeletionRequestStatusRequested: + *s = ConsentDeletionRequestStatusRequested + case ConsentDeletionRequestStatusProcessing: + *s = ConsentDeletionRequestStatusProcessing + default: + *s = ConsentDeletionRequestStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ConsentDeletionRequestStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentDeletionRequestStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *ConsentOrganization) Encode(e *jx.Encoder) { e.ObjStart() @@ -12605,44 +12771,6 @@ func (s *ConsentOrganization) UnmarshalJSON(data []byte) error { return s.Decode(d) } -// Encode encodes ConsentPurpose as json. -func (s ConsentPurpose) Encode(e *jx.Encoder) { - e.Str(string(s)) -} - -// Decode decodes ConsentPurpose from json. -func (s *ConsentPurpose) Decode(d *jx.Decoder) error { - if s == nil { - return errors.New("invalid: unable to decode ConsentPurpose to nil") - } - v, err := d.StrBytes() - if err != nil { - return err - } - // Try to use constant string. - switch ConsentPurpose(v) { - case ConsentPurposeC1: - *s = ConsentPurposeC1 - default: - *s = ConsentPurpose(v) - } - - return nil -} - -// MarshalJSON implements stdjson.Marshaler. -func (s ConsentPurpose) MarshalJSON() ([]byte, error) { - e := jx.Encoder{} - s.Encode(&e) - return e.Bytes(), nil -} - -// UnmarshalJSON implements stdjson.Unmarshaler. -func (s *ConsentPurpose) UnmarshalJSON(data []byte) error { - d := jx.DecodeBytes(data) - return s.Decode(d) -} - // Encode encodes ConsentPurposeCode as json. func (s ConsentPurposeCode) Encode(e *jx.Encoder) { e.Str(string(s)) @@ -13135,6 +13263,147 @@ func (s *ConsentRevocationSource) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *ConsentSettingsGrantRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ConsentSettingsGrantRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("text_version") + s.TextVersion.Encode(e) + } + { + e.FieldStart("accepted") + s.Accepted.Encode(e) + } +} + +var jsonFieldsNameOfConsentSettingsGrantRequest = [2]string{ + 0: "text_version", + 1: "accepted", +} + +// Decode decodes ConsentSettingsGrantRequest from json. +func (s *ConsentSettingsGrantRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentSettingsGrantRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "text_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.TextVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text_version\"") + } + case "accepted": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Accepted.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"accepted\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ConsentSettingsGrantRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfConsentSettingsGrantRequest) { + name = jsonFieldsNameOfConsentSettingsGrantRequest[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ConsentSettingsGrantRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentSettingsGrantRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConsentSettingsGrantRequestAccepted as json. +func (s ConsentSettingsGrantRequestAccepted) Encode(e *jx.Encoder) { + e.Bool(bool(s)) +} + +// Decode decodes ConsentSettingsGrantRequestAccepted from json. +func (s *ConsentSettingsGrantRequestAccepted) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentSettingsGrantRequestAccepted to nil") + } + v, err := d.Bool() + if err != nil { + return err + } + *s = ConsentSettingsGrantRequestAccepted(v) + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ConsentSettingsGrantRequestAccepted) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentSettingsGrantRequestAccepted) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ConsentSource as json. func (s ConsentSource) Encode(e *jx.Encoder) { e.Str(string(s)) @@ -17436,6 +17705,82 @@ func (s *GetMyCardPreviewUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GetMyConsentTextBadRequest as json. +func (s *GetMyConsentTextBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyConsentTextBadRequest from json. +func (s *GetMyConsentTextBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyConsentTextBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyConsentTextBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyConsentTextBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyConsentTextBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyConsentTextUnauthorized as json. +func (s *GetMyConsentTextUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyConsentTextUnauthorized from json. +func (s *GetMyConsentTextUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyConsentTextUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyConsentTextUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyConsentTextUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyConsentTextUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes GetMyInvitationBadRequest as json. func (s *GetMyInvitationBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -18582,6 +18927,120 @@ func (s *GradeCode) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GrantMyConsentBadRequest as json. +func (s *GrantMyConsentBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GrantMyConsentBadRequest from json. +func (s *GrantMyConsentBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GrantMyConsentBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GrantMyConsentBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GrantMyConsentBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GrantMyConsentBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GrantMyConsentForbidden as json. +func (s *GrantMyConsentForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GrantMyConsentForbidden from json. +func (s *GrantMyConsentForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GrantMyConsentForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GrantMyConsentForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GrantMyConsentForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GrantMyConsentForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GrantMyConsentUnauthorized as json. +func (s *GrantMyConsentUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GrantMyConsentUnauthorized from json. +func (s *GrantMyConsentUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GrantMyConsentUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GrantMyConsentUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GrantMyConsentUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GrantMyConsentUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *HealthResponse) Encode(e *jx.Encoder) { e.ObjStart() @@ -43764,6 +44223,82 @@ func (s *RegistrationRequest) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes RequestMyAccountDeletionForbidden as json. +func (s *RequestMyAccountDeletionForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RequestMyAccountDeletionForbidden from json. +func (s *RequestMyAccountDeletionForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RequestMyAccountDeletionForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RequestMyAccountDeletionForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RequestMyAccountDeletionForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RequestMyAccountDeletionForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RequestMyAccountDeletionUnauthorized as json. +func (s *RequestMyAccountDeletionUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RequestMyAccountDeletionUnauthorized from json. +func (s *RequestMyAccountDeletionUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RequestMyAccountDeletionUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RequestMyAccountDeletionUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RequestMyAccountDeletionUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RequestMyAccountDeletionUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ResendEmailVerificationBadRequest as json. func (s *ResendEmailVerificationBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -43840,6 +44375,158 @@ func (s *ResendEmailVerificationForbidden) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes RevokeMyConsentForbidden as json. +func (s *RevokeMyConsentForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RevokeMyConsentForbidden from json. +func (s *RevokeMyConsentForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RevokeMyConsentForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RevokeMyConsentForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RevokeMyConsentForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RevokeMyConsentForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RevokeMyConsentUnauthorized as json. +func (s *RevokeMyConsentUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RevokeMyConsentUnauthorized from json. +func (s *RevokeMyConsentUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RevokeMyConsentUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RevokeMyConsentUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RevokeMyConsentUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RevokeMyConsentUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RevokeMyOrganizationContactConsentForbidden as json. +func (s *RevokeMyOrganizationContactConsentForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RevokeMyOrganizationContactConsentForbidden from json. +func (s *RevokeMyOrganizationContactConsentForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RevokeMyOrganizationContactConsentForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RevokeMyOrganizationContactConsentForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RevokeMyOrganizationContactConsentForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RevokeMyOrganizationContactConsentForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RevokeMyOrganizationContactConsentUnauthorized as json. +func (s *RevokeMyOrganizationContactConsentUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RevokeMyOrganizationContactConsentUnauthorized from json. +func (s *RevokeMyOrganizationContactConsentUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RevokeMyOrganizationContactConsentUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RevokeMyOrganizationContactConsentUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RevokeMyOrganizationContactConsentUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RevokeMyOrganizationContactConsentUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes RubAmount as json. func (s RubAmount) Encode(e *jx.Encoder) { unwrapped := int64(s) diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index f7e07dc..3a1d9eb 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -6,60 +6,65 @@ package api type OperationName = string const ( - AcceptMyInvitationOperation OperationName = "AcceptMyInvitation" - CancelMyInvitationOperation OperationName = "CancelMyInvitation" - ConfirmEmailOperation OperationName = "ConfirmEmail" - CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt" - CreateMySupportCaseOperation OperationName = "CreateMySupportCase" - CreateOrganizationOperation OperationName = "CreateOrganization" - CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation" - CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed" - DeclineMyInvitationOperation OperationName = "DeclineMyInvitation" - FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt" - GetConsentTextOperation OperationName = "GetConsentText" - GetCurrentAccountOperation OperationName = "GetCurrentAccount" - GetCurrentSessionOperation OperationName = "GetCurrentSession" - GetHealthzOperation OperationName = "GetHealthz" - GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt" - GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability" - GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult" - GetMyCardPreviewOperation OperationName = "GetMyCardPreview" - GetMyInvitationOperation OperationName = "GetMyInvitation" - GetMyPrivacySettingsOperation OperationName = "GetMyPrivacySettings" - GetMyProfileOperation OperationName = "GetMyProfile" - GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire" - GetMySupportCaseOperation OperationName = "GetMySupportCase" - GetOrganizationOperation OperationName = "GetOrganization" - GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation" - GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts" - GetOrganizationNeedOperation OperationName = "GetOrganizationNeed" - GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog" - HideOrganizationOperation OperationName = "HideOrganization" - ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory" - ListMyConsentsOperation OperationName = "ListMyConsents" - ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations" - ListMyInvitationsOperation OperationName = "ListMyInvitations" - ListMyOrganizationsOperation OperationName = "ListMyOrganizations" - ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory" - ListMySupportCasesOperation OperationName = "ListMySupportCases" - ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations" - ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds" - LoginOperation OperationName = "Login" - LogoutOperation OperationName = "Logout" - RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary" - RegisterAccountOperation OperationName = "RegisterAccount" - ResendEmailVerificationOperation OperationName = "ResendEmailVerification" - SaveMyProfileOperation OperationName = "SaveMyProfile" - SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire" - SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation" - SetMyPublicationOperation OperationName = "SetMyPublication" - SetMySearchStatusOperation OperationName = "SetMySearchStatus" - StartMyAssessmentAttemptSessionOperation OperationName = "StartMyAssessmentAttemptSession" - SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer" - UnhideOrganizationOperation OperationName = "UnhideOrganization" - UpdateOrganizationOperation OperationName = "UpdateOrganization" - UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation" - UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed" - ViewMyInvitationOperation OperationName = "ViewMyInvitation" - WithdrawOrganizationInvitationOperation OperationName = "WithdrawOrganizationInvitation" + AcceptMyInvitationOperation OperationName = "AcceptMyInvitation" + CancelMyInvitationOperation OperationName = "CancelMyInvitation" + ConfirmEmailOperation OperationName = "ConfirmEmail" + CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt" + CreateMySupportCaseOperation OperationName = "CreateMySupportCase" + CreateOrganizationOperation OperationName = "CreateOrganization" + CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation" + CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed" + DeclineMyInvitationOperation OperationName = "DeclineMyInvitation" + FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt" + GetConsentTextOperation OperationName = "GetConsentText" + GetCurrentAccountOperation OperationName = "GetCurrentAccount" + GetCurrentSessionOperation OperationName = "GetCurrentSession" + GetHealthzOperation OperationName = "GetHealthz" + GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt" + GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability" + GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult" + GetMyCardPreviewOperation OperationName = "GetMyCardPreview" + GetMyConsentTextOperation OperationName = "GetMyConsentText" + GetMyInvitationOperation OperationName = "GetMyInvitation" + GetMyPrivacySettingsOperation OperationName = "GetMyPrivacySettings" + GetMyProfileOperation OperationName = "GetMyProfile" + GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire" + GetMySupportCaseOperation OperationName = "GetMySupportCase" + GetOrganizationOperation OperationName = "GetOrganization" + GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation" + GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts" + GetOrganizationNeedOperation OperationName = "GetOrganizationNeed" + GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog" + GrantMyConsentOperation OperationName = "GrantMyConsent" + HideOrganizationOperation OperationName = "HideOrganization" + ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory" + ListMyConsentsOperation OperationName = "ListMyConsents" + ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations" + ListMyInvitationsOperation OperationName = "ListMyInvitations" + ListMyOrganizationsOperation OperationName = "ListMyOrganizations" + ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory" + ListMySupportCasesOperation OperationName = "ListMySupportCases" + ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations" + ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds" + LoginOperation OperationName = "Login" + LogoutOperation OperationName = "Logout" + RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary" + RegisterAccountOperation OperationName = "RegisterAccount" + RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion" + ResendEmailVerificationOperation OperationName = "ResendEmailVerification" + RevokeMyConsentOperation OperationName = "RevokeMyConsent" + RevokeMyOrganizationContactConsentOperation OperationName = "RevokeMyOrganizationContactConsent" + SaveMyProfileOperation OperationName = "SaveMyProfile" + SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire" + SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation" + SetMyPublicationOperation OperationName = "SetMyPublication" + SetMySearchStatusOperation OperationName = "SetMySearchStatus" + StartMyAssessmentAttemptSessionOperation OperationName = "StartMyAssessmentAttemptSession" + SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer" + UnhideOrganizationOperation OperationName = "UnhideOrganization" + UpdateOrganizationOperation OperationName = "UpdateOrganization" + UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation" + UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed" + ViewMyInvitationOperation OperationName = "ViewMyInvitation" + WithdrawOrganizationInvitationOperation OperationName = "WithdrawOrganizationInvitation" ) diff --git a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go index 7e352fe..7048758 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -1498,6 +1498,80 @@ func decodeGetMyAssessmentResultParams(args [1]string, argsEscaped bool, r *http return params, nil } +// GetMyConsentTextParams is parameters of GetMyConsentText operation. +type GetMyConsentTextParams struct { + // Consent whose current text is requested. + Purpose ConsentSettingsPurpose +} + +func unpackGetMyConsentTextParams(packed middleware.Parameters) (params GetMyConsentTextParams) { + { + key := middleware.ParameterKey{ + Name: "purpose", + In: "path", + } + params.Purpose = packed[key].(ConsentSettingsPurpose) + } + return params +} + +func decodeGetMyConsentTextParams(args [1]string, argsEscaped bool, r *http.Request) (params GetMyConsentTextParams, _ error) { + // Decode path: purpose. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "purpose", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.Purpose = ConsentSettingsPurpose(c) + return nil + }(); err != nil { + return err + } + if err := func() error { + if err := params.Purpose.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "purpose", + In: "path", + Err: err, + } + } + return params, nil +} + // GetMyInvitationParams is parameters of GetMyInvitation operation. type GetMyInvitationParams struct { // Identifier of an invitation addressed to the current candidate. A draft, an invitation addressed to @@ -2074,6 +2148,80 @@ func decodeGetOrganizationNeedParams(args [2]string, argsEscaped bool, r *http.R return params, nil } +// GrantMyConsentParams is parameters of GrantMyConsent operation. +type GrantMyConsentParams struct { + // Independent consent being granted. C4 is not available here. + Purpose ConsentSettingsPurpose +} + +func unpackGrantMyConsentParams(packed middleware.Parameters) (params GrantMyConsentParams) { + { + key := middleware.ParameterKey{ + Name: "purpose", + In: "path", + } + params.Purpose = packed[key].(ConsentSettingsPurpose) + } + return params +} + +func decodeGrantMyConsentParams(args [1]string, argsEscaped bool, r *http.Request) (params GrantMyConsentParams, _ error) { + // Decode path: purpose. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "purpose", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.Purpose = ConsentSettingsPurpose(c) + return nil + }(); err != nil { + return err + } + if err := func() error { + if err := params.Purpose.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "purpose", + In: "path", + Err: err, + } + } + return params, nil +} + // HideOrganizationParams is parameters of HideOrganization operation. type HideOrganizationParams struct { // Identifier of the organization that the current candidate hides or stops hiding the profile from. It @@ -4209,6 +4357,147 @@ func decodeRegisterAccountParams(args [0]string, argsEscaped bool, r *http.Reque return params, nil } +// RevokeMyConsentParams is parameters of RevokeMyConsent operation. +type RevokeMyConsentParams struct { + // Consent being revoked. C1 has a deletion-request operation and C4 requires an organization scope. + Purpose ConsentSettingsRevokePurpose +} + +func unpackRevokeMyConsentParams(packed middleware.Parameters) (params RevokeMyConsentParams) { + { + key := middleware.ParameterKey{ + Name: "purpose", + In: "path", + } + params.Purpose = packed[key].(ConsentSettingsRevokePurpose) + } + return params +} + +func decodeRevokeMyConsentParams(args [1]string, argsEscaped bool, r *http.Request) (params RevokeMyConsentParams, _ error) { + // Decode path: purpose. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "purpose", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.Purpose = ConsentSettingsRevokePurpose(c) + return nil + }(); err != nil { + return err + } + if err := func() error { + if err := params.Purpose.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "purpose", + In: "path", + Err: err, + } + } + return params, nil +} + +// RevokeMyOrganizationContactConsentParams is parameters of RevokeMyOrganizationContactConsent operation. +type RevokeMyOrganizationContactConsentParams struct { + // Organization whose stored C4 grants this account revokes. A well-formed identifier outside the + // account's stored records changes nothing and does not reveal whether that organization exists. + OrgID uuid.UUID +} + +func unpackRevokeMyOrganizationContactConsentParams(packed middleware.Parameters) (params RevokeMyOrganizationContactConsentParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + return params +} + +func decodeRevokeMyOrganizationContactConsentParams(args [1]string, argsEscaped bool, r *http.Request) (params RevokeMyOrganizationContactConsentParams, _ error) { + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + return params, nil +} + // SendOrganizationInvitationParams is parameters of SendOrganizationInvitation operation. type SendOrganizationInvitationParams struct { // Identifier of an organization. Access comes only from an active membership of the session account in diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index 4a2333d..15a305d 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -804,6 +804,85 @@ func (s *Server) decodeFinalizeMyAssessmentAttemptRequest(r *http.Request) ( } } +func (s *Server) decodeGrantMyConsentRequest(r *http.Request) ( + req *ConsentSettingsGrantRequest, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request ConsentSettingsGrantRequest + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + func (s *Server) decodeLoginRequest(r *http.Request) ( req *LoginRequest, rawBody []byte, diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index 752e042..10baad2 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -1742,6 +1742,65 @@ func encodeGetMyCardPreviewResponse(response GetMyCardPreviewRes, w http.Respons } } +func encodeGetMyConsentTextResponse(response GetMyConsentTextRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *ConsentTextHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyConsentTextBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyConsentTextUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeGetMyInvitationResponse(response GetMyInvitationRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CandidateInvitationHeaders: @@ -2418,6 +2477,77 @@ func encodeGetSpecializationCatalogResponse(response *SpecializationCatalog, w h return nil } +func encodeGrantMyConsentResponse(response GrantMyConsentRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *ConsentRecordHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GrantMyConsentBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GrantMyConsentUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GrantMyConsentForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeHideOrganizationResponse(response HideOrganizationRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *HiddenOrganizationHeaders: @@ -3620,6 +3750,65 @@ func encodeRegisterAccountResponse(response RegisterAccountRes, w http.ResponseW } } +func encodeRequestMyAccountDeletionResponse(response RequestMyAccountDeletionRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *ConsentDeletionRequestHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(202) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RequestMyAccountDeletionUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RequestMyAccountDeletionForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *IdentityRequestAccepted: @@ -3695,6 +3884,78 @@ func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes, } } +func encodeRevokeMyConsentResponse(response RevokeMyConsentRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *RevokeMyConsentNoContent: + w.WriteHeader(204) + + return nil + + case *RevokeMyConsentUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RevokeMyConsentForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeRevokeMyOrganizationContactConsentResponse(response RevokeMyOrganizationContactConsentRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *RevokeMyOrganizationContactConsentNoContent: + w.WriteHeader(204) + + return nil + + case *RevokeMyOrganizationContactConsentUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RevokeMyOrganizationContactConsentForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeSaveMyProfileResponse(response SaveMyProfileRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CandidateProfileHeaders: diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index 16479f3..0d1a028 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,33 +11,43 @@ import ( ) var ( - rn59AllowedHeaders = map[string]string{ + rn66AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn7AllowedHeaders = map[string]string{ "POST": "Content-Type,Origin", } - rn57AllowedHeaders = map[string]string{ + rn62AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn54AllowedHeaders = map[string]string{ + rn59AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn25AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } + rn64AllowedHeaders = map[string]string{ + "POST": "X-Csrf-Token", + } rn9AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn66AllowedHeaders = map[string]string{ + rn75AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn20AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn65AllowedHeaders = map[string]string{ + rn74AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } + rn68AllowedHeaders = map[string]string{ + "DELETE": "X-Csrf-Token", + } + rn48AllowedHeaders = map[string]string{ + "DELETE": "X-Csrf-Token", + "PUT": "Content-Type,X-Csrf-Token", + } rn3AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } @@ -47,23 +57,23 @@ var ( rn17AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn67AllowedHeaders = map[string]string{ + rn76AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn46AllowedHeaders = map[string]string{ + rn51AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", "PUT": "X-Csrf-Token", } - rn63AllowedHeaders = map[string]string{ + rn72AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn64AllowedHeaders = map[string]string{ + rn73AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn34AllowedHeaders = map[string]string{ + rn36AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn35AllowedHeaders = map[string]string{ + rn37AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } rn10AllowedHeaders = map[string]string{ @@ -78,22 +88,22 @@ var ( rn14AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn39AllowedHeaders = map[string]string{ + rn41AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } - rn56AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } rn61AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn68AllowedHeaders = map[string]string{ + rn70AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn77AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn16AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn42AllowedHeaders = map[string]string{ + rn44AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } ) @@ -250,7 +260,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn59AllowedHeaders, + allowedHeaders: rn66AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -327,7 +337,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn57AllowedHeaders, + allowedHeaders: rn62AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -351,7 +361,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn54AllowedHeaders, + allowedHeaders: rn59AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -403,9 +413,9 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } switch elem[0] { - case 'a': // Prefix: "assessment-a" + case 'a': // Prefix: "a" - if l := len("assessment-a"); len(elem) >= l && elem[0:l] == "assessment-a" { + if l := len("a"); len(elem) >= l && elem[0:l] == "a" { elem = elem[l:] } else { break @@ -415,58 +425,60 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } switch elem[0] { - case 't': // Prefix: "ttempts" + case 'c': // Prefix: "ccount-deletion-requests" - if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" { + if l := len("ccount-deletion-requests"); len(elem) >= l && elem[0:l] == "ccount-deletion-requests" { elem = elem[l:] } else { break } if len(elem) == 0 { + // Leaf node. switch r.Method { case "POST": - s.handleCreateMyAssessmentAttemptRequest([0]string{}, elemIsEscaped, w, r) + s.handleRequestMyAccountDeletionRequest([0]string{}, elemIsEscaped, w, r) default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn9AllowedHeaders, - acceptPost: "application/json", + allowedHeaders: rn64AllowedHeaders, + acceptPost: "", acceptPatch: "", }) } return } - switch elem[0] { - case '/': // Prefix: "/" - if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + case 's': // Prefix: "ssessment-a" + + if l := len("ssessment-a"); len(elem) >= l && elem[0:l] == "ssessment-a" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 't': // Prefix: "ttempts" + + if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" { elem = elem[l:] } else { break } - // Param: "attempt_id" - // Match until "/" - idx := strings.IndexByte(elem, '/') - if idx < 0 { - idx = len(elem) - } - args[0] = elem[:idx] - elem = elem[idx:] - if len(elem) == 0 { switch r.Method { - case "GET": - s.handleGetMyAssessmentAttemptRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) + case "POST": + s.handleCreateMyAssessmentAttemptRequest([0]string{}, elemIsEscaped, w, r) default: s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET", - allowedHeaders: nil, - acceptPost: "", + allowedMethods: "POST", + allowedHeaders: rn9AllowedHeaders, + acceptPost: "application/json", acceptPatch: "", }) } @@ -482,137 +494,224 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } + // Param: "attempt_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + if len(elem) == 0 { - break + switch r.Method { + case "GET": + s.handleGetMyAssessmentAttemptRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return } switch elem[0] { - case 'a': // Prefix: "answers" + case '/': // Prefix: "/" - if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" { + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { elem = elem[l:] } else { break } if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "POST": - s.handleSubmitMyAssessmentAnswerRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "POST", - allowedHeaders: rn66AllowedHeaders, - acceptPost: "application/json", - acceptPatch: "", - }) - } - - return - } - - case 'f': // Prefix: "finalize" - - if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" { - elem = elem[l:] - } else { break } + switch elem[0] { + case 'a': // Prefix: "answers" - if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "POST": - s.handleFinalizeMyAssessmentAttemptRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "POST", - allowedHeaders: rn20AllowedHeaders, - acceptPost: "application/json", - acceptPatch: "", - }) + if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" { + elem = elem[l:] + } else { + break } - return - } + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleSubmitMyAssessmentAnswerRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn75AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } - case 'r': // Prefix: "result" - - if l := len("result"); len(elem) >= l && elem[0:l] == "result" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "GET": - s.handleGetMyAssessmentResultRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET", - allowedHeaders: nil, - acceptPost: "", - acceptPatch: "", - }) + return } - return - } + case 'f': // Prefix: "finalize" - case 's': // Prefix: "sessions" - - if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "POST": - s.handleStartMyAssessmentAttemptSessionRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "POST", - allowedHeaders: rn65AllowedHeaders, - acceptPost: "application/json", - acceptPatch: "", - }) + if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleFinalizeMyAssessmentAttemptRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn20AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 'r': // Prefix: "result" + + if l := len("result"); len(elem) >= l && elem[0:l] == "result" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyAssessmentResultRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 's': // Prefix: "sessions" + + if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleStartMyAssessmentAttemptSessionRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn74AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return } - return } } } + case 'v': // Prefix: "vailability" + + if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyAssessmentAvailabilityRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + } - case 'v': // Prefix: "vailability" + } - if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" { + case 'c': // Prefix: "consent" + + if l := len("consent"); len(elem) >= l && elem[0:l] == "consent" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case '-': // Prefix: "-texts/" + + if l := len("-texts/"); len(elem) >= l && elem[0:l] == "-texts/" { elem = elem[l:] } else { break } + // Param: "purpose" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + if len(elem) == 0 { // Leaf node. switch r.Method { case "GET": - s.handleGetMyAssessmentAvailabilityRequest([0]string{}, elemIsEscaped, w, r) + s.handleGetMyConsentTextRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET", @@ -625,31 +724,114 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - } + case 's': // Prefix: "s" + + if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleListMyConsentsRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'c': // Prefix: "c4/organizations/" + origElem := elem + if l := len("c4/organizations/"); len(elem) >= l && elem[0:l] == "c4/organizations/" { + elem = elem[l:] + } else { + break + } + + // Param: "org_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "DELETE": + s.handleRevokeMyOrganizationContactConsentRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "DELETE", + allowedHeaders: rn68AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + elem = origElem + } + // Param: "purpose" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "DELETE": + s.handleRevokeMyConsentRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + case "PUT": + s.handleGrantMyConsentRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "DELETE,PUT", + allowedHeaders: rn48AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } - case 'c': // Prefix: "consents" - - if l := len("consents"); len(elem) >= l && elem[0:l] == "consents" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "GET": - s.handleListMyConsentsRequest([0]string{}, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET", - allowedHeaders: nil, - acceptPost: "", - acceptPatch: "", - }) } - return } case 'i': // Prefix: "invitations" @@ -822,7 +1004,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn67AllowedHeaders, + allowedHeaders: rn76AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1002,7 +1184,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn46AllowedHeaders, + allowedHeaders: rn51AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1093,7 +1275,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn63AllowedHeaders, + allowedHeaders: rn72AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1120,7 +1302,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn64AllowedHeaders, + allowedHeaders: rn73AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1151,7 +1333,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn34AllowedHeaders, + allowedHeaders: rn36AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1180,7 +1362,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn35AllowedHeaders, + allowedHeaders: rn37AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1392,7 +1574,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn39AllowedHeaders, + allowedHeaders: rn41AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -1472,7 +1654,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn56AllowedHeaders, + allowedHeaders: rn61AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1500,7 +1682,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn61AllowedHeaders, + allowedHeaders: rn70AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1530,7 +1712,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn68AllowedHeaders, + allowedHeaders: rn77AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1608,7 +1790,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn42AllowedHeaders, + allowedHeaders: rn44AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -2009,9 +2191,9 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { break } switch elem[0] { - case 'a': // Prefix: "assessment-a" + case 'a': // Prefix: "a" - if l := len("assessment-a"); len(elem) >= l && elem[0:l] == "assessment-a" { + if l := len("a"); len(elem) >= l && elem[0:l] == "a" { elem = elem[l:] } else { break @@ -2021,9 +2203,296 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { break } switch elem[0] { - case 't': // Prefix: "ttempts" + case 'c': // Prefix: "ccount-deletion-requests" - if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" { + if l := len("ccount-deletion-requests"); len(elem) >= l && elem[0:l] == "ccount-deletion-requests" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = RequestMyAccountDeletionOperation + r.summary = "Revoke C1 and request account deletion." + r.operationID = "RequestMyAccountDeletion" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/account-deletion-requests" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 's': // Prefix: "ssessment-a" + + if l := len("ssessment-a"); len(elem) >= l && elem[0:l] == "ssessment-a" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 't': // Prefix: "ttempts" + + if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "POST": + r.name = CreateMyAssessmentAttemptOperation + r.summary = "Start a real, corrective, or training assessment attempt." + r.operationID = "CreateMyAssessmentAttempt" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "attempt_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + switch method { + case "GET": + r.name = GetMyAssessmentAttemptOperation + r.summary = "Read an assessment attempt of the current candidate." + r.operationID = "GetMyAssessmentAttempt" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'a': // Prefix: "answers" + + if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = SubmitMyAssessmentAnswerOperation + r.summary = "Answer the current item or submit a practice of an assessment attempt." + r.operationID = "SubmitMyAssessmentAnswer" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/answers" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 'f': // Prefix: "finalize" + + if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = FinalizeMyAssessmentAttemptOperation + r.summary = "Ask for the grade decision of an assessment attempt." + r.operationID = "FinalizeMyAssessmentAttempt" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/finalize" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 'r': // Prefix: "result" + + if l := len("result"); len(elem) >= l && elem[0:l] == "result" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyAssessmentResultOperation + r.summary = "Read the result of an assessment attempt of the current candidate." + r.operationID = "GetMyAssessmentResult" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/result" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 's': // Prefix: "sessions" + + if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = StartMyAssessmentAttemptSessionOperation + r.summary = "Start or resume a work session for the current candidate's attempt." + r.operationID = "StartMyAssessmentAttemptSession" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + } + + } + + } + + case 'v': // Prefix: "vailability" + + if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyAssessmentAvailabilityOperation + r.summary = "Read which assessment attempts the current candidate can start." + r.operationID = "GetMyAssessmentAvailability" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-availability" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + } + + } + + case 'c': // Prefix: "consent" + + if l := len("consent"); len(elem) >= l && elem[0:l] == "consent" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case '-': // Prefix: "-texts/" + + if l := len("-texts/"); len(elem) >= l && elem[0:l] == "-texts/" { + elem = elem[l:] + } else { + break + } + + // Param: "purpose" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyConsentTextOperation + r.summary = "Read a current consent text for account settings." + r.operationID = "GetMyConsentText" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/consent-texts/{purpose}" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 's': // Prefix: "s" + + if l := len("s"); len(elem) >= l && elem[0:l] == "s" { elem = elem[l:] } else { break @@ -2031,12 +2500,12 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { if len(elem) == 0 { switch method { - case "POST": - r.name = CreateMyAssessmentAttemptOperation - r.summary = "Start a real, corrective, or training assessment attempt." - r.operationID = "CreateMyAssessmentAttempt" + case "GET": + r.name = ListMyConsentsOperation + r.summary = "List the consents of the current account with their history." + r.operationID = "ListMyConsents" r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts" + r.pathPattern = "/api/v1/me/consents" r.args = args r.count = 0 return r, true @@ -2053,23 +2522,73 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { break } - // Param: "attempt_id" - // Match until "/" - idx := strings.IndexByte(elem, '/') - if idx < 0 { - idx = len(elem) + if len(elem) == 0 { + break } - args[0] = elem[:idx] - elem = elem[idx:] + switch elem[0] { + case 'c': // Prefix: "c4/organizations/" + origElem := elem + if l := len("c4/organizations/"); len(elem) >= l && elem[0:l] == "c4/organizations/" { + elem = elem[l:] + } else { + break + } + + // Param: "org_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch method { + case "DELETE": + r.name = RevokeMyOrganizationContactConsentOperation + r.summary = "Revoke C4 for one organization." + r.operationID = "RevokeMyOrganizationContactConsent" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/consents/c4/organizations/{org_id}" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + elem = origElem + } + // Param: "purpose" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" if len(elem) == 0 { + // Leaf node. switch method { - case "GET": - r.name = GetMyAssessmentAttemptOperation - r.summary = "Read an assessment attempt of the current candidate." - r.operationID = "GetMyAssessmentAttempt" + case "DELETE": + r.name = RevokeMyConsentOperation + r.summary = "Revoke a non-scoped consent from settings." + r.operationID = "RevokeMyConsent" r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}" + r.pathPattern = "/api/v1/me/consents/{purpose}" + r.args = args + r.count = 1 + return r, true + case "PUT": + r.name = GrantMyConsentOperation + r.summary = "Record an explicit consent grant from settings." + r.operationID = "GrantMyConsent" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/consents/{purpose}" r.args = args r.count = 1 return r, true @@ -2077,175 +2596,9 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { return } } - switch elem[0] { - case '/': // Prefix: "/" - - if l := len("/"); len(elem) >= l && elem[0:l] == "/" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - break - } - switch elem[0] { - case 'a': // Prefix: "answers" - - if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch method { - case "POST": - r.name = SubmitMyAssessmentAnswerOperation - r.summary = "Answer the current item or submit a practice of an assessment attempt." - r.operationID = "SubmitMyAssessmentAnswer" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/answers" - r.args = args - r.count = 1 - return r, true - default: - return - } - } - - case 'f': // Prefix: "finalize" - - if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch method { - case "POST": - r.name = FinalizeMyAssessmentAttemptOperation - r.summary = "Ask for the grade decision of an assessment attempt." - r.operationID = "FinalizeMyAssessmentAttempt" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/finalize" - r.args = args - r.count = 1 - return r, true - default: - return - } - } - - case 'r': // Prefix: "result" - - if l := len("result"); len(elem) >= l && elem[0:l] == "result" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch method { - case "GET": - r.name = GetMyAssessmentResultOperation - r.summary = "Read the result of an assessment attempt of the current candidate." - r.operationID = "GetMyAssessmentResult" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/result" - r.args = args - r.count = 1 - return r, true - default: - return - } - } - - case 's': // Prefix: "sessions" - - if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch method { - case "POST": - r.name = StartMyAssessmentAttemptSessionOperation - r.summary = "Start or resume a work session for the current candidate's attempt." - r.operationID = "StartMyAssessmentAttemptSession" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions" - r.args = args - r.count = 1 - return r, true - default: - return - } - } - - } - - } } - case 'v': // Prefix: "vailability" - - if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch method { - case "GET": - r.name = GetMyAssessmentAvailabilityOperation - r.summary = "Read which assessment attempts the current candidate can start." - r.operationID = "GetMyAssessmentAvailability" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-availability" - r.args = args - r.count = 0 - return r, true - default: - return - } - } - - } - - case 'c': // Prefix: "consents" - - if l := len("consents"); len(elem) >= l && elem[0:l] == "consents" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch method { - case "GET": - r.name = ListMyConsentsOperation - r.summary = "List the consents of the current account with their history." - r.operationID = "ListMyConsents" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/consents" - r.args = args - r.count = 0 - return r, true - default: - return - } } case 'i': // Prefix: "invitations" diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 33aaee0..68e9a42 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -6261,6 +6261,117 @@ type ConfirmEmailForbidden Problem func (*ConfirmEmailForbidden) confirmEmailRes() {} +// Durable request to delete the account and its personal data. The request is recorded before +// asynchronous processing starts; it does not mean deletion has completed. +// Ref: #/components/schemas/ConsentDeletionRequest +type ConsentDeletionRequest struct { + // Identifier of the durable deletion request. + ID uuid.UUID `json:"id"` + // Current state of the deletion request. + Status ConsentDeletionRequestStatus `json:"status"` + RequestedAt Timestamp `json:"requested_at"` +} + +// GetID returns the value of ID. +func (s *ConsentDeletionRequest) GetID() uuid.UUID { + return s.ID +} + +// GetStatus returns the value of Status. +func (s *ConsentDeletionRequest) GetStatus() ConsentDeletionRequestStatus { + return s.Status +} + +// GetRequestedAt returns the value of RequestedAt. +func (s *ConsentDeletionRequest) GetRequestedAt() Timestamp { + return s.RequestedAt +} + +// SetID sets the value of ID. +func (s *ConsentDeletionRequest) SetID(val uuid.UUID) { + s.ID = val +} + +// SetStatus sets the value of Status. +func (s *ConsentDeletionRequest) SetStatus(val ConsentDeletionRequestStatus) { + s.Status = val +} + +// SetRequestedAt sets the value of RequestedAt. +func (s *ConsentDeletionRequest) SetRequestedAt(val Timestamp) { + s.RequestedAt = val +} + +// ConsentDeletionRequestHeaders wraps ConsentDeletionRequest with response headers. +type ConsentDeletionRequestHeaders struct { + CacheControl CacheControlNoStore + Response ConsentDeletionRequest +} + +// GetCacheControl returns the value of CacheControl. +func (s *ConsentDeletionRequestHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *ConsentDeletionRequestHeaders) GetResponse() ConsentDeletionRequest { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *ConsentDeletionRequestHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *ConsentDeletionRequestHeaders) SetResponse(val ConsentDeletionRequest) { + s.Response = val +} + +func (*ConsentDeletionRequestHeaders) requestMyAccountDeletionRes() {} + +// Current state of the deletion request. +type ConsentDeletionRequestStatus string + +const ( + ConsentDeletionRequestStatusRequested ConsentDeletionRequestStatus = "requested" + ConsentDeletionRequestStatusProcessing ConsentDeletionRequestStatus = "processing" +) + +// AllValues returns all ConsentDeletionRequestStatus values. +func (ConsentDeletionRequestStatus) AllValues() []ConsentDeletionRequestStatus { + return []ConsentDeletionRequestStatus{ + ConsentDeletionRequestStatusRequested, + ConsentDeletionRequestStatusProcessing, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ConsentDeletionRequestStatus) MarshalText() ([]byte, error) { + switch s { + case ConsentDeletionRequestStatusRequested: + return []byte(s), nil + case ConsentDeletionRequestStatusProcessing: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ConsentDeletionRequestStatus) UnmarshalText(data []byte) error { + switch ConsentDeletionRequestStatus(data) { + case ConsentDeletionRequestStatusRequested: + *s = ConsentDeletionRequestStatusRequested + return nil + case ConsentDeletionRequestStatusProcessing: + *s = ConsentDeletionRequestStatusProcessing + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Organization of a c4 consent as the consent recorded it. `name` is a snapshot of the name that the // shown consent text carried at the time of the consent, and the stored text hash proves that text // with this name; a later rename of the organization does not change it, so it can differ from the @@ -6559,6 +6670,34 @@ func (s *ConsentRecord) SetInvitationTermsVersion(val NilInvitationTermsVersion) s.InvitationTermsVersion = val } +// ConsentRecordHeaders wraps ConsentRecord with response headers. +type ConsentRecordHeaders struct { + CacheControl CacheControlNoStore + Response ConsentRecord +} + +// GetCacheControl returns the value of CacheControl. +func (s *ConsentRecordHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *ConsentRecordHeaders) GetResponse() ConsentRecord { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *ConsentRecordHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *ConsentRecordHeaders) SetResponse(val ConsentRecord) { + s.Response = val +} + +func (*ConsentRecordHeaders) grantMyConsentRes() {} + // One page of the consent ledger of the current account, newest grant first. // Ref: #/components/schemas/ConsentRecordList type ConsentRecordList struct { @@ -6662,6 +6801,158 @@ func (s *ConsentRevocationSource) UnmarshalText(data []byte) error { } } +// Accept the current published text shown by GetMyConsentText. The server checks its version again +// before recording the grant. +// Ref: #/components/schemas/ConsentSettingsGrantRequest +type ConsentSettingsGrantRequest struct { + TextVersion ConsentTextVersion `json:"text_version"` + // Must be true to record an explicit acceptance. + Accepted ConsentSettingsGrantRequestAccepted `json:"accepted"` +} + +// GetTextVersion returns the value of TextVersion. +func (s *ConsentSettingsGrantRequest) GetTextVersion() ConsentTextVersion { + return s.TextVersion +} + +// GetAccepted returns the value of Accepted. +func (s *ConsentSettingsGrantRequest) GetAccepted() ConsentSettingsGrantRequestAccepted { + return s.Accepted +} + +// SetTextVersion sets the value of TextVersion. +func (s *ConsentSettingsGrantRequest) SetTextVersion(val ConsentTextVersion) { + s.TextVersion = val +} + +// SetAccepted sets the value of Accepted. +func (s *ConsentSettingsGrantRequest) SetAccepted(val ConsentSettingsGrantRequestAccepted) { + s.Accepted = val +} + +// Must be true to record an explicit acceptance. +type ConsentSettingsGrantRequestAccepted bool + +const ( + ConsentSettingsGrantRequestAcceptedTrue ConsentSettingsGrantRequestAccepted = true +) + +// AllValues returns all ConsentSettingsGrantRequestAccepted values. +func (ConsentSettingsGrantRequestAccepted) AllValues() []ConsentSettingsGrantRequestAccepted { + return []ConsentSettingsGrantRequestAccepted{ + ConsentSettingsGrantRequestAcceptedTrue, + } +} + +// Consent text that an authenticated account can read and accept in settings. C4 is scoped to an +// invitation and organization, so it is not available through the general settings flow. +// Ref: #/components/schemas/ConsentSettingsPurpose +type ConsentSettingsPurpose string + +const ( + ConsentSettingsPurposeC1 ConsentSettingsPurpose = "c1" + ConsentSettingsPurposeC2 ConsentSettingsPurpose = "c2" + ConsentSettingsPurposeC3 ConsentSettingsPurpose = "c3" + ConsentSettingsPurposeC5 ConsentSettingsPurpose = "c5" +) + +// AllValues returns all ConsentSettingsPurpose values. +func (ConsentSettingsPurpose) AllValues() []ConsentSettingsPurpose { + return []ConsentSettingsPurpose{ + ConsentSettingsPurposeC1, + ConsentSettingsPurposeC2, + ConsentSettingsPurposeC3, + ConsentSettingsPurposeC5, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ConsentSettingsPurpose) MarshalText() ([]byte, error) { + switch s { + case ConsentSettingsPurposeC1: + return []byte(s), nil + case ConsentSettingsPurposeC2: + return []byte(s), nil + case ConsentSettingsPurposeC3: + return []byte(s), nil + case ConsentSettingsPurposeC5: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ConsentSettingsPurpose) UnmarshalText(data []byte) error { + switch ConsentSettingsPurpose(data) { + case ConsentSettingsPurposeC1: + *s = ConsentSettingsPurposeC1 + return nil + case ConsentSettingsPurposeC2: + *s = ConsentSettingsPurposeC2 + return nil + case ConsentSettingsPurposeC3: + *s = ConsentSettingsPurposeC3 + return nil + case ConsentSettingsPurposeC5: + *s = ConsentSettingsPurposeC5 + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Consent that can be revoked through the general settings flow. C1 uses the account deletion request, +// and C4 must be revoked for one organization. +// Ref: #/components/schemas/ConsentSettingsRevokePurpose +type ConsentSettingsRevokePurpose string + +const ( + ConsentSettingsRevokePurposeC2 ConsentSettingsRevokePurpose = "c2" + ConsentSettingsRevokePurposeC3 ConsentSettingsRevokePurpose = "c3" + ConsentSettingsRevokePurposeC5 ConsentSettingsRevokePurpose = "c5" +) + +// AllValues returns all ConsentSettingsRevokePurpose values. +func (ConsentSettingsRevokePurpose) AllValues() []ConsentSettingsRevokePurpose { + return []ConsentSettingsRevokePurpose{ + ConsentSettingsRevokePurposeC2, + ConsentSettingsRevokePurposeC3, + ConsentSettingsRevokePurposeC5, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ConsentSettingsRevokePurpose) MarshalText() ([]byte, error) { + switch s { + case ConsentSettingsRevokePurposeC2: + return []byte(s), nil + case ConsentSettingsRevokePurposeC3: + return []byte(s), nil + case ConsentSettingsRevokePurposeC5: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ConsentSettingsRevokePurpose) UnmarshalText(data []byte) error { + switch ConsentSettingsRevokePurpose(data) { + case ConsentSettingsRevokePurposeC2: + *s = ConsentSettingsRevokePurposeC2 + return nil + case ConsentSettingsRevokePurposeC3: + *s = ConsentSettingsRevokePurposeC3 + return nil + case ConsentSettingsRevokePurposeC5: + *s = ConsentSettingsRevokePurposeC5 + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Where the subject gave the consent. // // - registration: the c1 acceptance of RegisterAccount. @@ -6780,7 +7071,7 @@ func (s *ConsentState) UnmarshalText(data []byte) error { // of exactly this text. // Ref: #/components/schemas/ConsentText type ConsentText struct { - Purpose ConsentPurpose `json:"purpose"` + Purpose ConsentPurposeCode `json:"purpose"` TextVersion ConsentTextVersion `json:"text_version"` // Full consent text in plain UTF-8; paragraphs are separated by an empty line. The client shows it as // text, never as HTML. @@ -6789,7 +7080,7 @@ type ConsentText struct { } // GetPurpose returns the value of Purpose. -func (s *ConsentText) GetPurpose() ConsentPurpose { +func (s *ConsentText) GetPurpose() ConsentPurposeCode { return s.Purpose } @@ -6809,7 +7100,7 @@ func (s *ConsentText) GetPublishedAt() Timestamp { } // SetPurpose sets the value of Purpose. -func (s *ConsentText) SetPurpose(val ConsentPurpose) { +func (s *ConsentText) SetPurpose(val ConsentPurposeCode) { s.Purpose = val } @@ -6830,6 +7121,34 @@ func (s *ConsentText) SetPublishedAt(val Timestamp) { func (*ConsentText) getConsentTextRes() {} +// ConsentTextHeaders wraps ConsentText with response headers. +type ConsentTextHeaders struct { + CacheControl CacheControlNoStore + Response ConsentText +} + +// GetCacheControl returns the value of CacheControl. +func (s *ConsentTextHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *ConsentTextHeaders) GetResponse() ConsentText { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *ConsentTextHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *ConsentTextHeaders) SetResponse(val ConsentText) { + s.Response = val +} + +func (*ConsentTextHeaders) getMyConsentTextRes() {} + type ConsentTextVersion string // Why an active grant does not allow a read now, shown only to the candidate. @@ -8046,6 +8365,14 @@ type GetMyCardPreviewUnauthorized Problem func (*GetMyCardPreviewUnauthorized) getMyCardPreviewRes() {} +type GetMyConsentTextBadRequest Problem + +func (*GetMyConsentTextBadRequest) getMyConsentTextRes() {} + +type GetMyConsentTextUnauthorized Problem + +func (*GetMyConsentTextUnauthorized) getMyConsentTextRes() {} + type GetMyInvitationBadRequest Problem func (*GetMyInvitationBadRequest) getMyInvitationRes() {} @@ -8222,6 +8549,18 @@ func (s *GradeCode) UnmarshalText(data []byte) error { } } +type GrantMyConsentBadRequest Problem + +func (*GrantMyConsentBadRequest) grantMyConsentRes() {} + +type GrantMyConsentForbidden Problem + +func (*GrantMyConsentForbidden) grantMyConsentRes() {} + +type GrantMyConsentUnauthorized Problem + +func (*GrantMyConsentUnauthorized) grantMyConsentRes() {} + // Ref: #/components/schemas/HealthResponse type HealthResponse struct { Status HealthResponseStatus `json:"status"` @@ -21991,6 +22330,14 @@ func (s *RegistrationRequest) SetConsentC1(val PersonalDataConsentAcceptance) { s.ConsentC1 = val } +type RequestMyAccountDeletionForbidden Problem + +func (*RequestMyAccountDeletionForbidden) requestMyAccountDeletionRes() {} + +type RequestMyAccountDeletionUnauthorized Problem + +func (*RequestMyAccountDeletionUnauthorized) requestMyAccountDeletionRes() {} + type ResendEmailVerificationBadRequest Problem func (*ResendEmailVerificationBadRequest) resendEmailVerificationRes() {} @@ -21999,6 +22346,32 @@ type ResendEmailVerificationForbidden Problem func (*ResendEmailVerificationForbidden) resendEmailVerificationRes() {} +type RevokeMyConsentForbidden Problem + +func (*RevokeMyConsentForbidden) revokeMyConsentRes() {} + +// RevokeMyConsentNoContent is response for RevokeMyConsent operation. +type RevokeMyConsentNoContent struct{} + +func (*RevokeMyConsentNoContent) revokeMyConsentRes() {} + +type RevokeMyConsentUnauthorized Problem + +func (*RevokeMyConsentUnauthorized) revokeMyConsentRes() {} + +type RevokeMyOrganizationContactConsentForbidden Problem + +func (*RevokeMyOrganizationContactConsentForbidden) revokeMyOrganizationContactConsentRes() {} + +// RevokeMyOrganizationContactConsentNoContent is response for RevokeMyOrganizationContactConsent operation. +type RevokeMyOrganizationContactConsentNoContent struct{} + +func (*RevokeMyOrganizationContactConsentNoContent) revokeMyOrganizationContactConsentRes() {} + +type RevokeMyOrganizationContactConsentUnauthorized Problem + +func (*RevokeMyOrganizationContactConsentUnauthorized) revokeMyOrganizationContactConsentRes() {} + type RubAmount int64 // Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change. diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go index 22b6792..d478c28 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -56,55 +56,60 @@ func findAuthorization(h http.Header, prefix string) (string, bool) { // operationRolesSessionCookie is a private map storing roles per operation. var operationRolesSessionCookie = map[string][]string{ - AcceptMyInvitationOperation: []string{}, - CancelMyInvitationOperation: []string{}, - CreateMyAssessmentAttemptOperation: []string{}, - CreateMySupportCaseOperation: []string{}, - CreateOrganizationOperation: []string{}, - CreateOrganizationInvitationOperation: []string{}, - CreateOrganizationNeedOperation: []string{}, - DeclineMyInvitationOperation: []string{}, - FinalizeMyAssessmentAttemptOperation: []string{}, - GetCurrentAccountOperation: []string{}, - GetCurrentSessionOperation: []string{}, - GetMyAssessmentAttemptOperation: []string{}, - GetMyAssessmentAvailabilityOperation: []string{}, - GetMyAssessmentResultOperation: []string{}, - GetMyCardPreviewOperation: []string{}, - GetMyInvitationOperation: []string{}, - GetMyPrivacySettingsOperation: []string{}, - GetMyProfileOperation: []string{}, - GetMyQuestionnaireOperation: []string{}, - GetMySupportCaseOperation: []string{}, - GetOrganizationOperation: []string{}, - GetOrganizationInvitationOperation: []string{}, - GetOrganizationInvitationContactsOperation: []string{}, - GetOrganizationNeedOperation: []string{}, - HideOrganizationOperation: []string{}, - ListMyCardAccessHistoryOperation: []string{}, - ListMyConsentsOperation: []string{}, - ListMyHiddenOrganizationsOperation: []string{}, - ListMyInvitationsOperation: []string{}, - ListMyOrganizationsOperation: []string{}, - ListMyPrivacyHistoryOperation: []string{}, - ListMySupportCasesOperation: []string{}, - ListOrganizationInvitationsOperation: []string{}, - ListOrganizationNeedsOperation: []string{}, - LogoutOperation: []string{}, - RaiseOrganizationInvitationSalaryOperation: []string{}, - SaveMyProfileOperation: []string{}, - SaveMyQuestionnaireOperation: []string{}, - SendOrganizationInvitationOperation: []string{}, - SetMyPublicationOperation: []string{}, - SetMySearchStatusOperation: []string{}, - StartMyAssessmentAttemptSessionOperation: []string{}, - SubmitMyAssessmentAnswerOperation: []string{}, - UnhideOrganizationOperation: []string{}, - UpdateOrganizationOperation: []string{}, - UpdateOrganizationInvitationOperation: []string{}, - UpdateOrganizationNeedOperation: []string{}, - ViewMyInvitationOperation: []string{}, - WithdrawOrganizationInvitationOperation: []string{}, + AcceptMyInvitationOperation: []string{}, + CancelMyInvitationOperation: []string{}, + CreateMyAssessmentAttemptOperation: []string{}, + CreateMySupportCaseOperation: []string{}, + CreateOrganizationOperation: []string{}, + CreateOrganizationInvitationOperation: []string{}, + CreateOrganizationNeedOperation: []string{}, + DeclineMyInvitationOperation: []string{}, + FinalizeMyAssessmentAttemptOperation: []string{}, + GetCurrentAccountOperation: []string{}, + GetCurrentSessionOperation: []string{}, + GetMyAssessmentAttemptOperation: []string{}, + GetMyAssessmentAvailabilityOperation: []string{}, + GetMyAssessmentResultOperation: []string{}, + GetMyCardPreviewOperation: []string{}, + GetMyConsentTextOperation: []string{}, + GetMyInvitationOperation: []string{}, + GetMyPrivacySettingsOperation: []string{}, + GetMyProfileOperation: []string{}, + GetMyQuestionnaireOperation: []string{}, + GetMySupportCaseOperation: []string{}, + GetOrganizationOperation: []string{}, + GetOrganizationInvitationOperation: []string{}, + GetOrganizationInvitationContactsOperation: []string{}, + GetOrganizationNeedOperation: []string{}, + GrantMyConsentOperation: []string{}, + HideOrganizationOperation: []string{}, + ListMyCardAccessHistoryOperation: []string{}, + ListMyConsentsOperation: []string{}, + ListMyHiddenOrganizationsOperation: []string{}, + ListMyInvitationsOperation: []string{}, + ListMyOrganizationsOperation: []string{}, + ListMyPrivacyHistoryOperation: []string{}, + ListMySupportCasesOperation: []string{}, + ListOrganizationInvitationsOperation: []string{}, + ListOrganizationNeedsOperation: []string{}, + LogoutOperation: []string{}, + RaiseOrganizationInvitationSalaryOperation: []string{}, + RequestMyAccountDeletionOperation: []string{}, + RevokeMyConsentOperation: []string{}, + RevokeMyOrganizationContactConsentOperation: []string{}, + SaveMyProfileOperation: []string{}, + SaveMyQuestionnaireOperation: []string{}, + SendOrganizationInvitationOperation: []string{}, + SetMyPublicationOperation: []string{}, + SetMySearchStatusOperation: []string{}, + StartMyAssessmentAttemptSessionOperation: []string{}, + SubmitMyAssessmentAnswerOperation: []string{}, + UnhideOrganizationOperation: []string{}, + UpdateOrganizationOperation: []string{}, + UpdateOrganizationInvitationOperation: []string{}, + UpdateOrganizationNeedOperation: []string{}, + ViewMyInvitationOperation: []string{}, + WithdrawOrganizationInvitationOperation: []string{}, } // GetRolesForSessionCookie returns the required roles for the given operation. @@ -130,31 +135,35 @@ func GetRolesForSessionCookie(operation string) []string { // operationRolesSessionCsrf is a private map storing roles per operation. var operationRolesSessionCsrf = map[string][]string{ - AcceptMyInvitationOperation: []string{}, - CancelMyInvitationOperation: []string{}, - CreateMyAssessmentAttemptOperation: []string{}, - CreateMySupportCaseOperation: []string{}, - CreateOrganizationOperation: []string{}, - CreateOrganizationInvitationOperation: []string{}, - CreateOrganizationNeedOperation: []string{}, - DeclineMyInvitationOperation: []string{}, - FinalizeMyAssessmentAttemptOperation: []string{}, - HideOrganizationOperation: []string{}, - LogoutOperation: []string{}, - RaiseOrganizationInvitationSalaryOperation: []string{}, - SaveMyProfileOperation: []string{}, - SaveMyQuestionnaireOperation: []string{}, - SendOrganizationInvitationOperation: []string{}, - SetMyPublicationOperation: []string{}, - SetMySearchStatusOperation: []string{}, - StartMyAssessmentAttemptSessionOperation: []string{}, - SubmitMyAssessmentAnswerOperation: []string{}, - UnhideOrganizationOperation: []string{}, - UpdateOrganizationOperation: []string{}, - UpdateOrganizationInvitationOperation: []string{}, - UpdateOrganizationNeedOperation: []string{}, - ViewMyInvitationOperation: []string{}, - WithdrawOrganizationInvitationOperation: []string{}, + AcceptMyInvitationOperation: []string{}, + CancelMyInvitationOperation: []string{}, + CreateMyAssessmentAttemptOperation: []string{}, + CreateMySupportCaseOperation: []string{}, + CreateOrganizationOperation: []string{}, + CreateOrganizationInvitationOperation: []string{}, + CreateOrganizationNeedOperation: []string{}, + DeclineMyInvitationOperation: []string{}, + FinalizeMyAssessmentAttemptOperation: []string{}, + GrantMyConsentOperation: []string{}, + HideOrganizationOperation: []string{}, + LogoutOperation: []string{}, + RaiseOrganizationInvitationSalaryOperation: []string{}, + RequestMyAccountDeletionOperation: []string{}, + RevokeMyConsentOperation: []string{}, + RevokeMyOrganizationContactConsentOperation: []string{}, + SaveMyProfileOperation: []string{}, + SaveMyQuestionnaireOperation: []string{}, + SendOrganizationInvitationOperation: []string{}, + SetMyPublicationOperation: []string{}, + SetMySearchStatusOperation: []string{}, + StartMyAssessmentAttemptSessionOperation: []string{}, + SubmitMyAssessmentAnswerOperation: []string{}, + UnhideOrganizationOperation: []string{}, + UpdateOrganizationOperation: []string{}, + UpdateOrganizationInvitationOperation: []string{}, + UpdateOrganizationNeedOperation: []string{}, + ViewMyInvitationOperation: []string{}, + WithdrawOrganizationInvitationOperation: []string{}, } // GetRolesForSessionCsrf returns the required roles for the given operation. diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index 7ce742c..53fbe70 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -621,6 +621,15 @@ type Handler interface { // // GET /api/v1/me/privacy/preview GetMyCardPreview(ctx context.Context) (GetMyCardPreviewRes, error) + // GetMyConsentText implements GetMyConsentText operation. + // + // Requires a verified session. Returns the current published text and version of c1, c2, c3, or c5 so + // the user can read the exact text before an explicit settings grant. C4 is excluded: its text + // includes an organization snapshot and it is granted only during invitation acceptance. The response + // is private and is not cached. + // + // GET /api/v1/me/consent-texts/{purpose} + GetMyConsentText(ctx context.Context, params GetMyConsentTextParams) (GetMyConsentTextRes, error) // GetMyInvitation implements GetMyInvitation operation. // // Requires the session cookie of a candidate account. The candidate comes from the session; the @@ -864,6 +873,20 @@ type Handler interface { // // GET /api/v1/specializations GetSpecializationCatalog(ctx context.Context) (*SpecializationCatalog, error) + // GrantMyConsent implements GrantMyConsent operation. + // + // Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The + // subject comes from the session. The body names the current text version the user read and requires + // `accepted: true`; the server verifies that version is still current and stores the hash of the exact + // text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant. + // + // C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate + // accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the + // same current version returns the existing record; after revocation a grant creates a new record and + // never reopens a publication or restores an older grant. + // + // PUT /api/v1/me/consents/{purpose} + GrantMyConsent(ctx context.Context, req *ConsentSettingsGrantRequest, params GrantMyConsentParams) (GrantMyConsentRes, error) // HideOrganization implements HideOrganization operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -945,8 +968,9 @@ type Handler interface { // value. A c2 record proves the consent to the publication text; the published field set and its // changes are evidence of the publication history. // - // Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations - // of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. + // Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit + // acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion + // request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed // `limit`, `cursor`, or `state` answers 400 validation_failed. @@ -1210,6 +1234,16 @@ type Handler interface { // // POST /api/v1/identity/registrations RegisterAccount(ctx context.Context, req *RegistrationRequest, params RegisterAccountParams) (RegisterAccountRes, error) + // RequestMyAccountDeletion implements RequestMyAccountDeletion operation. + // + // Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The + // subject comes from the session. In one transaction, revokes any active C1 record, creates or returns + // the subject's active durable deletion request, and writes the outbox intent. The API does not delete + // the account synchronously. Repeating the request returns the same active request; a later C1 grant + // never cancels it. + // + // POST /api/v1/me/account-deletion-requests + RequestMyAccountDeletion(ctx context.Context) (RequestMyAccountDeletionRes, error) // ResendEmailVerification implements ResendEmailVerification operation. // // Public operation without a session. The answer is the same 202 for an unknown email, a verified @@ -1226,6 +1260,31 @@ type Handler interface { // // POST /api/v1/identity/email-verification-requests ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (ResendEmailVerificationRes, error) + // RevokeMyConsent implements RevokeMyConsent operation. + // + // Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured + // Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5, + // including superseded records, and never changes another purpose. Repeating a revocation is harmless + // and creates no duplicate event. + // + // Revoking c2 immediately closes the stored publication and records privacy history in the same + // transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not + // reopen publication or restore old grants. Revoking c3 does not block the manual assessment path. + // Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent; + // an external FSP deletion adapter is not available yet. + // + // DELETE /api/v1/me/consents/{purpose} + RevokeMyConsent(ctx context.Context, params RevokeMyConsentParams) (RevokeMyConsentRes, error) + // RevokeMyOrganizationContactConsent implements RevokeMyOrganizationContactConsent operation. + // + // Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured + // Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The + // server revokes every unrevoked C4 record for this subject and organization, using the fields stored + // on those records to request downstream grant revocation. It does not affect another organization. + // Repeating the request is harmless and creates no duplicate event. + // + // DELETE /api/v1/me/consents/c4/organizations/{org_id} + RevokeMyOrganizationContactConsent(ctx context.Context, params RevokeMyOrganizationContactConsentParams) (RevokeMyOrganizationContactConsentRes, error) // SaveMyProfile implements SaveMyProfile operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index edb74e4..cfc31cc 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -680,6 +680,18 @@ func (UnimplementedHandler) GetMyCardPreview(ctx context.Context) (r GetMyCardPr return r, ht.ErrNotImplemented } +// GetMyConsentText implements GetMyConsentText operation. +// +// Requires a verified session. Returns the current published text and version of c1, c2, c3, or c5 so +// the user can read the exact text before an explicit settings grant. C4 is excluded: its text +// includes an organization snapshot and it is granted only during invitation acceptance. The response +// is private and is not cached. +// +// GET /api/v1/me/consent-texts/{purpose} +func (UnimplementedHandler) GetMyConsentText(ctx context.Context, params GetMyConsentTextParams) (r GetMyConsentTextRes, _ error) { + return r, ht.ErrNotImplemented +} + // GetMyInvitation implements GetMyInvitation operation. // // Requires the session cookie of a candidate account. The candidate comes from the session; the @@ -953,6 +965,23 @@ func (UnimplementedHandler) GetSpecializationCatalog(ctx context.Context) (r *Sp return r, ht.ErrNotImplemented } +// GrantMyConsent implements GrantMyConsent operation. +// +// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The +// subject comes from the session. The body names the current text version the user read and requires +// `accepted: true`; the server verifies that version is still current and stores the hash of the exact +// text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant. +// +// C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate +// accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the +// same current version returns the existing record; after revocation a grant creates a new record and +// never reopens a publication or restores an older grant. +// +// PUT /api/v1/me/consents/{purpose} +func (UnimplementedHandler) GrantMyConsent(ctx context.Context, req *ConsentSettingsGrantRequest, params GrantMyConsentParams) (r GrantMyConsentRes, _ error) { + return r, ht.ErrNotImplemented +} + // HideOrganization implements HideOrganization operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -1040,8 +1069,9 @@ func (UnimplementedHandler) ListMyCardAccessHistory(ctx context.Context, params // value. A c2 record proves the consent to the publication text; the published field set and its // changes are evidence of the publication history. // -// Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations -// of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. +// Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit +// acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion +// request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed // `limit`, `cursor`, or `state` answers 400 validation_failed. @@ -1341,6 +1371,19 @@ func (UnimplementedHandler) RegisterAccount(ctx context.Context, req *Registrati return r, ht.ErrNotImplemented } +// RequestMyAccountDeletion implements RequestMyAccountDeletion operation. +// +// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The +// subject comes from the session. In one transaction, revokes any active C1 record, creates or returns +// the subject's active durable deletion request, and writes the outbox intent. The API does not delete +// the account synchronously. Repeating the request returns the same active request; a later C1 grant +// never cancels it. +// +// POST /api/v1/me/account-deletion-requests +func (UnimplementedHandler) RequestMyAccountDeletion(ctx context.Context) (r RequestMyAccountDeletionRes, _ error) { + return r, ht.ErrNotImplemented +} + // ResendEmailVerification implements ResendEmailVerification operation. // // Public operation without a session. The answer is the same 202 for an unknown email, a verified @@ -1360,6 +1403,37 @@ func (UnimplementedHandler) ResendEmailVerification(ctx context.Context, req *Em return r, ht.ErrNotImplemented } +// RevokeMyConsent implements RevokeMyConsent operation. +// +// Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured +// Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5, +// including superseded records, and never changes another purpose. Repeating a revocation is harmless +// and creates no duplicate event. +// +// Revoking c2 immediately closes the stored publication and records privacy history in the same +// transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not +// reopen publication or restore old grants. Revoking c3 does not block the manual assessment path. +// Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent; +// an external FSP deletion adapter is not available yet. +// +// DELETE /api/v1/me/consents/{purpose} +func (UnimplementedHandler) RevokeMyConsent(ctx context.Context, params RevokeMyConsentParams) (r RevokeMyConsentRes, _ error) { + return r, ht.ErrNotImplemented +} + +// RevokeMyOrganizationContactConsent implements RevokeMyOrganizationContactConsent operation. +// +// Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured +// Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The +// server revokes every unrevoked C4 record for this subject and organization, using the fields stored +// on those records to request downstream grant revocation. It does not affect another organization. +// Repeating the request is harmless and creates no duplicate event. +// +// DELETE /api/v1/me/consents/c4/organizations/{org_id} +func (UnimplementedHandler) RevokeMyOrganizationContactConsent(ctx context.Context, params RevokeMyOrganizationContactConsentParams) (r RevokeMyOrganizationContactConsentRes, _ error) { + return r, ht.ErrNotImplemented +} + // SaveMyProfile implements SaveMyProfile operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index af643e0..7606516 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -5934,6 +5934,74 @@ func (s *ConfirmEmailForbidden) Validate() error { return nil } +func (s *ConsentDeletionRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ConsentDeletionRequestHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ConsentDeletionRequestStatus) Validate() error { + switch s { + case "requested": + return nil + case "processing": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *ConsentOrganization) Validate() error { if s == nil { return validate.ErrNilPointer @@ -6144,6 +6212,40 @@ func (s *ConsentRecord) Validate() error { return nil } +func (s *ConsentRecordHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *ConsentRecordList) Validate() error { if s == nil { return validate.ErrNilPointer @@ -6248,6 +6350,77 @@ func (s ConsentRevocationSource) Validate() error { } } +func (s *ConsentSettingsGrantRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.TextVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text_version", + Error: err, + }) + } + if err := func() error { + if err := s.Accepted.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "accepted", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ConsentSettingsGrantRequestAccepted) Validate() error { + switch s { + case true: + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s ConsentSettingsPurpose) Validate() error { + switch s { + case "c1": + return nil + case "c2": + return nil + case "c3": + return nil + case "c5": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s ConsentSettingsRevokePurpose) Validate() error { + switch s { + case "c2": + return nil + case "c3": + return nil + case "c5": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s ConsentSource) Validate() error { switch s { case "registration": @@ -6331,6 +6504,40 @@ func (s *ConsentText) Validate() error { return nil } +func (s *ConsentTextHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s ConsentTextVersion) Validate() error { alias := (string)(s) if err := (validate.String{ @@ -7773,6 +7980,22 @@ func (s *GetMyCardPreviewUnauthorized) Validate() error { return nil } +func (s *GetMyConsentTextBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyConsentTextUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *GetMyInvitationBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -8020,6 +8243,30 @@ func (s GradeCode) Validate() error { } } +func (s *GrantMyConsentBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GrantMyConsentForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GrantMyConsentUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *HealthResponse) Validate() error { if s == nil { return validate.ErrNilPointer @@ -17451,6 +17698,22 @@ func (s *RegistrationRequest) Validate() error { return nil } +func (s *RequestMyAccountDeletionForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RequestMyAccountDeletionUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *ResendEmailVerificationBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -17467,6 +17730,38 @@ func (s *ResendEmailVerificationForbidden) Validate() error { return nil } +func (s *RevokeMyConsentForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RevokeMyConsentUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RevokeMyOrganizationContactConsentForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RevokeMyOrganizationContactConsentUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s RubAmount) Validate() error { alias := (int64)(s) if err := (validate.Int{ diff --git a/backend/internal/adapter/primary/http/v1/api.go b/backend/internal/adapter/primary/http/v1/api.go index d75b6a1..0be1bb1 100644 --- a/backend/internal/adapter/primary/http/v1/api.go +++ b/backend/internal/adapter/primary/http/v1/api.go @@ -17,9 +17,11 @@ import ( type Handler struct { api.UnimplementedHandler - health *HealthHandler - identity *IdentityHandler - problems *problem.Responder + health *HealthHandler + identity *IdentityHandler + consent *ConsentHandler + organization *OrganizationHandler + problems *problem.Responder } var _ api.Handler = (*Handler)(nil) @@ -32,6 +34,16 @@ func WithIdentity(identity *IdentityHandler) HandlerOption { return func(handler *Handler) { handler.identity = identity } } +// WithConsent serves the published texts and ledger operations. +func WithConsent(consent *ConsentHandler) HandlerOption { + return func(handler *Handler) { handler.consent = consent } +} + +// WithOrganization serves company profiles and owner operations. +func WithOrganization(organization *OrganizationHandler) HandlerOption { + return func(handler *Handler) { handler.organization = organization } +} + func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler { handler := &Handler{health: health, problems: problems} for _, option := range options { diff --git a/backend/internal/adapter/primary/http/v1/consent.go b/backend/internal/adapter/primary/http/v1/consent.go new file mode 100644 index 0000000..9839bad --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/consent.go @@ -0,0 +1,432 @@ +package v1 + +import ( + "context" + "encoding/base64" + "encoding/binary" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/consent" +) + +const ( + defaultConsentPageLimit = 20 + consentCursorVersion = 1 + consentCursorBytes = 42 + maxConsentCursorNanos = int64(1<<63 - 1) + minConsentCursorNanos = -maxConsentCursorNanos - 1 +) + +// ConsentQueries reads current texts and a subject's own consent history. +type ConsentQueries interface { + CurrentText(ctx context.Context, purpose domain.ConsentPurpose) (domain.ConsentText, error) + List(ctx context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) +} + +// ConsentCommands records grants, revocations, and deletion requests. +type ConsentCommands interface { + GrantInSettingsInNewTransaction(ctx context.Context, input consent.SettingsGrantInput) (consent.GrantResult, error) + RevokeInSettingsInNewTransaction(ctx context.Context, input consent.SettingsRevocationInput) (consent.RevocationResult, error) + RequestAccountDeletionInNewTransaction(ctx context.Context, subjectID uuid.UUID) (domain.AccountDeletionRequest, error) +} + +// ConsentHandler serves consent text and ledger operations. +type ConsentHandler struct { + queries ConsentQueries + commands ConsentCommands +} + +func NewConsentHandler(queries ConsentQueries, commands ConsentCommands) *ConsentHandler { + if queries == nil || commands == nil { + panic("v1.NewConsentHandler - query and command services must not be nil") + } + return &ConsentHandler{queries: queries, commands: commands} +} + +func (handler *Handler) GetConsentText(ctx context.Context, params api.GetConsentTextParams) (api.GetConsentTextRes, error) { + if handler.consent == nil { + return handler.UnimplementedHandler.GetConsentText(ctx, params) + } + return handler.consent.GetConsentText(ctx, params) +} + +func (handler *Handler) GetMyConsentText(ctx context.Context, params api.GetMyConsentTextParams) (api.GetMyConsentTextRes, error) { + if handler.consent == nil { + return handler.UnimplementedHandler.GetMyConsentText(ctx, params) + } + return handler.consent.GetMyConsentText(ctx, params) +} + +func (handler *Handler) ListMyConsents(ctx context.Context, params api.ListMyConsentsParams) (api.ListMyConsentsRes, error) { + if handler.consent == nil { + return handler.UnimplementedHandler.ListMyConsents(ctx, params) + } + return handler.consent.ListMyConsents(ctx, params) +} + +func (handler *Handler) GrantMyConsent(ctx context.Context, request *api.ConsentSettingsGrantRequest, params api.GrantMyConsentParams) (api.GrantMyConsentRes, error) { + if handler.consent == nil { + return handler.UnimplementedHandler.GrantMyConsent(ctx, request, params) + } + return handler.consent.GrantMyConsent(ctx, request, params) +} + +func (handler *Handler) RevokeMyConsent(ctx context.Context, params api.RevokeMyConsentParams) (api.RevokeMyConsentRes, error) { + if handler.consent == nil { + return handler.UnimplementedHandler.RevokeMyConsent(ctx, params) + } + return handler.consent.RevokeMyConsent(ctx, params) +} + +func (handler *Handler) RevokeMyOrganizationContactConsent(ctx context.Context, params api.RevokeMyOrganizationContactConsentParams) (api.RevokeMyOrganizationContactConsentRes, error) { + if handler.consent == nil { + return handler.UnimplementedHandler.RevokeMyOrganizationContactConsent(ctx, params) + } + return handler.consent.RevokeMyOrganizationContactConsent(ctx, params) +} + +func (handler *Handler) RequestMyAccountDeletion(ctx context.Context) (api.RequestMyAccountDeletionRes, error) { + if handler.consent == nil { + return handler.UnimplementedHandler.RequestMyAccountDeletion(ctx) + } + return handler.consent.RequestMyAccountDeletion(ctx) +} + +func (handler *ConsentHandler) GetConsentText(ctx context.Context, params api.GetConsentTextParams) (api.GetConsentTextRes, error) { + purpose := domain.ConsentPurpose(params.Purpose) + if purpose != domain.ConsentPurposePersonalData { + response := problem.New(ctx, api.ProblemCodeValidationFailed).Response + return &response, nil + } + text, err := handler.queries.CurrentText(ctx, purpose) + if err != nil { + return nil, err + } + response := consentTextResponse(text) + return &response, nil +} + +func (handler *ConsentHandler) GetMyConsentText(ctx context.Context, params api.GetMyConsentTextParams) (api.GetMyConsentTextRes, error) { + if _, ok := currentConsentPrincipal(ctx); !ok { + return (*api.GetMyConsentTextUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + text, err := handler.queries.CurrentText(ctx, domain.ConsentPurpose(params.Purpose)) + if err != nil { + return nil, err + } + return &api.ConsentTextHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: consentTextResponse(text), + }, nil +} + +func (handler *ConsentHandler) ListMyConsents(ctx context.Context, params api.ListMyConsentsParams) (api.ListMyConsentsRes, error) { + principal, ok := currentConsentPrincipal(ctx) + if !ok { + return (*api.ListMyConsentsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + query, err := consentListQuery(principal.UserID, params) + if err != nil { + return consentListInvalid(ctx, err), nil + } + page, err := handler.queries.List(ctx, query) + if err != nil { + if errors.Is(err, domain.ErrInvalidConsent) { + return consentListInvalid(ctx, err), nil + } + return nil, err + } + items := make([]api.ConsentRecord, 0, len(page.Records)) + for _, record := range page.Records { + items = append(items, consentRecordResponse(record)) + } + var nextCursor api.NilString + nextCursor.SetToNull() + if page.HasMore && len(page.Records) > 0 { + last := page.Records[len(page.Records)-1] + cursor, err := encodeConsentCursor(principal.UserID, query.State, outbound.ConsentPositionOf(last)) + if err != nil { + return nil, fmt.Errorf("ConsentHandler.ListMyConsents - encode cursor: %w", err) + } + nextCursor.SetTo(cursor) + } + return &api.ConsentRecordListHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: api.ConsentRecordList{ + Items: items, + Page: api.PageInfo{HasMore: page.HasMore, NextCursor: nextCursor}, + }, + }, nil +} + +func (handler *ConsentHandler) GrantMyConsent(ctx context.Context, request *api.ConsentSettingsGrantRequest, params api.GrantMyConsentParams) (api.GrantMyConsentRes, error) { + principal, session, ok := currentConsentSession(ctx) + if !ok { + return (*api.GrantMyConsentUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + purpose := domain.ConsentPurpose(params.Purpose) + if candidateOnlyConsent(purpose) && session.User.Scenario != domain.ScenarioCandidate { + return (*api.GrantMyConsentForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + } + if request == nil || !bool(request.Accepted) { + return consentGrantInvalid(ctx, "/accepted"), nil + } + result, err := handler.commands.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{ + SubjectID: principal.UserID, Purpose: purpose, TextVersion: domain.ConsentTextVersion(request.TextVersion), + }) + if err != nil { + if errors.Is(err, consent.ErrStaleConsentText) { + return consentGrantInvalid(ctx, "/text_version"), nil + } + return nil, err + } + return &api.ConsentRecordHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: consentRecordResponse(result.Record), + }, nil +} + +func (handler *ConsentHandler) RevokeMyConsent(ctx context.Context, params api.RevokeMyConsentParams) (api.RevokeMyConsentRes, error) { + principal, session, ok := currentConsentSession(ctx) + if !ok { + return (*api.RevokeMyConsentUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if session.User.Scenario != domain.ScenarioCandidate { + return (*api.RevokeMyConsentForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + } + _, err := handler.commands.RevokeInSettingsInNewTransaction(ctx, consent.SettingsRevocationInput{ + SubjectID: principal.UserID, Purpose: domain.ConsentPurpose(params.Purpose), + }) + if err != nil { + return nil, err + } + return &api.RevokeMyConsentNoContent{}, nil +} + +func (handler *ConsentHandler) RevokeMyOrganizationContactConsent(ctx context.Context, params api.RevokeMyOrganizationContactConsentParams) (api.RevokeMyOrganizationContactConsentRes, error) { + principal, session, ok := currentConsentSession(ctx) + if !ok { + return (*api.RevokeMyOrganizationContactConsentUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if session.User.Scenario != domain.ScenarioCandidate { + return (*api.RevokeMyOrganizationContactConsentForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + } + _, err := handler.commands.RevokeInSettingsInNewTransaction(ctx, consent.SettingsRevocationInput{ + SubjectID: principal.UserID, Purpose: domain.ConsentPurposeContactDisclosure, OrganizationID: params.OrgID, + }) + if err != nil { + return nil, err + } + return &api.RevokeMyOrganizationContactConsentNoContent{}, nil +} + +func (handler *ConsentHandler) RequestMyAccountDeletion(ctx context.Context) (api.RequestMyAccountDeletionRes, error) { + principal, ok := currentConsentPrincipal(ctx) + if !ok { + return (*api.RequestMyAccountDeletionUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + request, err := handler.commands.RequestAccountDeletionInNewTransaction(ctx, principal.UserID) + if err != nil { + return nil, err + } + return &api.ConsentDeletionRequestHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: api.ConsentDeletionRequest{ + ID: request.ID(), Status: api.ConsentDeletionRequestStatus(request.Status()), RequestedAt: api.Timestamp(request.RequestedAt()), + }, + }, nil +} + +func currentConsentPrincipal(ctx context.Context) (Principal, bool) { + principal, ok := PrincipalFromContext(ctx) + if !ok || !principal.EmailVerified { + return Principal{}, false + } + session, ok := sessionFromContext(ctx) + if !ok || session.Principal != principal || session.User.ID != principal.UserID || !session.User.EmailVerified() { + return Principal{}, false + } + return principal, true +} + +func currentConsentSession(ctx context.Context) (Principal, authenticatedSession, bool) { + principal, ok := currentConsentPrincipal(ctx) + if !ok { + return Principal{}, authenticatedSession{}, false + } + session, ok := sessionFromContext(ctx) + return principal, session, ok +} + +func candidateOnlyConsent(purpose domain.ConsentPurpose) bool { + return purpose == domain.ConsentPurposePublication || purpose == domain.ConsentPurposeAutoCategorization || + purpose == domain.ConsentPurposeFSPImport +} + +func consentTextResponse(text domain.ConsentText) api.ConsentText { + return api.ConsentText{ + Purpose: api.ConsentPurposeCode(text.Purpose()), TextVersion: api.ConsentTextVersion(text.Version()), + Text: text.Body(), PublishedAt: api.Timestamp(text.PublishedAt()), + } +} + +func consentRecordResponse(record domain.ConsentRecord) api.ConsentRecord { + response := api.ConsentRecord{ + ID: record.ID(), Purpose: api.ConsentPurposeCode(record.Purpose()), State: api.ConsentState(record.State()), + TextVersion: api.ConsentTextVersion(record.TextVersion()), Source: api.ConsentSource(record.Source()), + GrantedAt: api.Timestamp(record.GrantedAt()), Fields: mapContactFields(record.Fields().Fields()), + } + if revokedAt, ok := record.RevokedAt(); ok { + response.RevokedAt.SetTo(api.Timestamp(revokedAt)) + response.RevocationSource.SetTo(api.ConsentRevocationSource(record.RevocationSource())) + } else { + response.RevokedAt.SetToNull() + response.RevocationSource.SetToNull() + } + if record.Purpose().OrganizationScoped() { + response.Organization.SetTo(api.ConsentOrganization{ID: record.OrganizationID(), Name: record.OrganizationName()}) + response.InvitationID.SetTo(record.InvitationID()) + response.InvitationTermsVersion.SetTo(api.InvitationTermsVersion(record.InvitationTermsVersion())) + } else { + response.Organization.SetToNull() + response.InvitationID.SetToNull() + response.InvitationTermsVersion.SetToNull() + } + return response +} + +func mapContactFields(fields []domain.ContactField) []api.ContactFieldKind { + if fields == nil { + return nil + } + mapped := make([]api.ContactFieldKind, 0, len(fields)) + for _, field := range fields { + mapped = append(mapped, api.ContactFieldKind(field)) + } + return mapped +} + +func consentListQuery(subjectID uuid.UUID, params api.ListMyConsentsParams) (outbound.ConsentListQuery, error) { + query := outbound.ConsentListQuery{SubjectID: subjectID, Limit: defaultConsentPageLimit} + if state, ok := params.State.Get(); ok { + query.State = domain.ConsentState(state) + } + if limit, ok := params.Limit.Get(); ok { + query.Limit = limit + } + if cursor, ok := params.Cursor.Get(); ok { + position, state, err := decodeConsentCursor(cursor, subjectID) + if err != nil || state != query.State { + return outbound.ConsentListQuery{}, errors.New("consent cursor is invalid") + } + query.After = &position + } + return query, nil +} + +func encodeConsentCursor(subjectID uuid.UUID, state domain.ConsentState, position outbound.ConsentListPosition) (string, error) { + nanos, inRange := consentCursorNanos(position.GrantedAt) + if subjectID == uuid.Nil || position.ID == uuid.Nil || !inRange { + return "", fmt.Errorf("encodeConsentCursor - subject and position are required: %w", domain.ErrInvalidConsent) + } + stateCode, ok := consentCursorStateCode(state) + if !ok { + return "", fmt.Errorf("encodeConsentCursor - state is invalid: %w", domain.ErrInvalidConsent) + } + var value [consentCursorBytes]byte + value[0] = consentCursorVersion + copy(value[1:17], subjectID[:]) + value[17] = stateCode + binary.BigEndian.PutUint64(value[18:26], encodeConsentCursorNanos(nanos)) + copy(value[26:], position.ID[:]) + return base64.RawURLEncoding.EncodeToString(value[:]), nil +} + +func decodeConsentCursor(cursor string, subjectID uuid.UUID) (outbound.ConsentListPosition, domain.ConsentState, error) { + value, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil || len(value) != consentCursorBytes || subjectID == uuid.Nil || value[0] != consentCursorVersion || + base64.RawURLEncoding.EncodeToString(value) != cursor || uuid.UUID(value[1:17]) != subjectID { + return outbound.ConsentListPosition{}, "", errors.New("consent cursor is invalid") + } + state, ok := consentCursorState(value[17]) + if !ok { + return outbound.ConsentListPosition{}, "", errors.New("consent cursor is invalid") + } + grantedAt := time.Unix(0, decodeConsentCursorNanos(binary.BigEndian.Uint64(value[18:26]))).UTC() + positionID := uuid.UUID(value[26:42]) + if positionID == uuid.Nil || grantedAt.IsZero() { + return outbound.ConsentListPosition{}, "", errors.New("consent cursor is invalid") + } + return outbound.ConsentListPosition{GrantedAt: grantedAt, ID: positionID}, state, nil +} + +func consentCursorNanos(at time.Time) (int64, bool) { + if at.IsZero() || at.Before(time.Unix(0, minConsentCursorNanos)) || at.After(time.Unix(0, maxConsentCursorNanos)) { + return 0, false + } + return at.UnixNano(), true +} + +func decodeConsentCursorNanos(encoded uint64) int64 { + if encoded <= uint64(maxConsentCursorNanos) { + return int64(encoded) + } + complement := ^encoded & uint64(maxConsentCursorNanos) + if complement == uint64(maxConsentCursorNanos) { + return minConsentCursorNanos + } + return -int64(complement) - 1 +} + +func encodeConsentCursorNanos(nanos int64) uint64 { + if nanos >= 0 { + return uint64(nanos) + } + return uint64(nanos&maxConsentCursorNanos) | uint64(1)<<63 +} + +func consentCursorStateCode(state domain.ConsentState) (byte, bool) { + switch state { + case "": + return 0, true + case domain.ConsentStateActive: + return 1, true + case domain.ConsentStateSuperseded: + return 2, true + case domain.ConsentStateRevoked: + return 3, true + default: + return 0, false + } +} + +func consentCursorState(code byte) (domain.ConsentState, bool) { + switch code { + case 0: + return "", true + case 1: + return domain.ConsentStateActive, true + case 2: + return domain.ConsentStateSuperseded, true + case 3: + return domain.ConsentStateRevoked, true + default: + return "", false + } +} + +func consentListInvalid(ctx context.Context, _ error) *api.ListMyConsentsBadRequest { + return (*api.ListMyConsentsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/cursor").Response) +} + +func consentGrantInvalid(ctx context.Context, pointer string) *api.GrantMyConsentBadRequest { + return (*api.GrantMyConsentBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, pointer).Response) +} diff --git a/backend/internal/adapter/primary/http/v1/consent_test.go b/backend/internal/adapter/primary/http/v1/consent_test.go new file mode 100644 index 0000000..89bd853 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/consent_test.go @@ -0,0 +1,46 @@ +package v1 + +import ( + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestConsentCursorTimeBounds(t *testing.T) { + subjectID := uuid.New() + positionID := uuid.New() + for _, grantedAt := range []time.Time{ + time.Unix(0, minConsentCursorNanos).UTC(), + time.Unix(0, -1).UTC(), + time.Unix(0, 0).UTC(), + time.Unix(0, maxConsentCursorNanos).UTC(), + } { + t.Run(grantedAt.String(), func(t *testing.T) { + cursor, err := encodeConsentCursor(subjectID, domain.ConsentStateActive, outbound.ConsentListPosition{ + GrantedAt: grantedAt, ID: positionID, + }) + if err != nil { + t.Fatalf("encode cursor at %s: %v", grantedAt, err) + } + position, state, err := decodeConsentCursor(cursor, subjectID) + if err != nil || !position.GrantedAt.Equal(grantedAt) || position.ID != positionID || state != domain.ConsentStateActive { + t.Fatalf("decode cursor = %#v, %q, %v; want time %s and matching position", position, state, err, grantedAt) + } + }) + } + + for _, grantedAt := range []time.Time{ + time.Unix(0, minConsentCursorNanos).Add(-time.Nanosecond), + time.Unix(0, maxConsentCursorNanos).Add(time.Nanosecond), + } { + if _, err := encodeConsentCursor(subjectID, domain.ConsentStateActive, outbound.ConsentListPosition{ + GrantedAt: grantedAt, ID: positionID, + }); err == nil { + t.Fatalf("encode cursor outside Unix-nanosecond range at %s: got nil error", grantedAt) + } + } +} diff --git a/backend/internal/adapter/primary/http/v1/organization.go b/backend/internal/adapter/primary/http/v1/organization.go new file mode 100644 index 0000000..cc2ed6b --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/organization.go @@ -0,0 +1,358 @@ +package v1 + +import ( + "context" + "encoding/json" + "errors" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/organization" +) + +// OrganizationOperations are the organization commands and reads served by +// this HTTP adapter. +type OrganizationOperations interface { + Create(ctx context.Context, command organization.CreateCommand) (organization.CreateResult, error) + Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error) + Update(ctx context.Context, command organization.UpdateCommand) (domain.Organization, error) +} + +// CreateOrganization delegates company creation to its business-area handler. +func (handler *Handler) CreateOrganization( + ctx context.Context, + request *api.OrganizationCreate, + params api.CreateOrganizationParams, +) (api.CreateOrganizationRes, error) { + if handler.organization == nil { + return handler.UnimplementedHandler.CreateOrganization(ctx, request, params) + } + return handler.organization.CreateOrganization(ctx, request, params) +} + +// GetOrganization delegates company reads to their business-area handler. +func (handler *Handler) GetOrganization( + ctx context.Context, + params api.GetOrganizationParams, +) (api.GetOrganizationRes, error) { + if handler.organization == nil { + return handler.UnimplementedHandler.GetOrganization(ctx, params) + } + return handler.organization.GetOrganization(ctx, params) +} + +// UpdateOrganization delegates company edits to their business-area handler. +func (handler *Handler) UpdateOrganization( + ctx context.Context, + request *api.OrganizationUpdate, + params api.UpdateOrganizationParams, +) (api.UpdateOrganizationRes, error) { + if handler.organization == nil { + return handler.UnimplementedHandler.UpdateOrganization(ctx, request, params) + } + return handler.organization.UpdateOrganization(ctx, request, params) +} + +// OrganizationHandler serves organization create, read, and profile update +// operations. +type OrganizationHandler struct { + operations OrganizationOperations + publicOrigin string +} + +func NewOrganizationHandler(operations OrganizationOperations, publicOrigin string) *OrganizationHandler { + return &OrganizationHandler{operations: operations, publicOrigin: publicOrigin} +} + +func (handler *OrganizationHandler) CreateOrganization( + ctx context.Context, + request *api.OrganizationCreate, + params api.CreateOrganizationParams, +) (api.CreateOrganizationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.CreateOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if !originAllowed(ctx, handler.publicOrigin) { + return (*api.CreateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil + } + if request == nil { + return (*api.CreateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil + } + canonicalBody, err := json.Marshal(request) + if err != nil { + return nil, err + } + result, err := handler.operations.Create(ctx, organization.CreateCommand{ + ActorID: principal.UserID, IdempotencyKey: params.IdempotencyKey, CanonicalBody: canonicalBody, + Profile: createProfileInput(request), + }) + if err != nil { + return createOrganizationFailure(ctx, err) + } + return &api.OrganizationHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: organizationFromDomain(result.Organization), + }, nil +} + +func (handler *OrganizationHandler) GetOrganization( + ctx context.Context, + params api.GetOrganizationParams, +) (api.GetOrganizationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.GetOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + company, err := handler.operations.Get(ctx, principal.UserID, params.OrgID) + if err != nil { + return getOrganizationFailure(ctx, err) + } + return &api.OrganizationHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: organizationFromDomain(company), + }, nil +} + +func (handler *OrganizationHandler) UpdateOrganization( + ctx context.Context, + request *api.OrganizationUpdate, + params api.UpdateOrganizationParams, +) (api.UpdateOrganizationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.UpdateOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if !originAllowed(ctx, handler.publicOrigin) { + return (*api.UpdateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil + } + if request == nil { + return (*api.UpdateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil + } + company, err := handler.operations.Update(ctx, organization.UpdateCommand{ + ActorID: principal.UserID, OrganizationID: params.OrgID, + ExpectedVersion: int64(request.ExpectedVersion), Patch: updateProfilePatch(request), + }) + if err != nil { + return updateOrganizationFailure(ctx, err) + } + return &api.OrganizationHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: organizationFromDomain(company), + }, nil +} + +func createProfileInput(request *api.OrganizationCreate) domain.OrganizationProfileInput { + contacts := request.Contacts.Or(api.OrganizationContactChannels{}) + description, _ := request.Description.Get() + sphere, _ := request.Sphere.Get() + representatives := make([]domain.OrganizationRepresentativeInput, 0, len(request.Representatives)) + for _, representative := range request.Representatives { + representatives = append(representatives, domain.OrganizationRepresentativeInput{ + Name: representative.Name, JobTitle: representative.JobTitle, + }) + } + return domain.OrganizationProfileInput{ + Name: string(request.Name), Description: string(description), Sphere: string(sphere), + Contacts: contactsToDomain(contacts), Representatives: representatives, + } +} + +func updateProfilePatch(request *api.OrganizationUpdate) organization.ProfilePatch { + var patch organization.ProfilePatch + if request.Name.Set { + patch.Name = organization.OptionalString{Set: true, Value: string(request.Name.Value)} + } + if request.Description.Set { + value := "" + if !request.Description.Null { + value = string(request.Description.Value) + } + patch.Description = organization.OptionalString{Set: true, Value: value} + } + if request.Sphere.Set { + value := "" + if !request.Sphere.Null { + value = string(request.Sphere.Value) + } + patch.Sphere = organization.OptionalString{Set: true, Value: value} + } + if request.Contacts.Set { + contacts, _ := request.Contacts.Get() + input := contactsToDomain(contacts) + patch.Contacts = &input + } + if request.Representatives != nil { + representatives := make([]domain.OrganizationRepresentativeInput, 0, len(request.Representatives)) + for _, representative := range request.Representatives { + representatives = append(representatives, domain.OrganizationRepresentativeInput{ + Name: representative.Name, JobTitle: representative.JobTitle, + }) + } + patch.Representatives = &representatives + } + return patch +} + +func contactsToDomain(contacts api.OrganizationContactChannels) domain.OrganizationContactsInput { + website, _ := contacts.Website.Get() + email, _ := contacts.Email.Get() + phone, _ := contacts.Phone.Get() + telegram, _ := contacts.Telegram.Get() + return domain.OrganizationContactsInput{ + Website: string(website), Email: string(email), Phone: string(phone), Telegram: string(telegram), + } +} + +func organizationFromDomain(company domain.Organization) api.Organization { + profile := company.Profile() + verification := company.Verification() + representatives := representativesFromDomain(profile.Representatives()) + card := company.CandidateCard() + return api.Organization{ + ID: company.ID(), Version: api.OrganizationVersion(company.Version()), + Name: api.OrganizationName(profile.Name()), Description: nullableDescription(profile.Description()), + Sphere: nullableSphere(profile.Sphere()), Contacts: contactsFromDomain(profile.Contacts()), + Representatives: representatives, + Verification: api.OrganizationVerification{ + Level: api.OrganizationVerificationLevel(verification.Level()), + Basis: api.OrganizationVerificationBasis(verification.Basis()), + ChangedAt: api.Timestamp(verification.ChangedAt()), + }, + CandidateCard: candidateCardFromDomain(card), + CreatedAt: api.Timestamp(company.CreatedAt()), + UpdatedAt: api.Timestamp(company.UpdatedAt()), + } +} + +func candidateCardFromDomain(card domain.OrganizationCandidateCard) api.CandidateOrganizationCard { + profile := card.Profile() + representatives := representativesFromDomain(profile.Representatives()) + optionalRepresentatives := api.NewOptNilOrganizationRepresentativeArray(representatives) + return api.CandidateOrganizationCard{ + ID: card.ID(), Name: api.OrganizationName(profile.Name()), + Description: nullableDescription(profile.Description()), Sphere: nullableSphere(profile.Sphere()), + Contacts: contactsFromDomain(profile.Contacts()), Representatives: optionalRepresentatives, + VerificationLevel: api.OrganizationVerificationLevel(card.VerificationLevel()), + } +} + +func representativesFromDomain(source []domain.OrganizationRepresentative) []api.OrganizationRepresentative { + representatives := make([]api.OrganizationRepresentative, 0, len(source)) + for _, representative := range source { + representatives = append(representatives, api.OrganizationRepresentative{ + Name: representative.Name(), JobTitle: representative.JobTitle(), + }) + } + return representatives +} + +func nullableDescription(value string) api.NilOrganizationDescription { + if value == "" { + return api.NilOrganizationDescription{Null: true} + } + return api.NewNilOrganizationDescription(api.OrganizationDescription(value)) +} + +func nullableSphere(value string) api.NilOrganizationSphere { + if value == "" { + return api.NilOrganizationSphere{Null: true} + } + return api.NewNilOrganizationSphere(api.OrganizationSphere(value)) +} + +func contactsFromDomain(contacts domain.OrganizationContacts) api.OrganizationContactChannels { + return api.OrganizationContactChannels{ + Website: nullableWebsite(contacts.Website()), Email: nullableEmail(contacts.Email()), + Phone: nullablePhone(contacts.Phone()), Telegram: nullableTelegram(contacts.Telegram()), + } +} + +func nullableWebsite(value string) api.NilOrganizationWebsite { + if value == "" { + return api.NilOrganizationWebsite{Null: true} + } + return api.NewNilOrganizationWebsite(api.OrganizationWebsite(value)) +} + +func nullableEmail(value string) api.NilEmailAddress { + if value == "" { + return api.NilEmailAddress{Null: true} + } + return api.NewNilEmailAddress(api.EmailAddress(value)) +} + +func nullablePhone(value string) api.NilContactPhoneNumber { + if value == "" { + return api.NilContactPhoneNumber{Null: true} + } + return api.NewNilContactPhoneNumber(api.ContactPhoneNumber(value)) +} + +func nullableTelegram(value string) api.NilContactTelegramUsername { + if value == "" { + return api.NilContactTelegramUsername{Null: true} + } + return api.NewNilContactTelegramUsername(api.ContactTelegramUsername(value)) +} + +func createOrganizationFailure(ctx context.Context, err error) (api.CreateOrganizationRes, error) { + switch { + case errors.Is(err, organization.ErrForbidden): + return (*api.CreateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, organization.ErrEmailNotVerified): + return (*api.CreateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil + case errors.Is(err, organization.ErrIdempotencyKeyReused): + return (*api.CreateOrganizationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil + case errors.Is(err, organization.ErrInvalidIdempotencyKey): + return (*api.CreateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil + case errors.Is(err, organization.ErrInvalidCreateRequest): + return (*api.CreateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil + case errors.Is(err, domain.ErrInvalidOrganization): + return (*api.CreateOrganizationBadRequest)(&organizationFieldProblem(ctx, err).Response), nil + default: + return nil, err + } +} + +func getOrganizationFailure(ctx context.Context, err error) (api.GetOrganizationRes, error) { + switch { + case errors.Is(err, organization.ErrForbidden): + return (*api.GetOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, organization.ErrEmailNotVerified): + return (*api.GetOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil + case errors.Is(err, outbound.ErrOrganizationNotFound): + return (*api.GetOrganizationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + default: + return nil, err + } +} + +func updateOrganizationFailure(ctx context.Context, err error) (api.UpdateOrganizationRes, error) { + switch { + case errors.Is(err, organization.ErrForbidden), errors.Is(err, outbound.ErrOrganizationManagerRequired): + return (*api.UpdateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, organization.ErrEmailNotVerified): + return (*api.UpdateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil + case errors.Is(err, outbound.ErrOrganizationNotFound): + return (*api.UpdateOrganizationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case errors.Is(err, outbound.ErrOrganizationVersionConflict): + return (*api.UpdateOrganizationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil + case errors.Is(err, domain.ErrInvalidOrganization): + return (*api.UpdateOrganizationBadRequest)(&organizationFieldProblem(ctx, err).Response), nil + default: + return nil, err + } +} + +func organizationFieldProblem(ctx context.Context, err error) *api.ProblemStatusCode { + field, ok := errors.AsType[*domain.OrganizationFieldError](err) + if !ok { + return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "") + } + return problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer) +} diff --git a/backend/internal/adapter/secondary/postgres/consent_revocation.go b/backend/internal/adapter/secondary/postgres/consent_revocation.go new file mode 100644 index 0000000..5993048 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/consent_revocation.go @@ -0,0 +1,211 @@ +package postgres + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +type accountDeletionRequestRepository struct { + queries *sqlc.Queries +} + +func (unit *UnitOfWork) AccountDeletionRequests() outbound.AccountDeletionRequests { + return accountDeletionRequestRepository{queries: unit.queries} +} + +func (repository accountDeletionRequestRepository) CreateOrGet( + ctx context.Context, + request domain.AccountDeletionRequest, +) (domain.AccountDeletionRequest, bool, error) { + if request.IsZero() { + return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - request is not initialized: %w", domain.ErrInvalidConsent) + } + row, err := repository.queries.CreateAccountDeletionRequest(ctx, sqlc.CreateAccountDeletionRequestParams{ + ID: pgUUID(request.ID()), + SubjectID: pgUUID(request.SubjectID()), + RequestedAt: pgTime(request.RequestedAt()), + }) + if err == nil { + stored, err := accountDeletionRequestFromRow(row.ID, row.SubjectID, row.Status, row.RequestedAt) + return stored, err == nil, err + } + if !errors.Is(err, pgx.ErrNoRows) { + return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - insert request: %w", mapConsentError(err)) + } + activeRow, err := repository.queries.GetActiveAccountDeletionRequest(ctx, pgUUID(request.SubjectID())) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - concurrent request was not readable: %w", outbound.ErrTransactionConflict) + } + return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - select active request: %w", mapConsentError(err)) + } + stored, err := accountDeletionRequestFromRow(activeRow.ID, activeRow.SubjectID, activeRow.Status, activeRow.RequestedAt) + return stored, false, err +} + +func accountDeletionRequestFromRow(id, subjectID pgtype.UUID, status string, requestedAt pgtype.Timestamptz) (domain.AccountDeletionRequest, error) { + if !id.Valid || !subjectID.Valid || !requestedAt.Valid { + return domain.AccountDeletionRequest{}, fmt.Errorf("postgres.accountDeletionRequestFromRow - required column is null: %w", domain.ErrInvalidConsent) + } + request, err := domain.RestoreAccountDeletionRequest(id.Bytes, subjectID.Bytes, status, requestedAt.Time) + if err != nil { + return domain.AccountDeletionRequest{}, fmt.Errorf("postgres.accountDeletionRequestFromRow - restore request: %w", err) + } + return request, nil +} + +type consentRevocationEffects struct { + queries *sqlc.Queries +} + +func (unit *UnitOfWork) ConsentRevocationEffects() outbound.ConsentRevocationEffects { + return consentRevocationEffects{queries: unit.queries} +} + +var _ outbound.ConsentRevocationEffects = consentRevocationEffects{} + +func (effects consentRevocationEffects) Apply( + ctx context.Context, + revocation domain.ConsentRevocation, + records []domain.ConsentRecord, +) error { + if revocation.IsZero() || len(records) == 0 { + return fmt.Errorf("consentRevocationEffects.Apply - revocation and affected records are required: %w", domain.ErrInvalidConsent) + } + for _, record := range records { + if record.IsZero() || record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() || + (revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) { + return fmt.Errorf("consentRevocationEffects.Apply - record scope does not match revocation: %w", domain.ErrInvalidConsent) + } + } + if revocation.Purpose() == domain.ConsentPurposePublication { + if err := effects.closePublication(ctx, revocation, records); err != nil { + return fmt.Errorf("consentRevocationEffects.Apply - close publication: %w", err) + } + } + if err := effects.appendRevocationIntent(ctx, revocation, records); err != nil { + return fmt.Errorf("consentRevocationEffects.Apply - append outbox intent: %w", err) + } + return nil +} + +func (effects consentRevocationEffects) closePublication( + ctx context.Context, + revocation domain.ConsentRevocation, + records []domain.ConsentRecord, +) error { + const location = "consentRevocationEffects.closePublication" + recordIDs := make([]pgtype.UUID, 0, len(records)) + for _, record := range records { + if record.Purpose() == domain.ConsentPurposePublication { + recordIDs = append(recordIDs, pgUUID(record.ID())) + } + } + if len(recordIDs) == 0 { + return fmt.Errorf("%s - revoked C2 record IDs are required: %w", location, domain.ErrInvalidConsent) + } + row, err := effects.queries.LockCandidatePublicationForConsentRevocation(ctx, sqlc.LockCandidatePublicationForConsentRevocationParams{ + UserID: pgUUID(revocation.SubjectID()), ConsentRecordIds: recordIDs, + }) + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + if err != nil { + return fmt.Errorf("%s - close publication: %w", location, mapConsentError(err)) + } + if !row.Valid { + return fmt.Errorf("%s - query returned no closing time: %w", location, domain.ErrInvalidVisibility) + } + event, err := domain.NewConsentRevokedPublicationEvent(revocation.SubjectID(), row.Time) + if err != nil { + return fmt.Errorf("%s - build publication privacy event: %w", location, err) + } + if err := effects.queries.InsertCandidatePrivacyEvent(ctx, sqlc.InsertCandidatePrivacyEventParams{ + ID: pgUUID(event.ID()), + UserID: pgUUID(event.UserID()), + Kind: string(event.Kind()), + OccurredAt: pgTime(event.OccurredAt()), + Fields: event.Fields().Codes(), + ConsentRecordID: pgtype.UUID{}, + OrganizationID: pgtype.UUID{}, + }); err != nil { + return fmt.Errorf("%s - record publication privacy event: %w", location, mapConsentError(err)) + } + return nil +} + +type consentRevocationPayload struct { + RevocationID uuid.UUID `json:"revocation_id"` + RecordID uuid.UUID `json:"record_id"` + SubjectID uuid.UUID `json:"subject_id"` + Purpose domain.ConsentPurpose `json:"purpose"` + Source domain.ConsentRevocationSource `json:"source"` + RevokedAt time.Time `json:"revoked_at"` + OrganizationID *uuid.UUID `json:"organization_id,omitempty"` + Fields []domain.ContactField `json:"fields,omitempty"` +} + +func (effects consentRevocationEffects) appendRevocationIntent( + ctx context.Context, + revocation domain.ConsentRevocation, + records []domain.ConsentRecord, +) error { + events, err := newConsentRevocationEvents(revocation, records) + if err != nil { + return fmt.Errorf("consentRevocationEffects.appendRevocationIntent - build events: %w", err) + } + if err := outboxWriter(effects).Append(ctx, events...); err != nil { + return fmt.Errorf("consentRevocationEffects.appendRevocationIntent - append events: %w", err) + } + return nil +} + +func newConsentRevocationEvents(revocation domain.ConsentRevocation, records []domain.ConsentRecord) ([]domain.DomainEvent, error) { + if revocation.IsZero() || len(records) == 0 { + return nil, fmt.Errorf("newConsentRevocationEvents - revocation and records are required: %w", domain.ErrInvalidConsent) + } + revocationID, err := uuid.NewV7() + if err != nil { + return nil, fmt.Errorf("newConsentRevocationEvents - generate revocation ID: %w", err) + } + events := make([]domain.DomainEvent, 0, len(records)) + for _, record := range records { + if record.IsZero() || record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() || + (revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) { + return nil, fmt.Errorf("newConsentRevocationEvents - record scope does not match revocation: %w", domain.ErrInvalidConsent) + } + payload := consentRevocationPayload{ + RevocationID: revocationID, RecordID: record.ID(), SubjectID: revocation.SubjectID(), + Purpose: revocation.Purpose(), Source: revocation.Source(), RevokedAt: revocation.RevokedAt(), + } + if revocation.Purpose().OrganizationScoped() { + organizationID := record.OrganizationID() + payload.OrganizationID = &organizationID + payload.Fields = record.Fields().Fields() + } + body, err := json.Marshal(payload) + if err != nil { + return nil, fmt.Errorf("newConsentRevocationEvents - marshal payload: %w", err) + } + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: "consent.revoked", SchemaVersion: 1, AggregateType: "consent_record", + AggregateID: record.ID(), AggregateVersion: 2, Payload: body, + }) + if err != nil { + return nil, fmt.Errorf("newConsentRevocationEvents - build event: %w", err) + } + events = append(events, event) + } + return events, nil +} diff --git a/backend/internal/adapter/secondary/postgres/consent_revocation_test.go b/backend/internal/adapter/secondary/postgres/consent_revocation_test.go new file mode 100644 index 0000000..ce7919d --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/consent_revocation_test.go @@ -0,0 +1,91 @@ +package postgres + +import ( + "encoding/json" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +func TestConsentRevocationEventsStayBoundedForLargeContactHistory(t *testing.T) { + const historySize = 500 + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + subject := uuid.New() + organization := uuid.New() + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: subject, Purpose: domain.ConsentPurposeContactDisclosure, OrganizationID: organization, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: now, + }) + if err != nil { + t.Fatal(err) + } + fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone) + if err != nil { + t.Fatal(err) + } + fieldCodes := make([]string, 0, len(fields.Fields())) + for _, field := range fields.Fields() { + fieldCodes = append(fieldCodes, string(field)) + } + hash := domain.HashConsentText("c4 text with the stored organization snapshot") + records := make([]domain.ConsentRecord, 0, historySize) + legacyFacts := make([]uuid.UUID, 0, historySize) + for index := 0; index < historySize; index++ { + id := uuid.New() + legacyFacts = append(legacyFacts, id) + record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{ + ID: id, SubjectID: subject, Purpose: string(domain.ConsentPurposeContactDisclosure), + TextVersion: "c4-2026-10-01", TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance), + State: string(domain.ConsentStateActive), GrantedAt: now.Add(-time.Duration(index+1) * time.Minute), + OrganizationID: organization, OrganizationName: "Acme Synthetic LLC", FieldSet: fieldCodes, + InvitationID: uuid.New(), InvitationTermsVersion: 1, + }) + if err != nil { + t.Fatalf("RestoreConsentRecord() error = %v", err) + } + records = append(records, record) + } + legacyPayload, err := json.Marshal(map[string]any{"records": legacyFacts}) + if err != nil { + t.Fatal(err) + } + if len(legacyPayload) <= domain.MaxDomainEventPayloadBytes { + t.Fatalf("legacy aggregate fixture has %d bytes; expected it to exceed %d", len(legacyPayload), domain.MaxDomainEventPayloadBytes) + } + + events, err := newConsentRevocationEvents(revocation, records) + if err != nil { + t.Fatalf("newConsentRevocationEvents() error = %v", err) + } + if len(events) != historySize { + t.Fatalf("event count = %d, want one for every revoked record (%d)", len(events), historySize) + } + seen := make(map[uuid.UUID]bool, historySize) + for _, event := range events { + if event.AggregateType() != "consent_record" || event.AggregateVersion() != 2 || event.EventType() != "consent.revoked" { + t.Fatalf("event identity = %s/%s/%d, want one revoked record version", event.EventType(), event.AggregateType(), event.AggregateVersion()) + } + if len(event.Payload()) > domain.MaxDomainEventPayloadBytes { + t.Fatalf("event payload has %d bytes, above the limit", len(event.Payload())) + } + var payload struct { + RecordID uuid.UUID `json:"record_id"` + SubjectID uuid.UUID `json:"subject_id"` + Purpose domain.ConsentPurpose `json:"purpose"` + OrganizationID uuid.UUID `json:"organization_id"` + Fields []domain.ContactField `json:"fields"` + } + if err := json.Unmarshal(event.Payload(), &payload); err != nil { + t.Fatalf("decode event payload: %v", err) + } + if event.AggregateID() != payload.RecordID || payload.RecordID == uuid.Nil || seen[payload.RecordID] || + payload.SubjectID != subject || payload.Purpose != domain.ConsentPurposeContactDisclosure || + payload.OrganizationID != organization || len(payload.Fields) != 1 || payload.Fields[0] != domain.ContactFieldPhone { + t.Fatalf("event payload lost or changed a stored revocation fact: %+v", payload) + } + seen[payload.RecordID] = true + } +} diff --git a/backend/internal/adapter/secondary/postgres/consents.go b/backend/internal/adapter/secondary/postgres/consents.go index 767ff94..9129b60 100644 --- a/backend/internal/adapter/secondary/postgres/consents.go +++ b/backend/internal/adapter/secondary/postgres/consents.go @@ -22,11 +22,12 @@ import ( // never by text. The duplicate grants of the ledger are no errors: the // inserts use ON CONFLICT DO NOTHING. var consentConstraintErrors = map[constraintViolation]error{ - {foreignKeyViolationCode, "consent_records_subject_id_fkey"}: outbound.ErrUserNotFound, - {foreignKeyViolationCode, "consent_records_text_fkey"}: outbound.ErrConsentTextNotFound, - {foreignKeyViolationCode, "consent_records_published_text_fkey"}: outbound.ErrConsentTextMismatch, - {checkViolationCode, "consent_records_text_published"}: outbound.ErrConsentTextNotPublished, - {checkViolationCode, "consent_records_c4_text_hash"}: outbound.ErrConsentTextMismatch, + {foreignKeyViolationCode, "account_deletion_requests_subject_id_fkey"}: outbound.ErrUserNotFound, + {foreignKeyViolationCode, "consent_records_subject_id_fkey"}: outbound.ErrUserNotFound, + {foreignKeyViolationCode, "consent_records_text_fkey"}: outbound.ErrConsentTextNotFound, + {foreignKeyViolationCode, "consent_records_published_text_fkey"}: outbound.ErrConsentTextMismatch, + {checkViolationCode, "consent_records_text_published"}: outbound.ErrConsentTextNotPublished, + {checkViolationCode, "consent_records_c4_text_hash"}: outbound.ErrConsentTextMismatch, // The revoke queries clamp the time to the grant, so this stays a // backstop for a revocation written around them. {checkViolationCode, "consent_records_revocation_stamp"}: domain.ErrInvalidConsent, diff --git a/backend/internal/adapter/secondary/postgres/organizations.go b/backend/internal/adapter/secondary/postgres/organizations.go index 5819351..e461190 100644 --- a/backend/internal/adapter/secondary/postgres/organizations.go +++ b/backend/internal/adapter/secondary/postgres/organizations.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" @@ -59,6 +60,8 @@ type organizationRepository struct { var _ outbound.OrganizationRepository = organizationRepository{} +const maxOrganizationCreationSnapshotBytes = 65536 + func (repository organizationRepository) CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error { const location = "organizationRepository.CreateWithOwner" switch { @@ -100,6 +103,158 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or return nil } +func (repository organizationRepository) SaveCreationResult( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, + result outbound.OrganizationCreationResult, +) error { + const location = "organizationRepository.SaveCreationResult" + if scope == ([outbound.IdempotencyDigestSize]byte{}) || result.Organization.IsZero() || result.Owner.IsZero() || + result.Owner.OrganizationID() != result.Organization.ID() || result.Owner.Role() != domain.OrganizationRoleOwner || + !result.Owner.GrantsAccess() { + return fmt.Errorf("%s - scope and active owner result must be set: %w", location, domain.ErrInvalidOrganization) + } + snapshot := creationSnapshotFromDomain(result) + encoded, err := json.Marshal(snapshot) + if err != nil { + return fmt.Errorf("%s - encode domain snapshot", location) + } + if len(encoded) > maxOrganizationCreationSnapshotBytes { + return fmt.Errorf("%s - domain snapshot exceeds its storage bound: %w", location, domain.ErrInvalidOrganization) + } + if err := repository.queries.SaveOrganizationCreationResult(ctx, sqlc.SaveOrganizationCreationResultParams{ + ScopeHash: scope[:], + Snapshot: encoded, + }); err != nil { + return fmt.Errorf("%s - store domain snapshot: %w", location, mapOrganizationError(err)) + } + return nil +} + +func (repository organizationRepository) GetCreationResult( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, +) (outbound.OrganizationCreationResult, error) { + const location = "organizationRepository.GetCreationResult" + if scope == ([outbound.IdempotencyDigestSize]byte{}) { + return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - scope must be set: %w", location, domain.ErrInvalidOrganization) + } + encoded, err := repository.queries.GetOrganizationCreationResult(ctx, scope[:]) + if err != nil { + return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - read domain snapshot: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationCreationResultNotFound)) + } + if len(encoded) > maxOrganizationCreationSnapshotBytes { + return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - stored domain snapshot exceeds its bound", location) + } + var snapshot organizationCreationSnapshot + if err := json.Unmarshal(encoded, &snapshot); err != nil { + // The snapshot contains company profile data and representative names. + return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - stored domain snapshot is invalid", location) + } + result, err := snapshot.domainResult() + if err != nil { + return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - restore domain snapshot: %w", location, err) + } + return result, nil +} + +type organizationCreationSnapshot struct { + Organization organizationCreationOrganizationSnapshot `json:"organization"` + Owner organizationCreationMembershipSnapshot `json:"owner"` +} + +type organizationCreationOrganizationSnapshot struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Sphere string `json:"sphere"` + Website string `json:"website"` + Email string `json:"email"` + Phone string `json:"phone"` + Telegram string `json:"telegram"` + Representatives []organizationCreationRepresentativeSnapshot `json:"representatives"` + VerificationLevel string `json:"verification_level"` + VerificationBasis string `json:"verification_basis"` + VerificationChangedAt time.Time `json:"verification_changed_at"` + Version int64 `json:"version"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +type organizationCreationRepresentativeSnapshot struct { + Name string `json:"name"` + JobTitle string `json:"job_title"` +} + +type organizationCreationMembershipSnapshot struct { + ID uuid.UUID `json:"id"` + OrganizationID uuid.UUID `json:"organization_id"` + UserID uuid.UUID `json:"user_id"` + Role string `json:"role"` + State string `json:"state"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +func creationSnapshotFromDomain(result outbound.OrganizationCreationResult) organizationCreationSnapshot { + organization := result.Organization + profile := organization.Profile() + contacts := profile.Contacts() + representatives := profile.Representatives() + snapshotRepresentatives := make([]organizationCreationRepresentativeSnapshot, 0, len(representatives)) + for _, representative := range representatives { + snapshotRepresentatives = append(snapshotRepresentatives, organizationCreationRepresentativeSnapshot{ + Name: representative.Name(), JobTitle: representative.JobTitle(), + }) + } + verification := organization.Verification() + owner := result.Owner + return organizationCreationSnapshot{ + Organization: organizationCreationOrganizationSnapshot{ + ID: organization.ID(), Name: profile.Name(), Description: profile.Description(), Sphere: profile.Sphere(), + Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(), + Representatives: snapshotRepresentatives, VerificationLevel: string(verification.Level()), + VerificationBasis: string(verification.Basis()), VerificationChangedAt: verification.ChangedAt(), + Version: organization.Version(), CreatedAt: organization.CreatedAt(), UpdatedAt: organization.UpdatedAt(), + }, + Owner: organizationCreationMembershipSnapshot{ + ID: owner.ID(), OrganizationID: owner.OrganizationID(), UserID: owner.UserID(), Role: string(owner.Role()), + State: string(owner.State()), CreatedAt: owner.CreatedAt(), UpdatedAt: owner.UpdatedAt(), + }, + } +} + +func (snapshot organizationCreationSnapshot) domainResult() (outbound.OrganizationCreationResult, error) { + stored := snapshot.Organization + representatives := make([]domain.StoredRepresentative, 0, len(stored.Representatives)) + for _, representative := range stored.Representatives { + representatives = append(representatives, domain.StoredRepresentative{ + Name: representative.Name, JobTitle: representative.JobTitle, + }) + } + organization, err := domain.RestoreOrganization(domain.StoredOrganization{ + ID: stored.ID, Name: stored.Name, Description: stored.Description, Sphere: stored.Sphere, + Website: stored.Website, Email: stored.Email, Phone: stored.Phone, Telegram: stored.Telegram, + Representatives: representatives, VerificationLevel: stored.VerificationLevel, VerificationBasis: stored.VerificationBasis, + VerificationChangedAt: stored.VerificationChangedAt, Version: stored.Version, CreatedAt: stored.CreatedAt, UpdatedAt: stored.UpdatedAt, + }) + if err != nil { + return outbound.OrganizationCreationResult{}, err + } + owner := snapshot.Owner + membership, err := domain.RestoreMembership(domain.StoredMembership{ + ID: owner.ID, OrganizationID: owner.OrganizationID, UserID: owner.UserID, + Role: owner.Role, State: owner.State, CreatedAt: owner.CreatedAt, UpdatedAt: owner.UpdatedAt, + }) + if err != nil { + return outbound.OrganizationCreationResult{}, err + } + if membership.OrganizationID() != organization.ID() || membership.Role() != domain.OrganizationRoleOwner || !membership.GrantsAccess() { + return outbound.OrganizationCreationResult{}, domain.ErrInvalidMembership + } + return outbound.OrganizationCreationResult{Organization: organization, Owner: membership}, nil +} + func (repository organizationRepository) insertRepresentatives( ctx context.Context, organizationID uuid.UUID, diff --git a/backend/internal/adapter/secondary/postgres/organizations_test.go b/backend/internal/adapter/secondary/postgres/organizations_test.go index 891ea13..b59ffb9 100644 --- a/backend/internal/adapter/secondary/postgres/organizations_test.go +++ b/backend/internal/adapter/secondary/postgres/organizations_test.go @@ -2,9 +2,11 @@ package postgres import ( "context" + "encoding/json" "errors" "strings" "testing" + "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgconn" @@ -81,3 +83,50 @@ func TestManagerRoleNamesFollowTheDomainRule(t *testing.T) { t.Fatalf("managerRoleNames() = %v, want only the owner", got) } } + +func TestOrganizationCreationSnapshotRoundTripsDomainResult(t *testing.T) { + at := time.Date(2026, 8, 15, 10, 30, 0, 123456789, time.UTC) + profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{ + Name: "ООО Пример", Description: "Описание", Sphere: "Платежи", + Contacts: domain.OrganizationContactsInput{ + Website: "https://example.com", Email: "careers@example.com", Phone: "+74951234567", Telegram: "@example", + }, + Representatives: []domain.OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Директор"}}, + }) + if err != nil { + t.Fatalf("NewOrganizationProfile() error = %v", err) + } + company, err := domain.NewOrganization(profile, at) + if err != nil { + t.Fatalf("NewOrganization() error = %v", err) + } + owner, err := domain.NewOwnerMembership(company.ID(), uuid.New(), at) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + result := outbound.OrganizationCreationResult{Organization: company, Owner: owner} + snapshot := creationSnapshotFromDomain(result) + encoded, err := json.Marshal(snapshot) + if err != nil { + t.Fatalf("Marshal(snapshot) error = %v", err) + } + var decoded organizationCreationSnapshot + if err := json.Unmarshal(encoded, &decoded); err != nil { + t.Fatalf("Unmarshal(snapshot) error = %v", err) + } + got, err := decoded.domainResult() + if err != nil { + t.Fatalf("domainResult() error = %v", err) + } + if got.Organization.ID() != company.ID() || got.Organization.Version() != company.Version() || + !got.Organization.Profile().Equal(company.Profile()) || + got.Organization.Verification().Level() != domain.OrganizationVerificationE0 || + got.Organization.Verification().Basis() != domain.OrganizationBasisConfirmedEmail || + !got.Organization.CreatedAt().Equal(at) || got.Owner.ID() != owner.ID() || got.Owner.UserID() != owner.UserID() || + got.Owner.OrganizationID() != company.ID() || got.Owner.Role() != domain.OrganizationRoleOwner || !got.Owner.GrantsAccess() { + t.Fatal("creation snapshot did not preserve the original organization and owner result") + } + if len(encoded) > maxOrganizationCreationSnapshotBytes { + t.Fatalf("snapshot size = %d, want at most %d bytes", len(encoded), maxOrganizationCreationSnapshotBytes) + } +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go index 2faf301..f733510 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go @@ -11,6 +11,82 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const createAccountDeletionRequest = `-- name: CreateAccountDeletionRequest :one +INSERT INTO account_deletion_requests ( + id, + subject_id, + status, + requested_at +) VALUES ( + $1, + $2, + 'requested', + $3 +) +ON CONFLICT (subject_id) +WHERE subject_id IS NOT NULL AND status IN ('requested', 'processing') +DO NOTHING +RETURNING id, subject_id, status, requested_at +` + +type CreateAccountDeletionRequestParams struct { + ID pgtype.UUID + SubjectID pgtype.UUID + RequestedAt pgtype.Timestamptz +} + +type CreateAccountDeletionRequestRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Status string + RequestedAt pgtype.Timestamptz +} + +// Creates one durable deletion request per subject until a worker completes it. +// The caller appends the matching outbox intent in the same transaction only +// when this insert returns a row. +func (q *Queries) CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error) { + row := q.db.QueryRow(ctx, createAccountDeletionRequest, arg.ID, arg.SubjectID, arg.RequestedAt) + var i CreateAccountDeletionRequestRow + err := row.Scan( + &i.ID, + &i.SubjectID, + &i.Status, + &i.RequestedAt, + ) + return i, err +} + +const getActiveAccountDeletionRequest = `-- name: GetActiveAccountDeletionRequest :one +SELECT id, subject_id, status, requested_at +FROM account_deletion_requests +WHERE subject_id = $1 + AND status IN ('requested', 'processing') +ORDER BY requested_at, id +LIMIT 1 +` + +type GetActiveAccountDeletionRequestRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Status string + RequestedAt pgtype.Timestamptz +} + +// Reads the durable active deletion request when an earlier request already +// exists. A completed request does not suppress a later explicit request. +func (q *Queries) GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error) { + row := q.db.QueryRow(ctx, getActiveAccountDeletionRequest, subjectID) + var i GetActiveAccountDeletionRequestRow + err := row.Scan( + &i.ID, + &i.SubjectID, + &i.Status, + &i.RequestedAt, + ) + return i, err +} + const getConsentText = `-- name: GetConsentText :one SELECT purpose, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index fbe633a..ffcef50 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -8,6 +8,14 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +type AccountDeletionRequest struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Status string + RequestedAt pgtype.Timestamptz + CompletedAt pgtype.Timestamptz +} + type AssessmentCategoryOpening struct { ID pgtype.UUID Category string @@ -315,6 +323,11 @@ type Organization struct { UpdatedAt pgtype.Timestamptz } +type OrganizationCreationResult struct { + ScopeHash []byte + Snapshot []byte +} + type OrganizationRepresentative struct { OrganizationID pgtype.UUID Ordinal int16 diff --git a/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go index be231d7..394a300 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go @@ -57,6 +57,21 @@ func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (M return i, err } +const getOrganizationCreationResult = `-- name: GetOrganizationCreationResult :one +SELECT snapshot +FROM organization_creation_results +WHERE scope_hash = $1 +` + +// Reads only the historical result. It intentionally does not join the live +// organization or membership, whose profile and state may have since changed. +func (q *Queries) GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error) { + row := q.db.QueryRow(ctx, getOrganizationCreationResult, scopeHash) + var snapshot []byte + err := row.Scan(&snapshot) + return snapshot, err +} + const getOrganizationForMember = `-- name: GetOrganizationForMember :one SELECT organization.id, @@ -390,6 +405,27 @@ func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganiza return items, nil } +const saveOrganizationCreationResult = `-- name: SaveOrganizationCreationResult :exec +INSERT INTO organization_creation_results (scope_hash, snapshot) +VALUES ($1, $2) +ON CONFLICT (scope_hash) DO UPDATE +SET snapshot = excluded.snapshot +` + +type SaveOrganizationCreationResultParams struct { + ScopeHash []byte + Snapshot []byte +} + +// Stores the immutable domain snapshot of a successful create command. The +// generic idempotency row and this result are committed with the organization +// and owner membership. A reused expired scope replaces the snapshot in the +// same transaction as the new organization. +func (q *Queries) SaveOrganizationCreationResult(ctx context.Context, arg SaveOrganizationCreationResultParams) error { + _, err := q.db.Exec(ctx, saveOrganizationCreationResult, arg.ScopeHash, arg.Snapshot) + return err +} + const updateOrganizationProfile = `-- name: UpdateOrganizationProfile :one WITH target AS ( SELECT id FROM organizations diff --git a/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go index b23a813..b83e5d0 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go @@ -421,6 +421,38 @@ func (q *Queries) ListCandidatePrivacyEvents(ctx context.Context, arg ListCandid return items, nil } +const lockCandidatePublicationForConsentRevocation = `-- name: LockCandidatePublicationForConsentRevocation :one +SELECT greatest(candidate_publications.published_at, consent_records.revoked_at)::timestamptz AS closed_at +FROM candidate_publications +INNER JOIN consent_records + ON consent_records.id = candidate_publications.consent_record_id +WHERE + candidate_publications.user_id = $1 + AND candidate_publications.state = 'published' + AND consent_records.id = ANY($2::uuid []) + AND consent_records.subject_id = candidate_publications.user_id + AND consent_records.purpose = 'c2' + AND consent_records.revoked_at IS NOT NULL +FOR UPDATE OF candidate_publications +` + +type LockCandidatePublicationForConsentRevocationParams struct { + UserID pgtype.UUID + ConsentRecordIds []pgtype.UUID +} + +// Locks the candidate's published row only when it refers to a C2 record +// revoked by this transaction. The setting remains linked to that immutable +// record; ReadCandidatePublication computes the effective closed state and +// keeps the consent-revoked reason after later grants. The returned time is +// the effective close time used by the privacy history event. +func (q *Queries) LockCandidatePublicationForConsentRevocation(ctx context.Context, arg LockCandidatePublicationForConsentRevocationParams) (pgtype.Timestamptz, error) { + row := q.db.QueryRow(ctx, lockCandidatePublicationForConsentRevocation, arg.UserID, arg.ConsentRecordIds) + var closed_at pgtype.Timestamptz + err := row.Scan(&closed_at) + return closed_at, err +} + const lockCurrentC2Record = `-- name: LockCurrentC2Record :one SELECT id FROM consent_records diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 983c82f..d38aa44 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -107,6 +107,10 @@ type Querier interface { // Counts the families of a category that have at least one published // version, however many versions each has. CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error) + // Creates one durable deletion request per subject until a worker completes it. + // The caller appends the matching outbox intent in the same transaction only + // when this insert returns a row. + CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error) // Lifts one hiding. No row returns when the organization was not hidden, so // the caller writes the history event only for a real deletion and answers // 204 either way. @@ -156,6 +160,9 @@ type Querier interface { // made at or after reserved_since. A retry of the delivery inside the // provider's idempotency window reuses it instead of counting again. FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error) + // Reads the durable active deletion request when an earlier request already + // exists. A completed request does not suppress a later explicit request. + GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error) GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error) GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error) @@ -207,6 +214,9 @@ type Querier interface { GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error) // Reads the membership of one account in one organization, in any state. GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) + // Reads only the historical result. It intentionally does not join the live + // organization or membership, whose profile and state may have since changed. + GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error) // Reads an organization together with the membership of one account in it // and its representatives in list order, as one statement, so the profile and // the list come from one snapshot. Only an active membership matches, so an @@ -377,6 +387,12 @@ type Querier interface { // published or open the category, until the transaction ends. The key is // namespaced, so it cannot collide with another use of advisory locks. LockAssessmentCategory(ctx context.Context, category string) error + // Locks the candidate's published row only when it refers to a C2 record + // revoked by this transaction. The setting remains linked to that immutable + // record; ReadCandidatePublication computes the effective closed state and + // keeps the consent-revoked reason after later grants. The returned time is + // the effective close time used by the privacy history event. + LockCandidatePublicationForConsentRevocation(ctx context.Context, arg LockCandidatePublicationForConsentRevocationParams) (pgtype.Timestamptz, error) // Locks the delivery row of the lease holder until the transaction ends, so // every path that settles a send takes the delivery lock before the quota // rows, the same order as the claim. No row means that owner no longer holds @@ -542,6 +558,11 @@ type Querier interface { RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error) RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error) RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error) + // Stores the immutable domain snapshot of a successful create command. The + // generic idempotency row and this result are committed with the organization + // and owner membership. A reused expired scope replaces the snapshot in the + // same transaction as the new organization. + SaveOrganizationCreationResult(ctx context.Context, arg SaveOrganizationCreationResultParams) error // Bounds a consumer transaction on the server, local to the transaction. // statement_timeout stops a slow statement; idle_in_transaction_session_timeout // ends the session of a process that froze or lost the network inside the diff --git a/backend/internal/bootstrap/consent.go b/backend/internal/bootstrap/consent.go new file mode 100644 index 0000000..945f05a --- /dev/null +++ b/backend/internal/bootstrap/consent.go @@ -0,0 +1,27 @@ +package bootstrap + +import ( + "context" + "time" + + "lincodex/backend/config" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/usecase/consent" +) + +const consentPoolMaxConns = 4 + +func newConsentHandler(ctx context.Context, settings config.Config) (*v1.ConsentHandler, func(), error) { + if settings.DatabaseURL == "" { + return nil, func() {}, nil + } + pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, consentPoolMaxConns) + if err != nil { + return nil, nil, err + } + store := postgres.NewConsentStore(pool) + reader := consent.NewQueryService(store, time.Now) + commands := consent.NewService(postgres.NewTransactor(pool), time.Now) + return v1.NewConsentHandler(reader, commands), pool.Close, nil +} diff --git a/backend/internal/bootstrap/identity.go b/backend/internal/bootstrap/identity.go index 6800cea..cc4dff0 100644 --- a/backend/internal/bootstrap/identity.go +++ b/backend/internal/bootstrap/identity.go @@ -31,8 +31,18 @@ func newTrustedProxies(settings config.Config) []netip.Prefix { return settings. // newAPIHandler composes the handler of the public API from the business // areas that are built. An area without a handler answers 501. -func newAPIHandler(health *v1.HealthHandler, problems *problem.Responder, identityHandler *v1.IdentityHandler) *v1.Handler { - return v1.NewHandler(health, problems, v1.WithIdentity(identityHandler)) +func newAPIHandler( + health *v1.HealthHandler, + problems *problem.Responder, + identityHandler *v1.IdentityHandler, + consentHandler *v1.ConsentHandler, + organizationHandler *v1.OrganizationHandler, +) *v1.Handler { + return v1.NewHandler(health, problems, + v1.WithIdentity(identityHandler), + v1.WithConsent(consentHandler), + v1.WithOrganization(organizationHandler), + ) } // newIdentityHandler builds the registration and session operations and the @@ -45,15 +55,12 @@ func newIdentityHandler( logger *slog.Logger, cache *redisadapter.Cache, metrics *prometheus.Metrics, + keyring *identity.Keyring, ) (*v1.IdentityHandler, func(), error) { if settings.DatabaseURL == "" { logger.Warn("identity operations are not served because DATABASE_URL is not set") return nil, func() {}, nil } - keyring, err := newIdentityKeyring(settings, logger) - if err != nil { - return nil, nil, err - } renderer, err := mailtemplate.NewRenderer(settings.AppPublicURL) if err != nil { return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create mail renderer: %w", err) @@ -146,6 +153,9 @@ func newIdentityHandler( // counters no longer match after restart, and CSRF tokens differ between // restarts and instances. func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity.Keyring, error) { + if settings.DatabaseURL == "" { + return nil, nil + } secret := []byte(settings.IdentityKeySecret) if len(secret) == 0 { secret = make([]byte, identity.MinKeySecretBytes) diff --git a/backend/internal/bootstrap/organization.go b/backend/internal/bootstrap/organization.go new file mode 100644 index 0000000..5fd2ebe --- /dev/null +++ b/backend/internal/bootstrap/organization.go @@ -0,0 +1,48 @@ +package bootstrap + +import ( + "context" + "fmt" + "log/slog" + "time" + + "lincodex/backend/config" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/organization" +) + +const organizationPoolMaxConns = 8 + +// newOrganizationHandler builds company reads and writes from the PostgreSQL +// transaction boundary. Without DATABASE_URL the composite handler keeps the +// operations on its 501 fallback. +func newOrganizationHandler( + ctx context.Context, + settings config.Config, + logger *slog.Logger, + keyring *identity.Keyring, +) (*v1.OrganizationHandler, func(), error) { + if settings.DatabaseURL == "" { + logger.Warn("organization operations are not served because DATABASE_URL is not set") + return nil, func() {}, nil + } + if keyring == nil { + return nil, nil, fmt.Errorf("bootstrap.newOrganizationHandler - identity keyring must be set") + } + pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, organizationPoolMaxConns) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newOrganizationHandler - create pool: %w", err) + } + service, err := organization.NewService(organization.Dependencies{ + Transactor: postgres.NewTransactor(pool), + Keyring: keyring, + Clock: time.Now, + }) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newOrganizationHandler - create service: %w", err) + } + return v1.NewOrganizationHandler(service, settings.AppPublicURL), pool.Close, nil +} diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 0c6ae67..6025c0e 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -47,6 +47,9 @@ func initialize( newAPIHandler, newTrustedProxies, newIdentityHandler, + newIdentityKeyring, + newConsentHandler, + newOrganizationHandler, newSessionSecurity, httpadapter.NewRouter, newOutboxRelay, diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index bb12d83..98e7a4b 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -46,17 +46,21 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, healthHandler := newHealthHandler(readiness, config2) responder := problem.NewResponder(logger) metrics := prometheus.New() - identityHandler, cleanup4, err := newIdentityHandler(ctx, config2, logger, cache, metrics) + keyring, err := newIdentityKeyring(config2, logger) if err != nil { cleanup3() cleanup2() cleanup() return nil, nil, err } - handler := newAPIHandler(healthHandler, responder, identityHandler) - sessionSecurity := newSessionSecurity(identityHandler) - v := newTrustedProxies(config2) - httpHandler, err := httpadapter.NewRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v) + identityHandler, cleanup4, err := newIdentityHandler(ctx, config2, logger, cache, metrics, keyring) + if err != nil { + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + consentHandler, cleanup5, err := newConsentHandler(ctx, config2) if err != nil { cleanup4() cleanup3() @@ -64,15 +68,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - relay, cleanup5, err := newOutboxRelay(ctx, config2, logger, metrics) - if err != nil { - cleanup4() - cleanup3() - cleanup2() - cleanup() - return nil, nil, err - } - bootstrapEventConsumers, cleanup6, err := newEventConsumers(ctx, config2, logger, metrics) + organizationHandler, cleanup6, err := newOrganizationHandler(ctx, config2, logger, keyring) if err != nil { cleanup5() cleanup4() @@ -81,7 +77,10 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - worker, cleanup7, err := newJobWorker(ctx, config2, logger, metrics) + handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, organizationHandler) + sessionSecurity := newSessionSecurity(identityHandler) + v := newTrustedProxies(config2) + httpHandler, err := httpadapter.NewRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v) if err != nil { cleanup6() cleanup5() @@ -91,7 +90,17 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - mailsenderWorker, cleanup8, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) + relay, cleanup7, err := newOutboxRelay(ctx, config2, logger, metrics) + if err != nil { + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + bootstrapEventConsumers, cleanup8, err := newEventConsumers(ctx, config2, logger, metrics) if err != nil { cleanup7() cleanup6() @@ -102,7 +111,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - sampler, cleanup9, err := newDeliveryMetrics(ctx, config2, logger, metrics) + worker, cleanup9, err := newJobWorker(ctx, config2, logger, metrics) if err != nil { cleanup8() cleanup7() @@ -114,8 +123,37 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } + mailsenderWorker, cleanup10, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) + if err != nil { + cleanup9() + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + sampler, cleanup11, err := newDeliveryMetrics(ctx, config2, logger, metrics) + if err != nil { + cleanup10() + cleanup9() + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler) return application, func() { + cleanup11() + cleanup10() cleanup9() cleanup8() cleanup7() diff --git a/backend/internal/domain/account_deletion.go b/backend/internal/domain/account_deletion.go new file mode 100644 index 0000000..13cd133 --- /dev/null +++ b/backend/internal/domain/account_deletion.go @@ -0,0 +1,55 @@ +package domain + +import ( + "fmt" + "time" + + "github.com/google/uuid" +) + +type AccountDeletionRequestStatus string + +const ( + AccountDeletionRequestStatusRequested AccountDeletionRequestStatus = "requested" + AccountDeletionRequestStatusProcessing AccountDeletionRequestStatus = "processing" +) + +type AccountDeletionRequest struct { + id uuid.UUID + subjectID uuid.UUID + status AccountDeletionRequestStatus + requestedAt time.Time +} + +func NewAccountDeletionRequest(subjectID uuid.UUID, requestedAt time.Time) (AccountDeletionRequest, error) { + if subjectID == uuid.Nil || requestedAt.IsZero() { + return AccountDeletionRequest{}, fmt.Errorf("domain.NewAccountDeletionRequest - subject and request time must be set: %w", ErrInvalidConsent) + } + id, err := uuid.NewV7() + if err != nil { + return AccountDeletionRequest{}, fmt.Errorf("domain.NewAccountDeletionRequest - generate ID: %w", err) + } + return AccountDeletionRequest{ + id: id, subjectID: subjectID, status: AccountDeletionRequestStatusRequested, requestedAt: requestedAt, + }, nil +} + +func RestoreAccountDeletionRequest(id, subjectID uuid.UUID, status string, requestedAt time.Time) (AccountDeletionRequest, error) { + if id == uuid.Nil || subjectID == uuid.Nil || requestedAt.IsZero() || + (status != string(AccountDeletionRequestStatusRequested) && status != string(AccountDeletionRequestStatusProcessing)) { + return AccountDeletionRequest{}, fmt.Errorf("domain.RestoreAccountDeletionRequest - stored request is invalid: %w", ErrInvalidConsent) + } + return AccountDeletionRequest{ + id: id, subjectID: subjectID, status: AccountDeletionRequestStatus(status), requestedAt: requestedAt, + }, nil +} + +func (request AccountDeletionRequest) ID() uuid.UUID { return request.id } + +func (request AccountDeletionRequest) SubjectID() uuid.UUID { return request.subjectID } + +func (request AccountDeletionRequest) Status() AccountDeletionRequestStatus { return request.status } + +func (request AccountDeletionRequest) RequestedAt() time.Time { return request.requestedAt } + +func (request AccountDeletionRequest) IsZero() bool { return request.id == uuid.Nil } diff --git a/backend/internal/domain/visibility.go b/backend/internal/domain/visibility.go index 7526303..4e64039 100644 --- a/backend/internal/domain/visibility.go +++ b/backend/internal/domain/visibility.go @@ -692,6 +692,17 @@ func NewPublicationEvent(change PublicationChange, at time.Time) (PrivacyEvent, return completeEvent(location, event) } +// NewConsentRevokedPublicationEvent records the closure caused by revoking +// C2. The event deliberately carries neither published fields nor a consent +// identifier; the consent ledger and publication table remain the sources of +// the detailed history. +func NewConsentRevokedPublicationEvent(userID uuid.UUID, at time.Time) (PrivacyEvent, error) { + const location = "domain.NewConsentRevokedPublicationEvent" + return completeEvent(location, PrivacyEvent{ + userID: userID, kind: PrivacyEventPublicationClosed, occurredAt: at, + }) +} + // NewSearchStatusEvent records a change of the search status. func NewSearchStatusEvent(change SearchStatusChange, at time.Time) (PrivacyEvent, error) { const location = "domain.NewSearchStatusEvent" diff --git a/backend/internal/port/outbound/consents.go b/backend/internal/port/outbound/consents.go index 66c914e..ba0832e 100644 --- a/backend/internal/port/outbound/consents.go +++ b/backend/internal/port/outbound/consents.go @@ -49,6 +49,36 @@ type ConsentRepositories interface { ConsentLedger() ConsentLedger } +// AccountDeletionRequests stores the durable request created when a subject +// revokes C1. The active request is independent of later consent grants. +type AccountDeletionRequests interface { + // CreateOrGet returns the current requested record when one exists, or + // stores request as the subject's active deletion request. + CreateOrGet(ctx context.Context, request domain.AccountDeletionRequest) (record domain.AccountDeletionRequest, created bool, err error) +} + +// ConsentRevocationEffects applies every currently available local privacy +// change and records downstream revocation intents in the same transaction as +// the ledger stamps. Future C2 and C4 grant adapters must bind each downstream +// grant to its source consent record ID and synchronously close grants for +// revoked record IDs before returning; a later consent record may create a +// new grant, but must never reactivate an older record's grant. Future C5 +// readers and importers must check the current consent ledger before reading +// or synchronizing data and fail closed on a missing grant or ledger error. +// An outbox event communicates a committed change; it is never an +// authorization check and cannot make a revoked grant current again. This +// release has no external FSP or downstream contact-grant adapter, so those +// external effects are not claimed as complete. +type ConsentRevocationEffects interface { + // Apply synchronously closes and records a C2 publication when present, + // then appends one bounded durable outbox intent per affected consent record + // with its stored scope. It must not truncate or omit affected records. A + // future local C2/C4 grant adapter must implement record-bound closure in + // this same UnitOfWork before the outbox intent is appended. An empty record + // set is not a valid call. + Apply(ctx context.Context, revocation domain.ConsentRevocation, records []domain.ConsentRecord) error +} + // ConsentTextRepository reads the immutable published consent texts. It has // no write method: texts are published by migrations. type ConsentTextRepository interface { diff --git a/backend/internal/port/outbound/organizations.go b/backend/internal/port/outbound/organizations.go index 211b5c9..f429775 100644 --- a/backend/internal/port/outbound/organizations.go +++ b/backend/internal/port/outbound/organizations.go @@ -33,6 +33,10 @@ var ( // ErrMembershipNotFound reports that the account has no membership in the // organization, in any state. ErrMembershipNotFound = errors.New("membership not found") + + // ErrOrganizationCreationResultNotFound reports a missing immutable result + // snapshot for a live organization creation idempotency record. + ErrOrganizationCreationResultNotFound = errors.New("organization creation result not found") ) // MaxOrganizationPageSize matches the largest page of the contract. @@ -65,6 +69,16 @@ type OrganizationRepository interface { // ErrUserNotFound, and the caller's transaction is aborted. CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error + // SaveCreationResult stores the immutable domain snapshot returned by the + // original create command. The scope is the HMAC key of a live generic + // idempotency record. The snapshot is bounded and expires with that record; + // it does not follow later profile edits or membership changes. + SaveCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result OrganizationCreationResult) error + + // GetCreationResult returns the original snapshot for a live idempotency + // scope. It never reads the current organization or membership rows. + GetCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (OrganizationCreationResult, error) + // GetForMember returns the organization with its representatives and the // active membership of the account in it, read from one snapshot in one // statement, so the profile and the list never come from two states. It @@ -100,6 +114,14 @@ type OrganizationRepository interface { UpdateProfile(ctx context.Context, actorID uuid.UUID, organization domain.Organization) (domain.Organization, error) } +// OrganizationCreationResult is the original business result of creating an +// organization. Keeping the domain values lets storage replay the response +// without depending on generated HTTP types or a later profile state. +type OrganizationCreationResult struct { + Organization domain.Organization + Owner domain.Membership +} + // MembershipRepository stores memberships. A membership is unique per account // and organization. type MembershipRepository interface { diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index 5bdee09..11fc6c3 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -50,6 +50,8 @@ type Transactor interface { type UnitOfWork interface { IdentityRepositories ConsentRepositories + AccountDeletionRequests() AccountDeletionRequests + ConsentRevocationEffects() ConsentRevocationEffects OrganizationRepositories AssessmentBankRepositories Policies() PolicyRepository diff --git a/backend/internal/usecase/consent/query.go b/backend/internal/usecase/consent/query.go new file mode 100644 index 0000000..0d3661f --- /dev/null +++ b/backend/internal/usecase/consent/query.go @@ -0,0 +1,90 @@ +package consent + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// QueryService reads published consent texts and the current account's ledger. +// The repository is a PostgreSQL adapter outside a transaction; history reads +// always receive the subject ID selected by the authenticated HTTP boundary. +type QueryService struct { + repositories outbound.ConsentRepositories + clock func() time.Time +} + +func NewQueryService(repositories outbound.ConsentRepositories, clock func() time.Time) *QueryService { + if repositories == nil { + panic("consent.NewQueryService - repositories must not be nil") + } + if clock == nil { + panic("consent.NewQueryService - clock must not be nil") + } + return &QueryService{repositories: repositories, clock: clock} +} + +func (service *QueryService) CurrentText(ctx context.Context, purpose domain.ConsentPurpose) (domain.ConsentText, error) { + if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil { + return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - validate purpose: %w", err) + } + if purpose.OrganizationScoped() { + return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - c4 text requires an organization snapshot: %w", ErrScopedConsentRequired) + } + text, err := service.repositories.ConsentTexts().Current(ctx, purpose, service.clock()) + if err != nil { + return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - read current text: %w", err) + } + return text, nil +} + +func (service *QueryService) List(ctx context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) { + if query.SubjectID == uuid.Nil { + return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - subject is required: %w", domain.ErrInvalidConsent) + } + if query.Limit < 1 || query.Limit > outbound.MaxConsentPageSize { + return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - limit is out of range: %w", domain.ErrInvalidConsent) + } + if query.State != "" { + if _, err := domain.ParseConsentState(string(query.State)); err != nil { + return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - validate state: %w", err) + } + } + if query.After != nil && (query.After.ID == uuid.Nil || query.After.GrantedAt.IsZero()) { + return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - cursor position is invalid: %w", domain.ErrInvalidConsent) + } + page, err := service.repositories.ConsentLedger().List(ctx, query) + if err != nil { + return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - read ledger: %w", err) + } + return page, nil +} + +// HasCurrentConsent is the fail-closed check used by consumers that must not +// proceed without a current grant. A missing record is a denial; a storage +// failure is returned so the caller must also deny instead of assuming consent. +func (service *QueryService) HasCurrentConsent(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (bool, error) { + if subjectID == uuid.Nil { + return false, fmt.Errorf("QueryService.HasCurrentConsent - subject is required: %w", domain.ErrInvalidConsent) + } + if purpose.OrganizationScoped() { + return false, fmt.Errorf("QueryService.HasCurrentConsent - c4 needs an organization scope: %w", domain.ErrInvalidConsent) + } + if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil { + return false, fmt.Errorf("QueryService.HasCurrentConsent - validate purpose: %w", err) + } + _, err := service.repositories.ConsentLedger().Current(ctx, subjectID, purpose) + if errors.Is(err, outbound.ErrConsentNotFound) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("QueryService.HasCurrentConsent - read current consent: %w", err) + } + return true, nil +} diff --git a/backend/internal/usecase/consent/query_test.go b/backend/internal/usecase/consent/query_test.go new file mode 100644 index 0000000..2d160a2 --- /dev/null +++ b/backend/internal/usecase/consent/query_test.go @@ -0,0 +1,126 @@ +package consent + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestQueryServiceReadsCurrentTextAndOwnLedgerPosition(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + body := "Current c2 text." + hash := domain.HashConsentText(body) + text, err := domain.RestoreConsentText(domain.StoredConsentText{ + Purpose: string(domain.ConsentPurposePublication), Version: "c2-current", Body: body, + Hash: hash[:], Kind: string(domain.ConsentTextKindDemo), PublishedAt: now.Add(-time.Hour), + }) + if err != nil { + t.Fatal(err) + } + accountID := uuid.New() + position := outbound.ConsentListPosition{GrantedAt: now.Add(-time.Minute), ID: uuid.New()} + ledger := &queryTestLedger{current: domain.ConsentRecord{}, page: outbound.ConsentPage{HasMore: true}} + reader := NewQueryService(&queryTestRepositories{ + texts: queryTestTexts{text: text}, + ledger: ledger, + }, func() time.Time { return now }) + + gotText, err := reader.CurrentText(context.Background(), domain.ConsentPurposePublication) + if err != nil || gotText.Version() != text.Version() || gotText.Body() != body { + t.Fatalf("CurrentText() = %#v, %v", gotText, err) + } + query := outbound.ConsentListQuery{ + SubjectID: accountID, State: domain.ConsentStateActive, + After: &position, Limit: 25, + } + page, err := reader.List(context.Background(), query) + if err != nil || !page.HasMore { + t.Fatalf("List() = %#v, %v", page, err) + } + if ledger.listQuery.SubjectID != accountID || ledger.listQuery.State != query.State || + ledger.listQuery.After == nil || *ledger.listQuery.After != position || ledger.listQuery.Limit != 25 { + t.Fatalf("List query = %#v", ledger.listQuery) + } +} + +func TestQueryServiceHasCurrentConsentFailsClosed(t *testing.T) { + accountID := uuid.New() + for _, test := range []struct { + name string + current error + want bool + wantErr bool + }{ + {name: "missing grant denies", current: outbound.ErrConsentNotFound}, + {name: "current grant allows", want: true}, + {name: "storage failure denies", current: errors.New("storage unavailable"), wantErr: true}, + } { + t.Run(test.name, func(t *testing.T) { + ledger := &queryTestLedger{currentErr: test.current} + reader := NewQueryService(&queryTestRepositories{ledger: ledger}, time.Now) + allowed, err := reader.HasCurrentConsent(context.Background(), accountID, domain.ConsentPurposeFSPImport) + if allowed != test.want || (err != nil) != test.wantErr { + t.Fatalf("HasCurrentConsent() = %v, %v", allowed, err) + } + }) + } +} + +func TestQueryServiceRejectsC4TextWithoutOrganizationSnapshot(t *testing.T) { + reader := NewQueryService(&queryTestRepositories{}, time.Now) + if _, err := reader.CurrentText(context.Background(), domain.ConsentPurposeContactDisclosure); !errors.Is(err, ErrScopedConsentRequired) { + t.Fatalf("CurrentText(c4) error = %v, want ErrScopedConsentRequired", err) + } +} + +type queryTestRepositories struct { + outbound.ConsentRepositories + + texts outbound.ConsentTextRepository + ledger outbound.ConsentLedger +} + +func (repositories *queryTestRepositories) ConsentTexts() outbound.ConsentTextRepository { + return repositories.texts +} + +func (repositories *queryTestRepositories) ConsentLedger() outbound.ConsentLedger { + return repositories.ledger +} + +type queryTestTexts struct { + outbound.ConsentTextRepository + + text domain.ConsentText +} + +func (texts queryTestTexts) Current(context.Context, domain.ConsentPurpose, time.Time) (domain.ConsentText, error) { + return texts.text, nil +} + +type queryTestLedger struct { + outbound.ConsentLedger + + currentErr error + current domain.ConsentRecord + listQuery outbound.ConsentListQuery + page outbound.ConsentPage +} + +func (ledger *queryTestLedger) Current(context.Context, uuid.UUID, domain.ConsentPurpose) (domain.ConsentRecord, error) { + if ledger.currentErr != nil { + return domain.ConsentRecord{}, ledger.currentErr + } + return ledger.current, nil +} + +func (ledger *queryTestLedger) List(_ context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) { + ledger.listQuery = query + return ledger.page, nil +} diff --git a/backend/internal/usecase/consent/revoke.go b/backend/internal/usecase/consent/revoke.go new file mode 100644 index 0000000..dc72839 --- /dev/null +++ b/backend/internal/usecase/consent/revoke.go @@ -0,0 +1,135 @@ +package consent + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +type SettingsRevocationInput struct { + SubjectID uuid.UUID + Purpose domain.ConsentPurpose + OrganizationID uuid.UUID +} + +type RevocationResult struct { + Records []domain.ConsentRecord +} + +func (service *Service) RevokeInSettingsInNewTransaction(ctx context.Context, input SettingsRevocationInput) (RevocationResult, error) { + const location = "Service.RevokeInSettingsInNewTransaction" + if input.Purpose == domain.ConsentPurposePersonalData { + return RevocationResult{}, fmt.Errorf("%s - c1 uses the account deletion request: %w", location, domain.ErrInvalidConsent) + } + if input.Purpose == domain.ConsentPurposeContactDisclosure && input.OrganizationID == uuid.Nil { + return RevocationResult{}, fmt.Errorf("%s - c4 organization is required: %w", location, domain.ErrInvalidConsent) + } + if input.Purpose != domain.ConsentPurposeContactDisclosure && input.OrganizationID != uuid.Nil { + return RevocationResult{}, fmt.Errorf("%s - organization scope is only valid for c4: %w", location, domain.ErrInvalidConsent) + } + if _, err := domain.ParseConsentPurpose(string(input.Purpose)); err != nil { + return RevocationResult{}, fmt.Errorf("%s - validate purpose: %w", location, err) + } + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: input.SubjectID, Purpose: input.Purpose, OrganizationID: input.OrganizationID, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: service.clock(), + }) + if err != nil { + return RevocationResult{}, fmt.Errorf("%s - create revocation: %w", location, err) + } + var result RevocationResult + err = service.inNewTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + records, err := unit.ConsentLedger().Revoke(ctx, revocation) + if err != nil { + return fmt.Errorf("%s - revoke consent ledger: %w", location, err) + } + if len(records) == 0 { + result = RevocationResult{} + return nil + } + if err := unit.ConsentRevocationEffects().Apply(ctx, revocation, records); err != nil { + return fmt.Errorf("%s - apply revocation effects: %w", location, err) + } + result = RevocationResult{Records: records} + return nil + }) + if err != nil { + return RevocationResult{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +func (service *Service) RequestAccountDeletionInNewTransaction(ctx context.Context, subjectID uuid.UUID) (domain.AccountDeletionRequest, error) { + const location = "Service.RequestAccountDeletionInNewTransaction" + request, err := domain.NewAccountDeletionRequest(subjectID, service.clock()) + if err != nil { + return domain.AccountDeletionRequest{}, fmt.Errorf("%s - create request: %w", location, err) + } + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: subjectID, Purpose: domain.ConsentPurposePersonalData, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: request.RequestedAt(), + }) + if err != nil { + return domain.AccountDeletionRequest{}, fmt.Errorf("%s - create c1 revocation: %w", location, err) + } + var result domain.AccountDeletionRequest + err = service.inNewTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + storedRequest, created, err := unit.AccountDeletionRequests().CreateOrGet(ctx, request) + if err != nil { + return fmt.Errorf("%s - store account deletion request: %w", location, err) + } + records, err := unit.ConsentLedger().Revoke(ctx, revocation) + if err != nil { + return fmt.Errorf("%s - revoke c1 consent: %w", location, err) + } + if len(records) > 0 { + if err := unit.ConsentRevocationEffects().Apply(ctx, revocation, records); err != nil { + return fmt.Errorf("%s - apply c1 revocation effects: %w", location, err) + } + } + if created { + if err := appendDeletionRequestedEvent(ctx, unit, storedRequest); err != nil { + return fmt.Errorf("%s - append deletion request event: %w", location, err) + } + } + result = storedRequest + return nil + }) + if err != nil { + return domain.AccountDeletionRequest{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +type accountDeletionRequestedPayload struct { + RequestID uuid.UUID `json:"request_id"` + SubjectID uuid.UUID `json:"subject_id"` + RequestedAt time.Time `json:"requested_at"` +} + +func appendDeletionRequestedEvent(ctx context.Context, unit outbound.UnitOfWork, request domain.AccountDeletionRequest) error { + const location = "appendDeletionRequestedEvent" + body, err := json.Marshal(accountDeletionRequestedPayload{ + RequestID: request.ID(), SubjectID: request.SubjectID(), RequestedAt: request.RequestedAt(), + }) + if err != nil { + return fmt.Errorf("%s - marshal payload: %w", location, err) + } + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: "privacy.account_deletion_requested", SchemaVersion: 1, + AggregateType: "account_deletion_request", AggregateID: request.ID(), AggregateVersion: 1, Payload: body, + }) + if err != nil { + return fmt.Errorf("%s - build event: %w", location, err) + } + if err := unit.Outbox().Append(ctx, event); err != nil { + return fmt.Errorf("%s - append event: %w", location, err) + } + return nil +} diff --git a/backend/internal/usecase/consent/revoke_test.go b/backend/internal/usecase/consent/revoke_test.go new file mode 100644 index 0000000..6074009 --- /dev/null +++ b/backend/internal/usecase/consent/revoke_test.go @@ -0,0 +1,501 @@ +package consent + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestSettingsRevocationAppliesEffectsOnce(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + subject := uuid.New() + ledger := &revocationTestLedger{records: []domain.ConsentRecord{ + revocationTestRecord(t, subject, domain.ConsentPurposePublication, uuid.Nil, now.Add(-time.Hour)), + }} + harness := newRevocationTestService(now, ledger) + input := SettingsRevocationInput{SubjectID: subject, Purpose: domain.ConsentPurposePublication} + + first, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), input) + if err != nil || len(first.Records) != 1 || first.Records[0].State() != domain.ConsentStateRevoked { + t.Fatalf("first revoke = %#v, %v; want one revoked record", first, err) + } + if len(harness.effects.calls) != 1 || harness.effects.calls[0].SubjectID() != subject { + t.Fatalf("revocation effects = %v; want one effect for the caller", harness.effects.calls) + } + + second, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), input) + if err != nil || len(second.Records) != 0 { + t.Fatalf("repeat revoke = %#v, %v; want no changed records", second, err) + } + if len(harness.effects.calls) != 1 { + t.Fatalf("repeat revoke applied effects again: %d calls", len(harness.effects.calls)) + } +} + +func TestDownstreamGrantClosureIsRecordBoundAcrossRegrant(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + for _, purpose := range []domain.ConsentPurpose{domain.ConsentPurposePublication, domain.ConsentPurposeContactDisclosure} { + t.Run(string(purpose), func(t *testing.T) { + subject := uuid.New() + organization := uuid.Nil + if purpose.OrganizationScoped() { + organization = uuid.New() + } + oldRecord := revocationTestRecord(t, subject, purpose, organization, now.Add(-time.Hour)) + ledger := &revocationTestLedger{records: []domain.ConsentRecord{oldRecord}} + harness := newRevocationTestService(now, ledger) + text := revocationTestConsentText(t, purpose, now.Add(-time.Minute)) + harness.transactor.unit.texts = revocationTestTexts{text: text} + harness.effects.activeDownstreamGrants = map[uuid.UUID]bool{oldRecord.ID(): true} + + _, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{ + SubjectID: subject, Purpose: purpose, OrganizationID: organization, + }) + if err != nil { + t.Fatalf("revoke %s: %v", purpose, err) + } + if harness.effects.activeDownstreamGrants[oldRecord.ID()] || !harness.effects.closedConsentRecords[oldRecord.ID()] { + t.Fatalf("revocation did not synchronously close downstream grant for consent record %s", oldRecord.ID()) + } + + var newRecord domain.ConsentRecord + if purpose == domain.ConsentPurposeContactDisclosure { + fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone) + if err != nil { + t.Fatal(err) + } + grant, err := harness.service.GrantContact(context.Background(), harness.transactor.unit, ContactGrantInput{ + SubjectID: subject, OrganizationID: organization, OrganizationName: "Acme Synthetic LLC", Fields: fields, + InvitationID: uuid.New(), InvitationTermsVersion: 1, TextVersion: text.Version(), + }) + if err != nil || !grant.Created { + t.Fatalf("grant new C4 invitation = %#v, %v", grant, err) + } + newRecord = grant.Record + } else { + grant, err := harness.service.GrantInSettingsInNewTransaction(context.Background(), SettingsGrantInput{ + SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), + }) + if err != nil || !grant.Created { + t.Fatalf("grant new C2 version = %#v, %v", grant, err) + } + newRecord = grant.Record + } + if newRecord.ID() == oldRecord.ID() || newRecord.State() != domain.ConsentStateActive { + t.Fatalf("new consent record = %s/%s, want a distinct active record", newRecord.ID(), newRecord.State()) + } + if harness.effects.closedConsentRecords[newRecord.ID()] || harness.effects.activeDownstreamGrants[oldRecord.ID()] { + t.Fatalf("new consent reopened the old downstream grant: old=%s new=%s", oldRecord.ID(), newRecord.ID()) + } + if !harness.effects.tryOpenForCurrentConsent(context.Background(), newRecord, ledger) || + !harness.effects.activeDownstreamGrants[newRecord.ID()] { + t.Fatal("test adapter did not open a downstream grant for the new current consent record") + } + if harness.effects.tryOpenForCurrentConsent(context.Background(), oldRecord, ledger) { + t.Fatal("test adapter reopened a grant bound to the revoked consent record") + } + }) + } +} + +func TestContactRevocationStaysWithinStoredOrganizationScope(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + subject := uuid.New() + organization := uuid.New() + otherOrganization := uuid.New() + ledger := &revocationTestLedger{records: []domain.ConsentRecord{ + revocationTestRecord(t, subject, domain.ConsentPurposeContactDisclosure, organization, now.Add(-time.Hour)), + revocationTestRecord(t, subject, domain.ConsentPurposeContactDisclosure, otherOrganization, now.Add(-30*time.Minute)), + }} + harness := newRevocationTestService(now, ledger) + + result, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{ + SubjectID: subject, Purpose: domain.ConsentPurposeContactDisclosure, OrganizationID: organization, + }) + if err != nil || len(result.Records) != 1 || result.Records[0].OrganizationID() != organization { + t.Fatalf("scoped revoke = %#v, %v; want only organization %s", result, err, organization) + } + if len(harness.effects.records) != 1 || harness.effects.records[0].OrganizationID() != organization || + harness.effects.records[0].Fields().Fields()[0] != domain.ContactFieldPhone { + t.Fatalf("revocation effect records = %v; want stored organization and field scope", harness.effects.records) + } + if ledger.records[1].State() != domain.ConsentStateActive { + t.Fatalf("record for another organization changed to %s", ledger.records[1].State()) + } +} + +func TestAccountDeletionRequestIsDurableAndIdempotent(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + subject := uuid.New() + ledger := &revocationTestLedger{records: []domain.ConsentRecord{ + revocationTestRecord(t, subject, domain.ConsentPurposePersonalData, uuid.Nil, now.Add(-time.Hour)), + }} + harness := newRevocationTestService(now, ledger) + + first, err := harness.service.RequestAccountDeletionInNewTransaction(context.Background(), subject) + if err != nil || first.IsZero() || first.SubjectID() != subject { + t.Fatalf("first deletion request = %#v, %v", first, err) + } + if len(harness.deletions.requests) != 1 || len(harness.outbox.events) != 1 || + harness.outbox.events[0].EventType() != "privacy.account_deletion_requested" { + t.Fatalf("request/outbox counts = %d/%d; want one durable request and one event", len(harness.deletions.requests), len(harness.outbox.events)) + } + if ledger.records[0].State() != domain.ConsentStateRevoked || len(harness.effects.calls) != 1 { + t.Fatalf("C1 revocation = %s, effects=%d; want revoked with one intent", ledger.records[0].State(), len(harness.effects.calls)) + } + + second, err := harness.service.RequestAccountDeletionInNewTransaction(context.Background(), subject) + if err != nil || second.ID() != first.ID() { + t.Fatalf("repeat deletion request = %#v, %v; want same durable request", second, err) + } + if len(harness.deletions.requests) != 1 || len(harness.outbox.events) != 1 || len(harness.effects.calls) != 1 { + t.Fatalf("repeat request duplicated effects: requests=%d events=%d revocations=%d", + len(harness.deletions.requests), len(harness.outbox.events), len(harness.effects.calls)) + } +} + +func TestRevocationFailureReturnsToTheTransactionBoundary(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + subject := uuid.New() + ledger := &revocationTestLedger{records: []domain.ConsentRecord{ + revocationTestRecord(t, subject, domain.ConsentPurposeFSPImport, uuid.Nil, now.Add(-time.Hour)), + }} + harness := newRevocationTestService(now, ledger) + harness.effects.err = errors.New("outbox unavailable") + + _, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{ + SubjectID: subject, Purpose: domain.ConsentPurposeFSPImport, + }) + if err == nil || !errors.Is(harness.transactor.lastErr, harness.effects.err) { + t.Fatalf("revoke error = %v, transaction error = %v; want the effect failure", err, harness.transactor.lastErr) + } +} + +type revocationTestHarness struct { + service *Service + transactor *revocationTestTransactor + deletions *revocationTestDeletions + effects *revocationTestEffects + outbox *revocationTestOutbox +} + +func newRevocationTestService(now time.Time, ledger *revocationTestLedger) *revocationTestHarness { + harness := &revocationTestHarness{ + deletions: &revocationTestDeletions{}, effects: &revocationTestEffects{}, outbox: &revocationTestOutbox{}, + } + unit := &revocationTestUnit{ + ledger: ledger, deletions: harness.deletions, effects: harness.effects, outbox: harness.outbox, + } + harness.transactor = &revocationTestTransactor{unit: unit} + harness.service = NewService(harness.transactor, func() time.Time { return now }) + return harness +} + +func revocationTestConsentText(t *testing.T, purpose domain.ConsentPurpose, publishedAt time.Time) domain.ConsentText { + t.Helper() + body := "I consent to this test purpose." + if purpose == domain.ConsentPurposeContactDisclosure { + body = "I consent to share selected contacts with {organization}." + } + hash := domain.HashConsentText(body) + text, err := domain.RestoreConsentText(domain.StoredConsentText{ + Purpose: string(purpose), Version: string(purpose) + "-2026-10-01", Body: body, + Hash: hash[:], Kind: string(domain.ConsentTextKindDemo), PublishedAt: publishedAt, + }) + if err != nil { + t.Fatalf("RestoreConsentText() error = %v", err) + } + return text +} + +func revocationTestRecord(t *testing.T, subject uuid.UUID, purpose domain.ConsentPurpose, organization uuid.UUID, grantedAt time.Time) domain.ConsentRecord { + t.Helper() + version := domain.ConsentTextVersion(string(purpose) + "-2026-10-01") + hash := domain.HashConsentText("consent text") + source := domain.ConsentSourceConsentSettings + if purpose == domain.ConsentPurposeContactDisclosure { + source = domain.ConsentSourceInvitationAcceptance + } + stored := domain.StoredConsentRecord{ + ID: uuid.New(), SubjectID: subject, Purpose: string(purpose), TextVersion: string(version), TextHash: hash[:], + Source: string(source), State: string(domain.ConsentStateActive), GrantedAt: grantedAt, + } + if purpose == domain.ConsentPurposeContactDisclosure { + fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone) + if err != nil { + t.Fatal(err) + } + stored.OrganizationID = organization + stored.OrganizationName = "Acme Synthetic LLC" + stored.FieldSet = contactFieldCodes(fields.Fields()) + stored.InvitationID = uuid.New() + stored.InvitationTermsVersion = 1 + } + record, err := domain.RestoreConsentRecord(stored) + if err != nil { + t.Fatalf("RestoreConsentRecord() error = %v", err) + } + return record +} + +type revocationTestLedger struct { + outbound.ConsentLedger + + records []domain.ConsentRecord +} + +type revocationTestTexts struct { + outbound.ConsentTextRepository + + text domain.ConsentText +} + +func (texts revocationTestTexts) Current(_ context.Context, purpose domain.ConsentPurpose, _ time.Time) (domain.ConsentText, error) { + if texts.text.IsZero() || texts.text.Purpose() != purpose { + return domain.ConsentText{}, outbound.ErrConsentTextNotFound + } + return texts.text, nil +} + +func (ledger *revocationTestLedger) Grant(_ context.Context, grant domain.ConsentGrant) (domain.ConsentRecord, bool, error) { + for _, existing := range ledger.records { + if existing.SubjectID() == grant.SubjectID() && existing.Purpose() == grant.Purpose() && + existing.TextVersion() == grant.TextVersion() && existing.State() != domain.ConsentStateRevoked { + return existing, false, nil + } + } + hash := grant.TextHash() + record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{ + ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(grant.Purpose()), + TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(grant.Source()), + RegistrationVersion: grant.RegistrationVersion(), State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(), + }) + if err != nil { + return domain.ConsentRecord{}, false, err + } + ledger.records = append(ledger.records, record) + return record, true, nil +} + +func (ledger *revocationTestLedger) GrantContact(_ context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) { + for _, existing := range ledger.records { + if existing.InvitationID() == grant.InvitationID() { + if existing.SubjectID() != grant.SubjectID() { + return domain.ConsentRecord{}, false, outbound.ErrConsentInvitationTaken + } + return existing, false, nil + } + } + hash := grant.TextHash() + record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{ + ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(domain.ConsentPurposeContactDisclosure), + TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance), + State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(), OrganizationID: grant.OrganizationID(), + OrganizationName: grant.OrganizationName(), FieldSet: contactFieldCodes(grant.Fields().Fields()), + InvitationID: grant.InvitationID(), InvitationTermsVersion: grant.InvitationTermsVersion(), + }) + if err != nil { + return domain.ConsentRecord{}, false, err + } + ledger.records = append(ledger.records, record) + return record, true, nil +} + +func (ledger *revocationTestLedger) Current(_ context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) { + var current domain.ConsentRecord + for _, record := range ledger.records { + if record.SubjectID() != subjectID || record.Purpose() != purpose || record.State() == domain.ConsentStateRevoked { + continue + } + if current.IsZero() || record.GrantedAt().After(current.GrantedAt()) || + (record.GrantedAt().Equal(current.GrantedAt()) && record.ID().String() > current.ID().String()) { + current = record + } + } + if current.IsZero() { + return domain.ConsentRecord{}, outbound.ErrConsentNotFound + } + return current, nil +} + +func (ledger *revocationTestLedger) CurrentContact(_ context.Context, subjectID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) { + var current []domain.ConsentRecord + for _, record := range ledger.records { + if record.SubjectID() == subjectID && record.Purpose() == domain.ConsentPurposeContactDisclosure && + record.OrganizationID() == organizationID && record.State() != domain.ConsentStateRevoked { + current = append(current, record) + } + } + return current, nil +} + +func (ledger *revocationTestLedger) Revoke(_ context.Context, revocation domain.ConsentRevocation) ([]domain.ConsentRecord, error) { + var revoked []domain.ConsentRecord + for index, record := range ledger.records { + if record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() || + record.State() == domain.ConsentStateRevoked || + (revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) { + continue + } + revokedAt := revocation.RevokedAt() + if revokedAt.Before(record.GrantedAt()) { + revokedAt = record.GrantedAt() + } + hash := record.TextHash() + var contactFields []string + if revocation.Purpose().OrganizationScoped() { + contactFields = contactFieldCodes(record.Fields().Fields()) + } + stored := domain.StoredConsentRecord{ + ID: record.ID(), SubjectID: record.SubjectID(), Purpose: string(record.Purpose()), + TextVersion: string(record.TextVersion()), TextHash: hash[:], Source: string(record.Source()), + RegistrationVersion: record.RegistrationVersion(), State: string(domain.ConsentStateRevoked), GrantedAt: record.GrantedAt(), + RevokedAt: &revokedAt, RevocationSource: string(revocation.Source()), OrganizationID: record.OrganizationID(), + OrganizationName: record.OrganizationName(), FieldSet: contactFields, InvitationID: record.InvitationID(), + InvitationTermsVersion: record.InvitationTermsVersion(), + } + updated, err := domain.RestoreConsentRecord(stored) + if err != nil { + return nil, err + } + ledger.records[index] = updated + revoked = append(revoked, updated) + } + return revoked, nil +} + +func contactFieldCodes(fields []domain.ContactField) []string { + codes := make([]string, 0, len(fields)) + for _, field := range fields { + codes = append(codes, string(field)) + } + return codes +} + +type revocationTestDeletions struct { + outbound.AccountDeletionRequests + + requests []domain.AccountDeletionRequest +} + +func (repository *revocationTestDeletions) CreateOrGet(_ context.Context, request domain.AccountDeletionRequest) (domain.AccountDeletionRequest, bool, error) { + for _, existing := range repository.requests { + if existing.SubjectID() == request.SubjectID() { + return existing, false, nil + } + } + repository.requests = append(repository.requests, request) + return request, true, nil +} + +type revocationTestEffects struct { + outbound.ConsentRevocationEffects + + calls []domain.ConsentRevocation + records []domain.ConsentRecord + activeDownstreamGrants map[uuid.UUID]bool + closedConsentRecords map[uuid.UUID]bool + err error +} + +func (effects *revocationTestEffects) Apply(_ context.Context, revocation domain.ConsentRevocation, records []domain.ConsentRecord) error { + if effects.err != nil { + return effects.err + } + effects.calls = append(effects.calls, revocation) + effects.records = append(effects.records, records...) + if effects.activeDownstreamGrants == nil { + effects.activeDownstreamGrants = make(map[uuid.UUID]bool) + } + if effects.closedConsentRecords == nil { + effects.closedConsentRecords = make(map[uuid.UUID]bool) + } + for _, record := range records { + effects.activeDownstreamGrants[record.ID()] = false + effects.closedConsentRecords[record.ID()] = true + } + return nil +} + +func (effects *revocationTestEffects) tryOpenForCurrentConsent( + ctx context.Context, + record domain.ConsentRecord, + ledger outbound.ConsentLedger, +) bool { + if record.IsZero() || effects.closedConsentRecords[record.ID()] { + return false + } + if record.Purpose().OrganizationScoped() { + current, err := ledger.CurrentContact(ctx, record.SubjectID(), record.OrganizationID()) + if err != nil { + return false + } + for _, candidate := range current { + if candidate.ID() == record.ID() { + effects.activeDownstreamGrants[record.ID()] = true + return true + } + } + return false + } + current, err := ledger.Current(ctx, record.SubjectID(), record.Purpose()) + if err != nil || current.ID() != record.ID() { + return false + } + if effects.activeDownstreamGrants == nil { + effects.activeDownstreamGrants = make(map[uuid.UUID]bool) + } + effects.activeDownstreamGrants[record.ID()] = true + return true +} + +type revocationTestOutbox struct { + outbound.OutboxWriter + + events []domain.DomainEvent +} + +func (outbox *revocationTestOutbox) Append(_ context.Context, events ...domain.DomainEvent) error { + outbox.events = append(outbox.events, events...) + return nil +} + +type revocationTestUnit struct { + outbound.UnitOfWork + + ledger *revocationTestLedger + texts outbound.ConsentTextRepository + deletions *revocationTestDeletions + effects *revocationTestEffects + outbox *revocationTestOutbox +} + +func (unit *revocationTestUnit) ConsentLedger() outbound.ConsentLedger { return unit.ledger } + +func (unit *revocationTestUnit) ConsentTexts() outbound.ConsentTextRepository { return unit.texts } + +func (unit *revocationTestUnit) AccountDeletionRequests() outbound.AccountDeletionRequests { + return unit.deletions +} + +func (unit *revocationTestUnit) ConsentRevocationEffects() outbound.ConsentRevocationEffects { + return unit.effects +} + +func (unit *revocationTestUnit) Outbox() outbound.OutboxWriter { return unit.outbox } + +type revocationTestTransactor struct { + unit *revocationTestUnit + lastErr error +} + +func (transactor *revocationTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error { + transactor.lastErr = work(ctx, transactor.unit) + return transactor.lastErr +} diff --git a/backend/internal/usecase/consent/service.go b/backend/internal/usecase/consent/service.go index 3e1e035..d9f9dc3 100644 --- a/backend/internal/usecase/consent/service.go +++ b/backend/internal/usecase/consent/service.go @@ -1,4 +1,4 @@ -// Package consent grants the consents C1-C5 of the consent ledger. +// Package consent manages consent grants, revocations, and the C1 deletion request. // // A grant is checked against the current published text of its purpose and // is recorded with the application clock; the client names the text version @@ -9,9 +9,13 @@ // product function; a subject without C3 simply has no C3 record, and // Current reports ErrConsentNotFound for it. // -// Revocation is not part of this package. Its downstream effects (closing -// publication and grants, the deletion request, the manual path, stopping -// the import) belong to consent revocation, which calls ConsentLedger().Revoke. +// C1 revocation creates a durable account-deletion request and never deletes +// the account synchronously. Other revocations update the ledger and apply +// transaction-bound effects. C2 closes local publication, C3 leaves the +// manual assessment path available, and C5 denies future import through the +// current-consent gate. Outbox events are notifications rather than access +// checks; external FSP deletion and downstream contact-grant adapters are not +// implemented here. package consent import ( diff --git a/backend/internal/usecase/organization/errors.go b/backend/internal/usecase/organization/errors.go new file mode 100644 index 0000000..1ce50ce --- /dev/null +++ b/backend/internal/usecase/organization/errors.go @@ -0,0 +1,22 @@ +package organization + +import "errors" + +var ( + // ErrForbidden reports an account that cannot create or manage an + // organization. + ErrForbidden = errors.New("organization operation forbidden") + + // ErrEmailNotVerified reports an account whose current email is not + // confirmed. + ErrEmailNotVerified = errors.New("organization requires a confirmed email") + + // ErrIdempotencyKeyReused reports a live key first used with another body. + ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request") + + // ErrInvalidIdempotencyKey reports a key outside the public contract bound. + ErrInvalidIdempotencyKey = errors.New("invalid idempotency key") + + // ErrInvalidCreateRequest reports an oversized canonical request body. + ErrInvalidCreateRequest = errors.New("invalid organization create request") +) diff --git a/backend/internal/usecase/organization/service.go b/backend/internal/usecase/organization/service.go new file mode 100644 index 0000000..6ec30c1 --- /dev/null +++ b/backend/internal/usecase/organization/service.go @@ -0,0 +1,376 @@ +// Package organization creates organizations and lets their owners edit the +// company profile. +package organization + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + createOperation = "organization.create" + createLocation = "organization.Service.Create" + maxIdempotencyKeySize = 255 + maxCanonicalBodySize = 1 << 20 + purgeExpiredBatch = 100 +) + +// Keyring computes scoped idempotency digests. identity.Keyring implements +// this interface so the feature uses the existing server secret and storage. +type Keyring interface { + IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte + Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte +} + +// Dependencies are the collaborators of Service. +type Dependencies struct { + Transactor outbound.Transactor + Keyring Keyring + Clock func() time.Time +} + +// Service applies organization commands. It stores no request state. +type Service struct { + transactor outbound.Transactor + keyring Keyring + clock func() time.Time +} + +// NewService fails at startup when a required dependency is missing. +func NewService(deps Dependencies) (*Service, error) { + if deps.Transactor == nil || deps.Keyring == nil || deps.Clock == nil { + return nil, errors.New("organization.NewService - every dependency must be set") + } + return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock}, nil +} + +// CreateCommand is the caller and profile content of one create request. +type CreateCommand struct { + ActorID uuid.UUID + IdempotencyKey string + CanonicalBody []byte + Profile domain.OrganizationProfileInput +} + +// CreateResult is the organization and owner membership created by a request. +// Replayed marks an identical request answered from the immutable result +// snapshot; it does not change the public status or body. +type CreateResult struct { + Organization domain.Organization + Owner domain.Membership + Replayed bool +} + +type createRequest struct { + command CreateCommand + fingerprint [outbound.IdempotencyDigestSize]byte + scope [outbound.IdempotencyDigestSize]byte + record outbound.IdempotencyRecord + now time.Time +} + +// Create creates a company and its active owner membership in one +// transaction. An identical key and body returns the original creation +// snapshot, even if the live profile has since changed. +func (service *Service) Create(ctx context.Context, command CreateCommand) (CreateResult, error) { + request, err := service.prepareCreateRequest(command) + if err != nil { + return CreateResult{}, err + } + var result CreateResult + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + created, err := service.createInTransaction(ctx, unit, request) + if err != nil { + return err + } + result = created + return nil + }) + if err != nil { + return CreateResult{}, fmt.Errorf("%s - run transaction: %w", createLocation, err) + } + return result, nil +} + +func (service *Service) prepareCreateRequest(command CreateCommand) (createRequest, error) { + switch { + case command.ActorID == uuid.Nil: + return createRequest{}, fmt.Errorf("%s - actor ID must be set: %w", createLocation, ErrForbidden) + case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize: + return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", createLocation, ErrInvalidIdempotencyKey) + } + canonical := command.CanonicalBody + if len(canonical) == 0 { + var err error + canonical, err = canonicalCreateBody(command.Profile) + if err != nil { + return createRequest{}, fmt.Errorf("%s - encode canonical profile", createLocation) + } + } + if len(canonical) > maxCanonicalBodySize { + return createRequest{}, fmt.Errorf("%s - request body exceeds its bound: %w", createLocation, ErrInvalidCreateRequest) + } + fingerprint := service.keyring.Fingerprint(canonical) + scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, command.ActorID.String()) + now := service.clock() + if now.IsZero() { + return createRequest{}, fmt.Errorf("%s - application time must be set", createLocation) + } + record := outbound.IdempotencyRecord{ + Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention), + } + return createRequest{command: command, fingerprint: fingerprint, scope: scope, record: record, now: now}, nil +} + +func (service *Service) createInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + request createRequest, +) (CreateResult, error) { + if err := requireEmployer(ctx, unit, request.command.ActorID, createLocation); err != nil { + return CreateResult{}, fmt.Errorf("%s - authorize creator: %w", createLocation, err) + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return CreateResult{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err) + } + if !created { + return replayCreation(ctx, unit, request, stored) + } + return service.createOrganization(ctx, unit, request) +} + +func replayCreation( + ctx context.Context, + unit outbound.UnitOfWork, + request createRequest, + stored outbound.IdempotencyRecord, +) (CreateResult, error) { + if stored.Fingerprint != request.fingerprint { + return CreateResult{}, ErrIdempotencyKeyReused + } + snapshot, err := unit.Organizations().GetCreationResult(ctx, request.scope) + if err != nil { + return CreateResult{}, fmt.Errorf("%s - read creation snapshot: %w", createLocation, err) + } + if !validCreationSnapshot(snapshot, request.command.ActorID) { + return CreateResult{}, fmt.Errorf("%s - stored creation snapshot does not match the actor: %w", createLocation, domain.ErrInvalidMembership) + } + return CreateResult{Organization: snapshot.Organization, Owner: snapshot.Owner, Replayed: true}, nil +} + +func validCreationSnapshot(snapshot outbound.OrganizationCreationResult, actorID uuid.UUID) bool { + if snapshot.Organization.IsZero() || snapshot.Owner.IsZero() { + return false + } + return snapshot.Owner.UserID() == actorID && + snapshot.Owner.OrganizationID() == snapshot.Organization.ID() && + snapshot.Owner.Role() == domain.OrganizationRoleOwner && snapshot.Owner.GrantsAccess() +} + +func (service *Service) createOrganization( + ctx context.Context, + unit outbound.UnitOfWork, + request createRequest, +) (CreateResult, error) { + profile, err := domain.NewOrganizationProfile(request.command.Profile) + if err != nil { + return CreateResult{}, fmt.Errorf("%s - validate profile: %w", createLocation, err) + } + company, err := domain.NewOrganization(profile, request.now) + if err != nil { + return CreateResult{}, fmt.Errorf("%s - build organization: %w", createLocation, err) + } + owner, err := domain.NewOwnerMembership(company.ID(), request.command.ActorID, request.now) + if err != nil { + return CreateResult{}, fmt.Errorf("%s - build owner membership: %w", createLocation, err) + } + if err := unit.Organizations().CreateWithOwner(ctx, company, owner); err != nil { + return CreateResult{}, fmt.Errorf("%s - store organization and owner: %w", createLocation, err) + } + creation := outbound.OrganizationCreationResult{Organization: company, Owner: owner} + if err := unit.Organizations().SaveCreationResult(ctx, request.scope, creation); err != nil { + return CreateResult{}, fmt.Errorf("%s - store creation snapshot: %w", createLocation, err) + } + if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { + return CreateResult{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err) + } + return CreateResult{Organization: company, Owner: owner}, nil +} + +func canonicalCreateBody(profile domain.OrganizationProfileInput) ([]byte, error) { + // An ordered array makes the fingerprint stable for non-HTTP callers. + return json.Marshal([]any{ + profile.Name, + profile.Description, + profile.Sphere, + profile.Contacts.Website, + profile.Contacts.Email, + profile.Contacts.Phone, + profile.Contacts.Telegram, + profile.Representatives, + }) +} + +// OptionalString distinguishes an absent field from a present value. An empty +// value clears nullable description and sphere fields. +type OptionalString struct { + Set bool + Value string +} + +// ProfilePatch is the set of editable fields present in an update request. +// Contacts and representatives replace their complete value when set. +type ProfilePatch struct { + Name OptionalString + Description OptionalString + Sphere OptionalString + Contacts *domain.OrganizationContactsInput + Representatives *[]domain.OrganizationRepresentativeInput +} + +// UpdateCommand describes a versioned profile edit. +type UpdateCommand struct { + ActorID uuid.UUID + OrganizationID uuid.UUID + ExpectedVersion int64 + Patch ProfilePatch +} + +// Update merges the patch over the current profile, preserves verification, +// and checks that the acting account is the active owner. +func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.Organization, error) { + const location = "organization.Service.Update" + if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil { + return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden) + } + if command.ExpectedVersion < 1 { + return domain.Organization{}, fmt.Errorf("%s - expected version must be positive: %w", location, domain.ErrInvalidOrganization) + } + var result domain.Organization + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireEmployer(ctx, unit, command.ActorID, location); err != nil { + return fmt.Errorf("%s - authorize editor: %w", location, err) + } + current, membership, err := unit.Organizations().GetForMember(ctx, command.OrganizationID, command.ActorID) + if err != nil { + return fmt.Errorf("%s - read organization for member: %w", location, err) + } + if !membership.CanManageOrganization() { + return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired) + } + profile, err := applyPatch(current.Profile(), command.Patch) + if err != nil { + if command.ExpectedVersion != current.Version() { + return fmt.Errorf("%s - expected version %d, current version %d: %w", location, + command.ExpectedVersion, current.Version(), outbound.ErrOrganizationVersionConflict) + } + return fmt.Errorf("%s - validate profile: %w", location, err) + } + if current.Profile().Equal(profile) { + result = current + return nil + } + if command.ExpectedVersion != current.Version() { + return fmt.Errorf("%s - expected version %d, current version %d: %w", location, + command.ExpectedVersion, current.Version(), outbound.ErrOrganizationVersionConflict) + } + updated, err := current.ApplyProfile(profile, service.clock()) + if err != nil { + return fmt.Errorf("%s - apply profile: %w", location, err) + } + result, err = unit.Organizations().UpdateProfile(ctx, command.ActorID, updated) + if err != nil { + return fmt.Errorf("%s - store profile: %w", location, err) + } + return nil + }) + if err != nil { + return domain.Organization{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +// Get reads an organization only for an active member of the employer +// account. The membership is checked in the same transaction as the account. +func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error) { + const location = "organization.Service.Get" + if actorID == uuid.Nil || organizationID == uuid.Nil { + return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden) + } + var result domain.Organization + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireEmployer(ctx, unit, actorID, location); err != nil { + return fmt.Errorf("%s - authorize reader: %w", location, err) + } + organization, membership, err := unit.Organizations().GetForMember(ctx, organizationID, actorID) + if err != nil { + return fmt.Errorf("%s - read organization for member: %w", location, err) + } + if !membership.GrantsAccess() { + return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound) + } + result = organization + return nil + }) + if err != nil { + return domain.Organization{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +func applyPatch(current domain.OrganizationProfile, patch ProfilePatch) (domain.OrganizationProfile, error) { + contacts := current.Contacts() + input := domain.OrganizationProfileInput{ + Name: current.Name(), Description: current.Description(), Sphere: current.Sphere(), + Contacts: domain.OrganizationContactsInput{ + Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(), + }, + } + for _, representative := range current.Representatives() { + input.Representatives = append(input.Representatives, domain.OrganizationRepresentativeInput{ + Name: representative.Name(), JobTitle: representative.JobTitle(), + }) + } + if patch.Name.Set { + input.Name = patch.Name.Value + } + if patch.Description.Set { + input.Description = patch.Description.Value + } + if patch.Sphere.Set { + input.Sphere = patch.Sphere.Value + } + if patch.Contacts != nil { + input.Contacts = *patch.Contacts + } + if patch.Representatives != nil { + input.Representatives = append([]domain.OrganizationRepresentativeInput(nil), (*patch.Representatives)...) + } + return domain.NewOrganizationProfile(input) +} + +func requireEmployer(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID, location string) error { + user, err := unit.Users().GetByID(ctx, actorID) + if err != nil { + if errors.Is(err, outbound.ErrUserNotFound) { + return ErrForbidden + } + return fmt.Errorf("%s - read account: %w", location, err) + } + if !user.EmailVerified() { + return ErrEmailNotVerified + } + if user.Scenario != domain.ScenarioEmployer { + return ErrForbidden + } + return nil +} diff --git a/backend/internal/usecase/organization/service_test.go b/backend/internal/usecase/organization/service_test.go new file mode 100644 index 0000000..94b63aa --- /dev/null +++ b/backend/internal/usecase/organization/service_test.go @@ -0,0 +1,628 @@ +package organization + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/identity" +) + +type organizationTestState struct { + users map[uuid.UUID]domain.User + organizations map[uuid.UUID]domain.Organization + memberships map[organizationTestMembershipKey]domain.Membership + idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord + results map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult +} + +type organizationTestMembershipKey struct { + organizationID uuid.UUID + userID uuid.UUID +} + +func newOrganizationTestState() organizationTestState { + return organizationTestState{ + users: map[uuid.UUID]domain.User{}, + organizations: map[uuid.UUID]domain.Organization{}, + memberships: map[organizationTestMembershipKey]domain.Membership{}, + idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{}, + results: map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult{}, + } +} + +func (state organizationTestState) clone() organizationTestState { + cloned := newOrganizationTestState() + for id, user := range state.users { + cloned.users[id] = user + } + for id, company := range state.organizations { + cloned.organizations[id] = company + } + for key, membership := range state.memberships { + cloned.memberships[key] = membership + } + for scope, record := range state.idempotency { + cloned.idempotency[scope] = record + } + for scope, result := range state.results { + cloned.results[scope] = result + } + return cloned +} + +type organizationTestTransactor struct { + mu sync.Mutex + state organizationTestState + failOwnerInsert bool +} + +func newOrganizationTestTransactor() *organizationTestTransactor { + return &organizationTestTransactor{state: newOrganizationTestState()} +} + +func (transactor *organizationTestTransactor) WithinTransaction( + ctx context.Context, + work func(context.Context, outbound.UnitOfWork) error, +) error { + transactor.mu.Lock() + defer transactor.mu.Unlock() + working := transactor.state.clone() + unit := &organizationTestUnit{state: &working, failOwnerInsert: transactor.failOwnerInsert} + if err := work(ctx, unit); err != nil { + return err + } + transactor.state = working + return nil +} + +func (transactor *organizationTestTransactor) snapshot() organizationTestState { + transactor.mu.Lock() + defer transactor.mu.Unlock() + return transactor.state.clone() +} + +type organizationTestUnit struct { + outbound.UnitOfWork + + state *organizationTestState + failOwnerInsert bool +} + +func (unit *organizationTestUnit) Users() outbound.UserRepository { + return organizationTestUsers{state: unit.state} +} + +func (unit *organizationTestUnit) IdempotencyRecords() outbound.IdempotencyRepository { + return organizationTestIdempotency{state: unit.state} +} + +func (unit *organizationTestUnit) Organizations() outbound.OrganizationRepository { + return organizationTestOrganizations{state: unit.state, failOwnerInsert: unit.failOwnerInsert} +} + +type organizationTestUsers struct { + outbound.UserRepository + + state *organizationTestState +} + +func (repository organizationTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) { + user, ok := repository.state.users[id] + if !ok { + return domain.User{}, outbound.ErrUserNotFound + } + return user, nil +} + +type organizationTestIdempotency struct { + outbound.IdempotencyRepository + + state *organizationTestState +} + +func (repository organizationTestIdempotency) Reserve( + _ context.Context, + record outbound.IdempotencyRecord, +) (outbound.IdempotencyRecord, bool, error) { + if stored, ok := repository.state.idempotency[record.Scope]; ok && stored.ExpiresAt.After(record.CreatedAt) { + return stored, false, nil + } + repository.state.idempotency[record.Scope] = record + return record, true, nil +} + +func (repository organizationTestIdempotency) Find( + _ context.Context, + scope [outbound.IdempotencyDigestSize]byte, + at time.Time, +) (outbound.IdempotencyRecord, error) { + record, ok := repository.state.idempotency[scope] + if !ok || !record.ExpiresAt.After(at) { + return outbound.IdempotencyRecord{}, outbound.ErrIdempotencyRecordNotFound + } + return record, nil +} + +func (repository organizationTestIdempotency) PurgeExpired( + _ context.Context, + at time.Time, + limit int32, +) (int64, error) { + var deleted int64 + for scope, record := range repository.state.idempotency { + if deleted >= int64(limit) { + break + } + if !record.ExpiresAt.After(at) { + delete(repository.state.idempotency, scope) + delete(repository.state.results, scope) + deleted++ + } + } + return deleted, nil +} + +type organizationTestOrganizations struct { + outbound.OrganizationRepository + + state *organizationTestState + failOwnerInsert bool +} + +func (repository organizationTestOrganizations) CreateWithOwner( + _ context.Context, + company domain.Organization, + owner domain.Membership, +) error { + repository.state.organizations[company.ID()] = company + if repository.failOwnerInsert { + return errors.New("simulated owner membership insert failure") + } + repository.state.memberships[organizationTestMembershipKey{company.ID(), owner.UserID()}] = owner + return nil +} + +func (repository organizationTestOrganizations) SaveCreationResult( + _ context.Context, + scope [outbound.IdempotencyDigestSize]byte, + result outbound.OrganizationCreationResult, +) error { + if _, ok := repository.state.idempotency[scope]; !ok { + return outbound.ErrIdempotencyRecordNotFound + } + repository.state.results[scope] = result + return nil +} + +func (repository organizationTestOrganizations) GetCreationResult( + _ context.Context, + scope [outbound.IdempotencyDigestSize]byte, +) (outbound.OrganizationCreationResult, error) { + result, ok := repository.state.results[scope] + if !ok { + return outbound.OrganizationCreationResult{}, outbound.ErrOrganizationCreationResultNotFound + } + return result, nil +} + +func (repository organizationTestOrganizations) GetForMember( + _ context.Context, + organizationID, userID uuid.UUID, +) (domain.Organization, domain.Membership, error) { + company, companyOK := repository.state.organizations[organizationID] + membership, memberOK := repository.state.memberships[organizationTestMembershipKey{organizationID, userID}] + if !companyOK || !memberOK || !membership.GrantsAccess() { + return domain.Organization{}, domain.Membership{}, outbound.ErrOrganizationNotFound + } + return company, membership, nil +} + +func (repository organizationTestOrganizations) ListForUser( + context.Context, + outbound.OrganizationListQuery, +) (outbound.OrganizationPage, error) { + return outbound.OrganizationPage{}, nil +} + +func (repository organizationTestOrganizations) UpdateProfile( + _ context.Context, + actorID uuid.UUID, + updated domain.Organization, +) (domain.Organization, error) { + current, ok := repository.state.organizations[updated.ID()] + if !ok { + return domain.Organization{}, outbound.ErrOrganizationNotFound + } + membership, ok := repository.state.memberships[organizationTestMembershipKey{updated.ID(), actorID}] + if !ok || !membership.GrantsAccess() { + return domain.Organization{}, outbound.ErrOrganizationNotFound + } + if !membership.CanManageOrganization() { + return domain.Organization{}, outbound.ErrOrganizationManagerRequired + } + if current.Version() != updated.Version() { + return domain.Organization{}, outbound.ErrOrganizationVersionConflict + } + company, err := restoreOrganizationVersion(updated, current.Version()+1) + if err != nil { + return domain.Organization{}, err + } + repository.state.organizations[updated.ID()] = company + return company, nil +} + +func restoreOrganizationVersion(company domain.Organization, version int64) (domain.Organization, error) { + profile := company.Profile() + contacts := profile.Contacts() + representatives := profile.Representatives() + storedRepresentatives := make([]domain.StoredRepresentative, 0, len(representatives)) + for _, representative := range representatives { + storedRepresentatives = append(storedRepresentatives, domain.StoredRepresentative{ + Name: representative.Name(), JobTitle: representative.JobTitle(), + }) + } + verification := company.Verification() + return domain.RestoreOrganization(domain.StoredOrganization{ + ID: company.ID(), Name: profile.Name(), Description: profile.Description(), Sphere: profile.Sphere(), + Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(), + Representatives: storedRepresentatives, VerificationLevel: string(verification.Level()), + VerificationBasis: string(verification.Basis()), VerificationChangedAt: verification.ChangedAt(), + Version: version, CreatedAt: company.CreatedAt(), UpdatedAt: company.UpdatedAt(), + }) +} + +func newOrganizationTestService(t *testing.T, tx *organizationTestTransactor, clock func() time.Time) *Service { + t.Helper() + keyring, err := identity.NewKeyring([]byte(strings.Repeat("k", identity.MinKeySecretBytes))) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + service, err := NewService(Dependencies{Transactor: tx, Keyring: keyring, Clock: clock}) + if err != nil { + t.Fatalf("NewService() error = %v", err) + } + return service +} + +func verifiedEmployer(id uuid.UUID, at time.Time) domain.User { + verifiedAt := at + return domain.User{ID: id, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt} +} + +func organizationProfile(name, description string) domain.OrganizationProfileInput { + return domain.OrganizationProfileInput{ + Name: name, Description: description, Sphere: "Payments", + Contacts: domain.OrganizationContactsInput{ + Website: "https://example.com", Email: "careers@example.com", Phone: "+74951234567", Telegram: "@example", + }, + Representatives: []domain.OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Директор"}}, + } +} + +func canonicalBodyForTest(t *testing.T, profile domain.OrganizationProfileInput) []byte { + t.Helper() + body, err := canonicalCreateBody(profile) + if err != nil { + t.Fatalf("canonicalCreateBody() error = %v", err) + } + return body +} + +func TestCreateStoresOwnerAtE0AndReplaysOriginalSnapshotAfterEdit(t *testing.T) { + ctx := t.Context() + now := time.Date(2026, 8, 15, 10, 30, 0, 123456000, time.UTC) + currentTime := now + tx := newOrganizationTestTransactor() + ownerID := uuid.New() + tx.state.users[ownerID] = verifiedEmployer(ownerID, now) + service := newOrganizationTestService(t, tx, func() time.Time { return currentTime }) + profile := organizationProfile("ООО Пример", "Первоначальные данные") + command := CreateCommand{ + ActorID: ownerID, IdempotencyKey: "company-create-01", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile, + } + + created, err := service.Create(ctx, command) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + if created.Replayed || created.Organization.Version() != 1 || created.Owner.UserID() != ownerID || + created.Owner.Role() != domain.OrganizationRoleOwner || !created.Owner.GrantsAccess() { + t.Fatalf("Create() = %+v, want a new version 1 organization and its active owner", created) + } + verification := created.Organization.Verification() + if verification.Level() != domain.OrganizationVerificationE0 || verification.Basis() != domain.OrganizationBasisConfirmedEmail { + t.Fatalf("verification = %s %s, want e0 from confirmed email", verification.Level(), verification.Basis()) + } + if card := created.Organization.CandidateCard(); card.ID() != created.Organization.ID() || card.VerificationLevel() != domain.OrganizationVerificationE0 { + t.Fatalf("CandidateCard() = %+v, want the safe organization card", card) + } + + currentTime = now.Add(time.Minute) + updated, err := service.Update(ctx, UpdateCommand{ + ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, + Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Измененные данные"}}, + }) + if err != nil { + t.Fatalf("Update() error = %v", err) + } + if updated.Profile().Description() != "Измененные данные" || updated.Version() != 2 || + updated.Verification().Level() != domain.OrganizationVerificationE0 { + t.Fatalf("Update() = %+v, want version 2 with the edited profile and e0", updated) + } + + replayed, err := service.Create(ctx, command) + if err != nil { + t.Fatalf("Create(retry) error = %v", err) + } + if !replayed.Replayed || replayed.Organization.ID() != created.Organization.ID() || + !replayed.Organization.Profile().Equal(created.Organization.Profile()) || + replayed.Organization.Version() != 1 || replayed.Owner.ID() != created.Owner.ID() { + t.Fatalf("Create(retry) = %+v, want the original immutable result", replayed) + } + state := tx.snapshot() + if len(state.organizations) != 1 || len(state.memberships) != 1 || len(state.results) != 1 { + t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 1/1/1", len(state.organizations), len(state.memberships), len(state.results)) + } +} + +func TestCreateRejectsChangedBodyAndAllowsReuseAfterExpiration(t *testing.T) { + ctx := t.Context() + now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) + currentTime := now + tx := newOrganizationTestTransactor() + ownerID := uuid.New() + tx.state.users[ownerID] = verifiedEmployer(ownerID, now) + service := newOrganizationTestService(t, tx, func() time.Time { return currentTime }) + firstProfile := organizationProfile("ООО Пример", "Первоначальные данные") + first := CreateCommand{ + ActorID: ownerID, IdempotencyKey: "company-create-02", CanonicalBody: canonicalBodyForTest(t, firstProfile), Profile: firstProfile, + } + created, err := service.Create(ctx, first) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + changedProfile := organizationProfile("ООО Другое", "Первоначальные данные") + changed := CreateCommand{ + ActorID: ownerID, IdempotencyKey: first.IdempotencyKey, + CanonicalBody: canonicalBodyForTest(t, changedProfile), Profile: changedProfile, + } + if _, err := service.Create(ctx, changed); !errors.Is(err, ErrIdempotencyKeyReused) { + t.Fatalf("Create(changed body) error = %v, want ErrIdempotencyKeyReused", err) + } + if count := len(tx.snapshot().organizations); count != 1 { + t.Fatalf("organization count after changed-body retry = %d, want 1", count) + } + + currentTime = now.Add(outbound.IdempotencyRetention + time.Second) + reused, err := service.Create(ctx, first) + if err != nil { + t.Fatalf("Create(expired key) error = %v", err) + } + if reused.Replayed || reused.Organization.ID() == created.Organization.ID() { + t.Fatalf("Create(expired key) = %+v, want a new organization", reused) + } + state := tx.snapshot() + if len(state.organizations) != 2 || len(state.memberships) != 2 || len(state.results) != 1 { + t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 2/2/1", len(state.organizations), len(state.memberships), len(state.results)) + } +} + +func TestCreateRollsBackOrganizationOwnerIdempotencyAndSnapshot(t *testing.T) { + ctx := t.Context() + now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) + tx := newOrganizationTestTransactor() + tx.failOwnerInsert = true + ownerID := uuid.New() + tx.state.users[ownerID] = verifiedEmployer(ownerID, now) + service := newOrganizationTestService(t, tx, func() time.Time { return now }) + profile := organizationProfile("ООО Пример", "Данные") + _, err := service.Create(ctx, CreateCommand{ + ActorID: ownerID, IdempotencyKey: "company-create-03", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile, + }) + if err == nil || !strings.Contains(err.Error(), "run transaction") { + t.Fatalf("Create(owner insert failure) error = %v, want transaction failure", err) + } + state := tx.snapshot() + if len(state.organizations) != 0 || len(state.memberships) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 { + t.Fatalf("state after failed transaction = companies:%d memberships:%d idempotency:%d results:%d, want all zero", + len(state.organizations), len(state.memberships), len(state.idempotency), len(state.results)) + } +} + +func TestCreateRequiresVerifiedEmployer(t *testing.T) { + now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) + for _, test := range []struct { + name string + user domain.User + want error + }{ + {name: "candidate", user: domain.User{ID: uuid.New(), Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}, want: ErrForbidden}, + {name: "unverified employer", user: domain.User{ID: uuid.New(), Scenario: domain.ScenarioEmployer}, want: ErrEmailNotVerified}, + } { + t.Run(test.name, func(t *testing.T) { + tx := newOrganizationTestTransactor() + tx.state.users[test.user.ID] = test.user + service := newOrganizationTestService(t, tx, func() time.Time { return now }) + profile := organizationProfile("ООО Пример", "Данные") + _, err := service.Create(t.Context(), CreateCommand{ + ActorID: test.user.ID, IdempotencyKey: "company-create-04", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile, + }) + if !errors.Is(err, test.want) { + t.Fatalf("Create() error = %v, want %v", err, test.want) + } + if state := tx.snapshot(); len(state.organizations) != 0 || len(state.idempotency) != 0 { + t.Fatalf("state after denied create = companies:%d idempotency:%d, want both zero", len(state.organizations), len(state.idempotency)) + } + }) + } +} + +func TestUpdateRequiresOwnerAndPreservesVerification(t *testing.T) { + ctx := t.Context() + now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) + currentTime := now + tx := newOrganizationTestTransactor() + ownerID := uuid.New() + foreignID := uuid.New() + memberID := uuid.New() + tx.state.users[ownerID] = verifiedEmployer(ownerID, now) + tx.state.users[foreignID] = verifiedEmployer(foreignID, now) + tx.state.users[memberID] = verifiedEmployer(memberID, now) + service := newOrganizationTestService(t, tx, func() time.Time { return currentTime }) + profile := organizationProfile("ООО Пример", "Данные") + created, err := service.Create(ctx, CreateCommand{ + ActorID: ownerID, IdempotencyKey: "company-create-05", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile, + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + + if _, err := service.Update(ctx, UpdateCommand{ + ActorID: foreignID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, + Patch: ProfilePatch{Name: OptionalString{Set: true, Value: "Чужое изменение"}}, + }); !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("Update(foreign user) error = %v, want ErrOrganizationNotFound", err) + } + member, err := domain.NewMembership(domain.MembershipInput{ + OrganizationID: created.Organization.ID(), UserID: memberID, + Role: domain.OrganizationRoleRecruiter, At: now.Add(time.Second), + }) + if err != nil { + t.Fatalf("NewMembership() error = %v", err) + } + tx.mu.Lock() + tx.state.memberships[organizationTestMembershipKey{created.Organization.ID(), memberID}] = member + tx.mu.Unlock() + if _, err := service.Update(ctx, UpdateCommand{ + ActorID: memberID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, + Patch: ProfilePatch{Name: OptionalString{Set: true, Value: "Чужое изменение"}}, + }); !errors.Is(err, outbound.ErrOrganizationManagerRequired) { + t.Fatalf("Update(non-owner member) error = %v, want ErrOrganizationManagerRequired", err) + } + + currentTime = now.Add(time.Minute) + updated, err := service.Update(ctx, UpdateCommand{ + ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, + Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Новый текст"}}, + }) + if err != nil { + t.Fatalf("Update(owner) error = %v", err) + } + if updated.Version() != 2 || updated.Profile().Description() != "Новый текст" || + updated.Verification().Level() != domain.OrganizationVerificationE0 || + updated.Verification().Basis() != domain.OrganizationBasisConfirmedEmail { + t.Fatalf("Update(owner) = %+v, want profile version 2 with unchanged e0 verification", updated) + } + if _, err := service.Update(ctx, UpdateCommand{ + ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, + Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Другая версия"}}, + }); !errors.Is(err, outbound.ErrOrganizationVersionConflict) { + t.Fatalf("Update(stale version) error = %v, want ErrOrganizationVersionConflict", err) + } + noOp, err := service.Update(ctx, UpdateCommand{ + ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, + Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Новый текст"}}, + }) + if err != nil || noOp.Version() != 2 { + t.Fatalf("Update(stale no-op) = %v, %v, want current version 2", noOp, err) + } + invalidContacts := domain.OrganizationContactsInput{Website: "http://invalid.example"} + if _, err := service.Update(ctx, UpdateCommand{ + ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, + Patch: ProfilePatch{Contacts: &invalidContacts}, + }); !errors.Is(err, outbound.ErrOrganizationVersionConflict) { + t.Fatalf("Update(stale invalid website) error = %v, want version conflict", err) + } + if _, err := service.Update(ctx, UpdateCommand{ + ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 2, + Patch: ProfilePatch{Contacts: &invalidContacts}, + }); !errors.Is(err, domain.ErrInvalidOrganization) { + t.Fatalf("Update(current invalid website) error = %v, want domain validation error", err) + } +} + +func TestConcurrentCreateWithSameKeyReturnsOneCompany(t *testing.T) { + ctx := t.Context() + now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) + tx := newOrganizationTestTransactor() + ownerID := uuid.New() + tx.state.users[ownerID] = verifiedEmployer(ownerID, now) + service := newOrganizationTestService(t, tx, func() time.Time { return now }) + profile := organizationProfile("ООО Пример", "Данные") + command := CreateCommand{ + ActorID: ownerID, IdempotencyKey: "company-create-06", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile, + } + const requests = 12 + results := make(chan CreateResult, requests) + errorsFound := make(chan error, requests) + var wait sync.WaitGroup + for range requests { + wait.Add(1) + go func() { + defer wait.Done() + result, err := service.Create(ctx, command) + if err != nil { + errorsFound <- err + return + } + results <- result + }() + } + wait.Wait() + close(results) + close(errorsFound) + for err := range errorsFound { + t.Fatalf("Create(concurrent) error = %v", err) + } + var organizationID uuid.UUID + createdCount := 0 + for result := range results { + if organizationID == uuid.Nil { + organizationID = result.Organization.ID() + } + if result.Organization.ID() != organizationID || result.Owner.UserID() != ownerID { + t.Fatalf("concurrent result = %+v, want the same company and owner", result) + } + if !result.Replayed { + createdCount++ + } + } + if createdCount != 1 { + t.Fatalf("non-replayed results = %d, want one", createdCount) + } + state := tx.snapshot() + if len(state.organizations) != 1 || len(state.memberships) != 1 || len(state.results) != 1 { + t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 1/1/1", len(state.organizations), len(state.memberships), len(state.results)) + } +} + +func TestCreateInputCanonicalizationIsStable(t *testing.T) { + profile := organizationProfile("ООО Пример", "Данные") + one := canonicalBodyForTest(t, profile) + two := canonicalBodyForTest(t, profile) + if string(one) != string(two) { + t.Fatalf("canonical bodies differ: %q and %q", one, two) + } + changed := profile + changed.Representatives = append([]domain.OrganizationRepresentativeInput(nil), profile.Representatives...) + changed.Representatives[0].Name = "Другой человек" + three := canonicalBodyForTest(t, changed) + if string(one) == string(three) { + t.Fatalf("canonical body did not change with representative name: %q", one) + } +} + +func ExampleOptionalString() { + patch := ProfilePatch{Description: OptionalString{Set: true, Value: ""}} + fmt.Println(patch.Description.Set, patch.Description.Value == "") + // Output: true true +} diff --git a/frontend/src/shared/api/endpoints/consent/consent.msw.ts b/frontend/src/shared/api/endpoints/consent/consent.msw.ts index 6f25e51..a0f70d0 100644 --- a/frontend/src/shared/api/endpoints/consent/consent.msw.ts +++ b/frontend/src/shared/api/endpoints/consent/consent.msw.ts @@ -21,15 +21,38 @@ import type { } from 'msw'; import type { + ConsentDeletionRequest, ConsentOrganization, - ConsentRecordList + ConsentRecord, + ConsentRecordList, + ConsentText } from '../../schemas'; +export const getGetMyConsentTextResponseMock = (overrideResponse: Partial> = {}): ConsentText => ({purpose: faker.helpers.arrayElement(['c1','c2','c3','c4','c5'] as const), text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), text: faker.string.alpha({length: {min: 1, max: 100000}}), published_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) + export const getListMyConsentsResponseConsentOrganizationMock = (overrideResponse: Partial = {}): ConsentOrganization => ({...{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, ...overrideResponse}); export const getListMyConsentsResponseMock = (overrideResponse: Partial> = {}): ConsentRecordList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), purpose: faker.helpers.arrayElement(['c1','c2','c3','c4','c5'] as const), state: faker.helpers.arrayElement(['active','superseded','revoked'] as const), text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), source: faker.helpers.arrayElement(['registration','consent_settings','invitation_acceptance'] as const), granted_at: faker.date.past().toISOString().slice(0, 19) + 'Z', revoked_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), revocation_source: faker.helpers.arrayElement([faker.helpers.arrayElement(['consent_settings','support_request'] as const),null,]), organization: faker.helpers.arrayElement([{...getListMyConsentsResponseConsentOrganizationMock()},null,]), fields: faker.helpers.arrayElement([faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const), null]), invitation_id: faker.helpers.arrayElement([faker.string.uuid(), null]), invitation_terms_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse}) +export const getGrantMyConsentResponseConsentOrganizationMock = (overrideResponse: Partial = {}): ConsentOrganization => ({...{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, ...overrideResponse}); + +export const getGrantMyConsentResponseMock = (overrideResponse: Partial> = {}): ConsentRecord => ({id: faker.string.uuid(), purpose: faker.helpers.arrayElement(['c1','c2','c3','c4','c5'] as const), state: faker.helpers.arrayElement(['active','superseded','revoked'] as const), text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), source: faker.helpers.arrayElement(['registration','consent_settings','invitation_acceptance'] as const), granted_at: faker.date.past().toISOString().slice(0, 19) + 'Z', revoked_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), revocation_source: faker.helpers.arrayElement([faker.helpers.arrayElement(['consent_settings','support_request'] as const),null,]), organization: faker.helpers.arrayElement([{...getGrantMyConsentResponseConsentOrganizationMock()},null,]), fields: faker.helpers.arrayElement([faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const), null]), invitation_id: faker.helpers.arrayElement([faker.string.uuid(), null]), invitation_terms_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), ...overrideResponse}) + +export const getRequestMyAccountDeletionResponseMock = (overrideResponse: Partial> = {}): ConsentDeletionRequest => ({id: faker.string.uuid(), status: faker.helpers.arrayElement(['requested','processing'] as const), requested_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) + + +export const getGetMyConsentTextMockHandler = (overrideResponse?: ConsentText | ((info: Parameters[1]>[0]) => Promise | ConsentText), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/consent-texts/:purpose', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetMyConsentTextResponseMock(), + { status: 200 + }) + }, options) +} export const getListMyConsentsMockHandler = (overrideResponse?: ConsentRecordList | ((info: Parameters[1]>[0]) => Promise | ConsentRecordList), options?: RequestHandlerOptions) => { return http.get('*/api/v1/me/consents', async (info: Parameters[1]>[0]) => { @@ -42,6 +65,55 @@ export const getListMyConsentsMockHandler = (overrideResponse?: ConsentRecordLis }) }, options) } + +export const getGrantMyConsentMockHandler = (overrideResponse?: ConsentRecord | ((info: Parameters[1]>[0]) => Promise | ConsentRecord), options?: RequestHandlerOptions) => { + return http.put('*/api/v1/me/consents/:purpose', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGrantMyConsentResponseMock(), + { status: 200 + }) + }, options) +} + +export const getRevokeMyConsentMockHandler = (overrideResponse?: void | ((info: Parameters[1]>[0]) => Promise | void), options?: RequestHandlerOptions) => { + return http.delete('*/api/v1/me/consents/:purpose', async (info: Parameters[1]>[0]) => { + if (typeof overrideResponse === 'function') {await overrideResponse(info); } + + return new HttpResponse(null, + { status: 204 + }) + }, options) +} + +export const getRevokeMyOrganizationContactConsentMockHandler = (overrideResponse?: void | ((info: Parameters[1]>[0]) => Promise | void), options?: RequestHandlerOptions) => { + return http.delete('*/api/v1/me/consents/c4/organizations/:orgId', async (info: Parameters[1]>[0]) => { + if (typeof overrideResponse === 'function') {await overrideResponse(info); } + + return new HttpResponse(null, + { status: 204 + }) + }, options) +} + +export const getRequestMyAccountDeletionMockHandler = (overrideResponse?: ConsentDeletionRequest | ((info: Parameters[1]>[0]) => Promise | ConsentDeletionRequest), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/account-deletion-requests', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getRequestMyAccountDeletionResponseMock(), + { status: 202 + }) + }, options) +} export const getConsentMock = () => [ - getListMyConsentsMockHandler() + getGetMyConsentTextMockHandler(), + getListMyConsentsMockHandler(), + getGrantMyConsentMockHandler(), + getRevokeMyConsentMockHandler(), + getRevokeMyOrganizationContactConsentMockHandler(), + getRequestMyAccountDeletionMockHandler() ] diff --git a/frontend/src/shared/api/endpoints/consent/consent.ts b/frontend/src/shared/api/endpoints/consent/consent.ts index 8732fc0..f4b1b78 100644 --- a/frontend/src/shared/api/endpoints/consent/consent.ts +++ b/frontend/src/shared/api/endpoints/consent/consent.ts @@ -5,22 +5,32 @@ * OpenAPI spec version: 0.1.0 */ import { + useMutation, useQuery } from '@tanstack/react-query'; import type { DataTag, DefinedInitialDataOptions, DefinedUseQueryResult, + MutationFunction, QueryClient, QueryFunction, QueryKey, UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, UseQueryOptions, UseQueryResult } from '@tanstack/react-query'; import type { + ConsentDeletionRequest, + ConsentRecord, ConsentRecordList, + ConsentSettingsGrantRequest, + ConsentSettingsPurpose, + ConsentSettingsRevokePurpose, + ConsentText, ListMyConsentsParams, Problem } from '../../schemas'; @@ -48,6 +58,107 @@ const withQueryKey = (query: T, queryKey: K): T & { queryKe return result; }; +export const getGetMyConsentTextUrl = (purpose: ConsentSettingsPurpose,) => { + + + + + return `/api/v1/me/consent-texts/${purpose}` +} + +/** + * Requires a verified session. Returns the current published text and version of c1, c2, c3, or c5 so the user can read the exact text before an explicit settings grant. C4 is excluded: its text includes an organization snapshot and it is granted only during invitation acceptance. The response is private and is not cached. + * @summary Read a current consent text for account settings. + */ +export const getMyConsentText = async (purpose: ConsentSettingsPurpose, options?: Parameters[1]): Promise => { + + return apiRequest(getGetMyConsentTextUrl(purpose), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyConsentTextQueryKey = (purpose: ConsentSettingsPurpose,) => { + return [ + `/api/v1/me/consent-texts/${purpose}` + ] as const; + } + + +export const getGetMyConsentTextQueryOptions = >, TError = ErrorType>(purpose: ConsentSettingsPurpose, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyConsentTextQueryKey(purpose); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyConsentText(purpose, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: purpose !== null && purpose !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyConsentTextQueryResult = NonNullable>> +export type GetMyConsentTextQueryError = ErrorType + + +export function useGetMyConsentText>, TError = ErrorType>( + purpose: ConsentSettingsPurpose, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyConsentText>, TError = ErrorType>( + purpose: ConsentSettingsPurpose, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyConsentText>, TError = ErrorType>( + purpose: ConsentSettingsPurpose, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read a current consent text for account settings. + */ + +export function useGetMyConsentText>, TError = ErrorType>( + purpose: ConsentSettingsPurpose, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyConsentTextQueryOptions(purpose,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + export const getListMyConsentsUrl = (params?: ListMyConsentsParams,) => { const normalizedParams = new URLSearchParams(); @@ -70,7 +181,7 @@ export const getListMyConsentsUrl = (params?: ListMyConsentsParams,) => { * * Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history. * - * Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. + * Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation. * * Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit`, `cursor`, or `state` answers 400 validation_failed. * @summary List the consents of the current account with their history. @@ -164,3 +275,318 @@ export function useListMyConsents { + + + + + return `/api/v1/me/consents/${purpose}` +} + +/** + * Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. The body names the current text version the user read and requires `accepted: true`; the server verifies that version is still current and stores the hash of the exact text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant. + * + * C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the same current version returns the existing record; after revocation a grant creates a new record and never reopens a publication or restores an older grant. + * @summary Record an explicit consent grant from settings. + */ +export const grantMyConsent = async (purpose: ConsentSettingsPurpose, + consentSettingsGrantRequest: ConsentSettingsGrantRequest, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getGrantMyConsentUrl(purpose), + { + ...options, + method: 'PUT', + headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) }, + body: JSON.stringify(consentSettingsGrantRequest) + } +);} + + + + + +export const getGrantMyConsentMutationKey = () => ['grantMyConsent'] as const; + +export const getGrantMyConsentMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,GrantMyConsentMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,GrantMyConsentMutationVariables, TContext> => { + +const mutationKey = getGrantMyConsentMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, GrantMyConsentMutationVariables> = (props) => { + const {purpose,data} = props ?? {}; + + return grantMyConsent(purpose,data,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type GrantMyConsentMutationResult = NonNullable>> + export type GrantMyConsentMutationBody = ConsentSettingsGrantRequest + export type GrantMyConsentMutationError = ErrorType + export type GrantMyConsentMutationVariables = {purpose: ConsentSettingsPurpose;data: ConsentSettingsGrantRequest} + + /** + * @summary Record an explicit consent grant from settings. + */ +export const useGrantMyConsent = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,GrantMyConsentMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + GrantMyConsentMutationVariables, + TContext + > => { + return useMutation(getGrantMyConsentMutationOptions(options), queryClient); + } + export const getRevokeMyConsentUrl = (purpose: ConsentSettingsRevokePurpose,) => { + + + + + return `/api/v1/me/consents/${purpose}` +} + +/** + * Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5, including superseded records, and never changes another purpose. Repeating a revocation is harmless and creates no duplicate event. + * + * Revoking c2 immediately closes the stored publication and records privacy history in the same transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not reopen publication or restore old grants. Revoking c3 does not block the manual assessment path. Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent; an external FSP deletion adapter is not available yet. + * @summary Revoke a non-scoped consent from settings. + */ +export const revokeMyConsent = async (purpose: ConsentSettingsRevokePurpose, options?: Parameters[1]): Promise => { + + return apiRequest(getRevokeMyConsentUrl(purpose), + { + ...options, + method: 'DELETE' + + + } +);} + + + + + +export const getRevokeMyConsentMutationKey = () => ['revokeMyConsent'] as const; + +export const getRevokeMyConsentMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,RevokeMyConsentMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,RevokeMyConsentMutationVariables, TContext> => { + +const mutationKey = getRevokeMyConsentMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, RevokeMyConsentMutationVariables> = (props) => { + const {purpose} = props ?? {}; + + return revokeMyConsent(purpose,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type RevokeMyConsentMutationResult = NonNullable>> + + export type RevokeMyConsentMutationError = ErrorType + export type RevokeMyConsentMutationVariables = {purpose: ConsentSettingsRevokePurpose} + + /** + * @summary Revoke a non-scoped consent from settings. + */ +export const useRevokeMyConsent = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,RevokeMyConsentMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + RevokeMyConsentMutationVariables, + TContext + > => { + return useMutation(getRevokeMyConsentMutationOptions(options), queryClient); + } + export const getRevokeMyOrganizationContactConsentUrl = (orgId: string,) => { + + + + + return `/api/v1/me/consents/c4/organizations/${orgId}` +} + +/** + * Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The server revokes every unrevoked C4 record for this subject and organization, using the fields stored on those records to request downstream grant revocation. It does not affect another organization. Repeating the request is harmless and creates no duplicate event. + * @summary Revoke C4 for one organization. + */ +export const revokeMyOrganizationContactConsent = async (orgId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getRevokeMyOrganizationContactConsentUrl(orgId), + { + ...options, + method: 'DELETE' + + + } +);} + + + + + +export const getRevokeMyOrganizationContactConsentMutationKey = () => ['revokeMyOrganizationContactConsent'] as const; + +export const getRevokeMyOrganizationContactConsentMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,RevokeMyOrganizationContactConsentMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,RevokeMyOrganizationContactConsentMutationVariables, TContext> => { + +const mutationKey = getRevokeMyOrganizationContactConsentMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, RevokeMyOrganizationContactConsentMutationVariables> = (props) => { + const {orgId} = props ?? {}; + + return revokeMyOrganizationContactConsent(orgId,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type RevokeMyOrganizationContactConsentMutationResult = NonNullable>> + + export type RevokeMyOrganizationContactConsentMutationError = ErrorType + export type RevokeMyOrganizationContactConsentMutationVariables = {orgId: string} + + /** + * @summary Revoke C4 for one organization. + */ +export const useRevokeMyOrganizationContactConsent = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,RevokeMyOrganizationContactConsentMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + RevokeMyOrganizationContactConsentMutationVariables, + TContext + > => { + return useMutation(getRevokeMyOrganizationContactConsentMutationOptions(options), queryClient); + } + export const getRequestMyAccountDeletionUrl = () => { + + + + + return `/api/v1/me/account-deletion-requests` +} + +/** + * Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. In one transaction, revokes any active C1 record, creates or returns the subject's active durable deletion request, and writes the outbox intent. The API does not delete the account synchronously. Repeating the request returns the same active request; a later C1 grant never cancels it. + * @summary Revoke C1 and request account deletion. + */ +export const requestMyAccountDeletion = async ( options?: Parameters[1]): Promise => { + + return apiRequest(getRequestMyAccountDeletionUrl(), + { + ...options, + method: 'POST' + + + } +);} + + + + + +export const getRequestMyAccountDeletionMutationKey = () => ['requestMyAccountDeletion'] as const; + +export const getRequestMyAccountDeletionMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,void, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,void, TContext> => { + +const mutationKey = getRequestMyAccountDeletionMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, void> = () => { + + + return requestMyAccountDeletion(requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type RequestMyAccountDeletionMutationResult = NonNullable>> + + export type RequestMyAccountDeletionMutationError = ErrorType + + + /** + * @summary Revoke C1 and request account deletion. + */ +export const useRequestMyAccountDeletion = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,void, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + void, + TContext + > => { + return useMutation(getRequestMyAccountDeletionMutationOptions(options), queryClient); + } diff --git a/frontend/src/shared/api/endpoints/identity/identity.msw.ts b/frontend/src/shared/api/endpoints/identity/identity.msw.ts index 05749b9..ff8ff97 100644 --- a/frontend/src/shared/api/endpoints/identity/identity.msw.ts +++ b/frontend/src/shared/api/endpoints/identity/identity.msw.ts @@ -29,7 +29,7 @@ import type { } from '../../schemas'; -export const getGetConsentTextResponseMock = (overrideResponse: Partial> = {}): ConsentText => ({purpose: faker.helpers.arrayElement(['c1'] as const), text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), text: faker.string.alpha({length: {min: 1, max: 100000}}), published_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) +export const getGetConsentTextResponseMock = (overrideResponse: Partial> = {}): ConsentText => ({purpose: faker.helpers.arrayElement(['c1','c2','c3','c4','c5'] as const), text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), text: faker.string.alpha({length: {min: 1, max: 100000}}), published_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) export const getRegisterAccountResponseMock = (overrideResponse: Partial> = {}): IdentityRequestAccepted => ({status: faker.helpers.arrayElement(['accepted'] as const), ...overrideResponse}) diff --git a/frontend/src/shared/api/schemas/consent/consentDeletionRequest.zod.ts b/frontend/src/shared/api/schemas/consent/consentDeletionRequest.zod.ts new file mode 100644 index 0000000..834c33d --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentDeletionRequest.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const ConsentDeletionRequest = zod.object({ + "id": zod.uuid().describe('Identifier of the durable deletion request.'), + "status": zod.enum(['requested', 'processing']).describe('Current state of the deletion request.'), + "requested_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Durable request to delete the account and its personal data. The request is recorded before asynchronous processing starts; it does not mean deletion has completed.') + +export type ConsentDeletionRequest = zod.input; +export type ConsentDeletionRequestOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/consentSettingsGrantRequest.zod.ts b/frontend/src/shared/api/schemas/consent/consentSettingsGrantRequest.zod.ts new file mode 100644 index 0000000..4a45f20 --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentSettingsGrantRequest.zod.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const consentSettingsGrantRequestTextVersionMax = 64; + + +export const consentSettingsGrantRequestTextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); + +export const ConsentSettingsGrantRequest = zod.object({ + "text_version": zod.string().min(1).max(consentSettingsGrantRequestTextVersionMax).regex(consentSettingsGrantRequestTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), + "accepted": zod.literal(true).describe('Must be true to record an explicit acceptance.') +}).describe('Accept the current published text shown by GetMyConsentText. The server checks its version again before recording the grant.') + +export type ConsentSettingsGrantRequest = zod.input; +export type ConsentSettingsGrantRequestOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/consentSettingsPurpose.zod.ts b/frontend/src/shared/api/schemas/consent/consentSettingsPurpose.zod.ts new file mode 100644 index 0000000..34baaf7 --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentSettingsPurpose.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const ConsentSettingsPurpose = zod.enum(['c1', 'c2', 'c3', 'c5']).describe('Consent text that an authenticated account can read and accept in settings. C4 is scoped to an invitation and organization, so it is not available through the general settings flow.') + +export type ConsentSettingsPurpose = zod.input; +export type ConsentSettingsPurposeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/consentSettingsRevokePurpose.zod.ts b/frontend/src/shared/api/schemas/consent/consentSettingsRevokePurpose.zod.ts new file mode 100644 index 0000000..7b42444 --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentSettingsRevokePurpose.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const ConsentSettingsRevokePurpose = zod.enum(['c2', 'c3', 'c5']).describe('Consent that can be revoked through the general settings flow. C1 uses the account deletion request, and C4 must be revoked for one organization.') + +export type ConsentSettingsRevokePurpose = zod.input; +export type ConsentSettingsRevokePurposeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/grantMyConsentBody.zod.ts b/frontend/src/shared/api/schemas/consent/grantMyConsentBody.zod.ts new file mode 100644 index 0000000..c4ef7ce --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/grantMyConsentBody.zod.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const grantMyConsentBodyTextVersionMax = 64; + + +export const grantMyConsentBodyTextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); + +export const GrantMyConsentBody = zod.object({ + "text_version": zod.string().min(1).max(grantMyConsentBodyTextVersionMax).regex(grantMyConsentBodyTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), + "accepted": zod.literal(true).describe('Must be true to record an explicit acceptance.') +}).describe('Accept the current published text shown by GetMyConsentText. The server checks its version again before recording the grant.') + +export type GrantMyConsentBody = zod.input; +export type GrantMyConsentBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/index.ts b/frontend/src/shared/api/schemas/consent/index.ts index 4cf480d..afaae17 100644 --- a/frontend/src/shared/api/schemas/consent/index.ts +++ b/frontend/src/shared/api/schemas/consent/index.ts @@ -5,11 +5,15 @@ * OpenAPI spec version: 0.1.0 */ +export * from './consentDeletionRequest.zod'; export * from './consentOrganization.zod'; -export * from './consentPurposeCode.zod'; export * from './consentRecord.zod'; export * from './consentRecordList.zod'; export * from './consentRevocationSource.zod'; +export * from './consentSettingsGrantRequest.zod'; +export * from './consentSettingsPurpose.zod'; +export * from './consentSettingsRevokePurpose.zod'; export * from './consentSource.zod'; export * from './consentState.zod'; +export * from './grantMyConsentBody.zod'; export * from './listMyConsentsParams.zod'; diff --git a/frontend/src/shared/api/schemas/consent/consentPurposeCode.zod.ts b/frontend/src/shared/api/schemas/consentPurposeCode.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/consent/consentPurposeCode.zod.ts rename to frontend/src/shared/api/schemas/consentPurposeCode.zod.ts diff --git a/frontend/src/shared/api/schemas/identity/consentText.zod.ts b/frontend/src/shared/api/schemas/consentText.zod.ts similarity index 61% rename from frontend/src/shared/api/schemas/identity/consentText.zod.ts rename to frontend/src/shared/api/schemas/consentText.zod.ts index 191179d..368f9bc 100644 --- a/frontend/src/shared/api/schemas/identity/consentText.zod.ts +++ b/frontend/src/shared/api/schemas/consentText.zod.ts @@ -14,7 +14,7 @@ export const consentTextTextMax = 100000; export const ConsentText = zod.object({ - "purpose": zod.enum(['c1']).describe('Consent whose text the client may read before an account exists. Only the consents given at registration are listed: `c1` is the consent to the processing of personal data.'), + "purpose": zod.enum(['c1', 'c2', 'c3', 'c4', 'c5']).describe('One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another.\n\n- c1: processing of personal data, given at registration.\n- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change.\n- c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric.\n- c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance.\n- c5: import of FSP results.\n\nConsentPurpose lists the subset whose text the client may read before an account exists.'), "text_version": zod.string().min(1).max(consentTextTextVersionMax).regex(consentTextTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), "text": zod.string().min(1).max(consentTextTextMax).describe('Full consent text in plain UTF-8; paragraphs are separated by an empty line. The client shows it as text, never as HTML.'), "published_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') diff --git a/frontend/src/shared/api/schemas/identity/index.ts b/frontend/src/shared/api/schemas/identity/index.ts index fd6d5b1..3f91c7d 100644 --- a/frontend/src/shared/api/schemas/identity/index.ts +++ b/frontend/src/shared/api/schemas/identity/index.ts @@ -10,7 +10,6 @@ export * from './accountScenario.zod'; export * from './confirmEmailBody.zod'; export * from './confirmEmailHeaders.zod'; export * from './consentPurpose.zod'; -export * from './consentText.zod'; export * from './csrfToken.zod'; export * from './emailVerificationRequest.zod'; export * from './emailVerificationResendRequest.zod'; diff --git a/frontend/src/shared/api/schemas/index.ts b/frontend/src/shared/api/schemas/index.ts index f9c4a3d..504a7a4 100644 --- a/frontend/src/shared/api/schemas/index.ts +++ b/frontend/src/shared/api/schemas/index.ts @@ -5,6 +5,8 @@ * OpenAPI spec version: 0.1.0 */ +export * from './consentPurposeCode.zod'; +export * from './consentText.zod'; export * from './consentTextVersion.zod'; export * from './contactFieldKind.zod'; export * from './contactFullName.zod';