diff --git a/api/README.en.md b/api/README.en.md index 7cf35e2..8152402 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -465,6 +465,24 @@ Planned, additive: the counter offer and the company answer, reading earlier ter No new problem code is added: the `ProblemCode` enum is copied byte-for-byte into the ML contract, and `version_conflict` and `state_conflict` cover the stale terms and the state conflicts. +### Consents + +The `consent` tag covers the consent ledger of the current account (PRD FR01, FR12, and 7.3): the independent consents C1-C5 with their text versions, sources, states, and revocations. The read operation is in the contract; its handler is not implemented yet, so it answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind it exists (TASK-062, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#consent-ledger)). + +| Method and path | operationId | Security | Success | Specific errors | +| --- | --- | --- | --- | --- | +| `GET /api/v1/me/consents` | `ListMyConsents` | session | 200 `ConsentRecordList`, `Cache-Control: no-store` | 400, 401 | + +- 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. +- 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 (TASK-088), 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 (TASK-063) and revoking any purpose with its consequences (TASK-064), 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. + +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. + ### Generator checks `testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core. diff --git a/api/README.md b/api/README.md index 8bbf9be..da4e088 100644 --- a/api/README.md +++ b/api/README.md @@ -465,6 +465,24 @@ ML-сервис отвечает на ошибки той же схемой `Pro Новый код ошибки не добавлен: enum `ProblemCode` побайтно копируется в ML-контракт, а `version_conflict` и `state_conflict` покрывают устаревшие условия и конфликты состояния. +### Согласия + +Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Операция чтения есть в контракте, но ее обработчик еще не реализован, поэтому до появления сессий она отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ней уже есть (TASK-062, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#журнал-согласий)). + +| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | +| --- | --- | --- | --- | --- | +| `GET /api/v1/me/consents` | `ListMyConsents` | сессия | 200 `ConsentRecordList`, `Cache-Control: no-store` | 400, 401 | + +- Цели (`ConsentPurposeCode`): `c1` - обработка персональных данных, `c2` - публикация карточки кандидата, `c3` - автоматическая категоризация, `c4` - передача выбранных контактов одной организации, `c5` - импорт результатов ФСП. `ConsentPurpose` остается подмножеством, текст которого доступен до регистрации (`c1`), поэтому `GetConsentText` не расширяется. +- Субъект берется из сессии; ни один параметр не называет аккаунт, поэтому ответ содержит только собственные записи вызывающего. Страница перечисляет записи от новой выдачи к старой с курсорной пагинацией; необязательный фильтр `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` доказывает согласие с текстом публикации; какие поля и когда опубликованы - доказательства истории публикации (TASK-088), а scope полей в записях `c2` был бы аддитивным изменением. Запись никогда не содержит значения контакта, субъекта или хэш текста: сервер хранит SHA-256 ровно того текста, который видел субъект, а клиент его не отправляет и не получает, как и для C1 при регистрации. +- Журнал только дополняется. Новая версия текста цели - новая запись, а прежняя становится `superseded` без изменений; отзыв один раз ставит отметку на неотозванные записи цели, а для `c4` - одной организации; последующая выдача - новая запись, и отозванное `c4` приглашения не возвращается. Цели независимы. +- Запланировано, аддитивно: выдача C1, C2, C3 и C5 в настройках согласий (TASK-063) и отзыв любой цели с последствиями (TASK-064) новыми операциями этого тега; у C1 при регистрации и C4 в `AcceptMyInvitation` уже есть свои операции. Разрешение 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 и, на уровне типов, отсутствие полей хэша, субъекта и контактов. + ### Проверки генераторов `testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core. diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index 35802fa..28d3ab2 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -3521,3 +3521,62 @@ InvitationSendBlocked: code: state_conflict detail: The resource is in a state that does not allow this operation. trace_id: 5b6c7d8e-9f0a-4b1c-8d2e-4f5a6b7c8d9e +ConsentRecordListPage: + summary: The whole consent history of a candidate on one page + description: C1 was accepted at registration and again for a newer text version, so the first record is superseded; the version c1-2026-10-05 is an illustration, since the migration publishes only c1-2026-10-01 so far. C2 was granted and revoked. C4 was given in the acceptance of one invitation with the email only; the organization name is the one the consent text showed. + value: + items: + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + purpose: c4 + state: active + text_version: c4-2026-10-01 + source: invitation_acceptance + granted_at: "2026-10-06T10:15:00Z" + revoked_at: null + revocation_source: null + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + fields: + - email + invitation_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + invitation_terms_version: 3 + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + purpose: c1 + state: active + text_version: c1-2026-10-05 + source: consent_settings + granted_at: "2026-10-05T12:00:00Z" + revoked_at: null + revocation_source: null + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + purpose: c2 + state: revoked + text_version: c2-2026-10-01 + source: consent_settings + granted_at: "2026-10-02T09:00:00Z" + revoked_at: "2026-10-04T18:30:00Z" + revocation_source: consent_settings + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + - id: 01928f7a-6f7a-7b8c-9d0e-1f2a3b4c5d50 + purpose: c1 + state: superseded + text_version: c1-2026-10-01 + source: registration + granted_at: "2026-10-01T08:00:00Z" + revoked_at: null + revocation_source: null + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + page: + has_more: false + next_cursor: null diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index 78ebf58..a70cbb2 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -1395,6 +1395,174 @@ SpecializationCatalog: description: Grade scale in ascending order. items: $ref: '#/CatalogGrade' +ConsentPurposeCode: + type: string + description: 'One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another. + + + - c1: processing of personal data, given at registration. + + - 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 (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change. + + - c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric. + + - c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance. + + - c5: import of FSP results. + + + ConsentPurpose lists the subset whose text the client may read before an account exists.' + enum: + - c1 + - c2 + - c3 + - c4 + - c5 +ConsentState: + type: string + description: 'State of a consent record, computed from the ledger. + + + - active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation. + + - superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4. + + - revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it.' + enum: + - active + - superseded + - revoked +ConsentSource: + type: string + description: 'Where the subject gave the consent. + + + - registration: the c1 acceptance of RegisterAccount. + + - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064). + + - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. + + + A c4 given when sending an application (PRD Q9) is planned as an additional value.' + enum: + - registration + - consent_settings + - invitation_acceptance +ConsentRevocationSource: + type: string + description: 'Who recorded a revocation. + + + - consent_settings: the subject revoked the consent in the product. + + - support_request: an operator recorded a revocation that the subject requested through support.' + enum: + - consent_settings + - support_request +ConsentOrganization: + type: object + description: 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 current name. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: Name of the organization in the consent text at the time of the consent. Plain text; clients show it as text, never as HTML. +ConsentRecord: + type: object + description: 'One record of the consent ledger as its subject reads it: the purpose, the text version the subject accepted, where and when the consent was given, its state, and the revocation. A c4 record also names the organization, the contact fields, and the invitation with its terms version; these fields are null for every other purpose. The server also stores the SHA-256 hash of exactly the text the subject saw, which a client never sends or receives.' + additionalProperties: false + required: + - id + - purpose + - state + - text_version + - source + - granted_at + - revoked_at + - revocation_source + - organization + - fields + - invitation_id + - invitation_terms_version + properties: + id: + type: string + format: uuid + description: Identifier of the record. + purpose: + $ref: '#/ConsentPurposeCode' + state: + $ref: '#/ConsentState' + text_version: + description: Version of the consent text that the subject accepted. + allOf: + - $ref: '#/ConsentTextVersion' + source: + $ref: '#/ConsentSource' + granted_at: + $ref: '#/Timestamp' + revoked_at: + description: Moment of the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + revocation_source: + description: Who recorded the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: '#/ConsentRevocationSource' + - type: 'null' + organization: + description: Organization that a c4 consent allows to read the fields, with the name the consent text showed, or null for every other purpose. + oneOf: + - $ref: '#/ConsentOrganization' + - type: 'null' + fields: + type: + - array + - 'null' + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies another. + items: + $ref: '#/ContactFieldKind' + invitation_id: + type: + - string + - 'null' + format: uuid + description: Invitation whose acceptance gave a c4 consent, or null for every other purpose. + invitation_terms_version: + description: Terms version that the acceptance accepted, or null for every other purpose. + oneOf: + - $ref: '#/InvitationTermsVersion' + - type: 'null' +ConsentRecordList: + type: object + description: One page of the consent ledger of the current account, newest grant first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Records of the page. + items: + $ref: '#/ConsentRecord' + page: + $ref: '#/PageInfo' 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. diff --git a/api/core/components/schemas/consent_schemas.yml b/api/core/components/schemas/consent_schemas.yml new file mode 100644 index 0000000..f8b7ce2 --- /dev/null +++ b/api/core/components/schemas/consent_schemas.yml @@ -0,0 +1,182 @@ +schemas: + ConsentPurposeCode: + type: string + description: |- + One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another. + + - c1: processing of personal data, given at registration. + - 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 (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change. + - c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric. + - c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance. + - c5: import of FSP results. + + ConsentPurpose lists the subset whose text the client may read before an account exists. + enum: + - c1 + - c2 + - c3 + - c4 + - c5 + ConsentState: + type: string + description: |- + State of a consent record, computed from the ledger. + + - active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation. + - superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4. + - revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it. + enum: + - active + - superseded + - revoked + ConsentSource: + type: string + description: |- + Where the subject gave the consent. + + - registration: the c1 acceptance of RegisterAccount. + - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064). + - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. + + A c4 given when sending an application (PRD Q9) is planned as an additional value. + enum: + - registration + - consent_settings + - invitation_acceptance + ConsentRevocationSource: + type: string + description: |- + Who recorded a revocation. + + - consent_settings: the subject revoked the consent in the product. + - support_request: an operator recorded a revocation that the subject requested through support. + enum: + - consent_settings + - support_request + ConsentOrganization: + type: object + description: >- + 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 current name. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: >- + Name of the organization in the consent text at the time of the + consent. Plain text; clients show it as text, never as HTML. + ConsentRecord: + type: object + description: >- + One record of the consent ledger as its subject reads it: the purpose, + the text version the subject accepted, where and when the consent was + given, its state, and the revocation. A c4 record also names the + organization, the contact fields, and the invitation with its terms + version; these fields are null for every other purpose. The server + also stores the SHA-256 hash of exactly the text the subject saw, + which a client never sends or receives. + additionalProperties: false + required: + - id + - purpose + - state + - text_version + - source + - granted_at + - revoked_at + - revocation_source + - organization + - fields + - invitation_id + - invitation_terms_version + properties: + id: + type: string + format: uuid + description: Identifier of the record. + purpose: + $ref: "#/schemas/ConsentPurposeCode" + state: + $ref: "#/schemas/ConsentState" + text_version: + description: Version of the consent text that the subject accepted. + allOf: + - $ref: "./identity_schemas.yml#/schemas/ConsentTextVersion" + source: + $ref: "#/schemas/ConsentSource" + granted_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + revoked_at: + description: Moment of the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + revocation_source: + description: Who recorded the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: "#/schemas/ConsentRevocationSource" + - type: "null" + organization: + description: >- + Organization that a c4 consent allows to read the fields, with the + name the consent text showed, or null for every other purpose. + oneOf: + - $ref: "#/schemas/ConsentOrganization" + - type: "null" + fields: + type: + - array + - "null" + minItems: 1 + maxItems: 4 + uniqueItems: true + description: >- + Contact fields that a c4 consent covers, or null for every other + purpose. One kind never implies another. + items: + $ref: "./contact_grant_schemas.yml#/schemas/ContactFieldKind" + invitation_id: + type: + - string + - "null" + format: uuid + description: >- + Invitation whose acceptance gave a c4 consent, or null for every + other purpose. + invitation_terms_version: + description: >- + Terms version that the acceptance accepted, or null for every + other purpose. + oneOf: + - $ref: "./invitation_schemas.yml#/schemas/InvitationTermsVersion" + - type: "null" + ConsentRecordList: + type: object + description: >- + One page of the consent ledger of the current account, newest grant + first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Records of the page. + items: + $ref: "#/schemas/ConsentRecord" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 100d676..b04d9a3 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -21,6 +21,8 @@ tags: description: 'Hiring needs of an organization: requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. Access comes only from an active membership in the organization; a need never requires a vacancy.' - name: invitation description: 'Invitations from an organization to one candidate: drafts with complete terms, immutable terms versions, sending, the candidate''s inbox, acceptance with the consent C4, structured declines, withdrawal and cancellation, and the contact grant. Contacts are readable only through an active grant, in a response separate from the terms.' + - name: consent + description: 'The consent ledger of the current account: the independent consents C1-C5 with their text versions, sources, states, and revocations. The ledger is append-only and returns only the caller''s own records.' - name: support description: 'Support cases of the current account: questions, complaints, appeals of a grade or an anti-cheat decision, and manual assessment requests. The author sees the number, the status, the response target, the decision, and the public history; moderators and internal notes stay hidden.' paths: @@ -1809,6 +1811,52 @@ paths: $ref: '#/components/responses/TooManyRequests' default: $ref: '#/components/responses/Problem' + /api/v1/me/consents: + get: + operationId: ListMyConsents + summary: List the consents of the current account with their history. + description: |- + Requires the session cookie of a candidate or an employer account. The subject comes from the session, never from a request parameter, so the response holds only the caller's own consents: no request can name another account, and records of other accounts are never listed. Returns a page of the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with cursor pagination. + + The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the source, and the grant time; the server also stores the hash of exactly the text the subject saw. A newer text version of the same purpose is a new record, and the earlier one becomes `superseded` without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one organization, once; a later grant is a new record. Purposes are independent. + + 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 (TASK-088). + + Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 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: + - sessionCookie: [] + tags: + - consent + parameters: + - name: state + in: query + required: false + description: Lists only the records in this state; omit it for the whole history. + schema: + $ref: '#/components/schemas/ConsentState' + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the consent ledger of the current account. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentRecordList' + examples: + history: + $ref: '#/components/examples/ConsentRecordListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + default: + $ref: '#/components/responses/Problem' /api/v1/me/support-cases: get: operationId: ListMySupportCases @@ -6236,6 +6284,163 @@ components: oneOf: - $ref: '#/components/schemas/ContactTelegramUsername' - type: 'null' + ConsentPurposeCode: + type: string + description: |- + One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another. + + - c1: processing of personal data, given at registration. + - 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 (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change. + - c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric. + - c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance. + - c5: import of FSP results. + + ConsentPurpose lists the subset whose text the client may read before an account exists. + enum: + - c1 + - c2 + - c3 + - c4 + - c5 + ConsentState: + type: string + description: |- + State of a consent record, computed from the ledger. + + - active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation. + - superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4. + - revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it. + enum: + - active + - superseded + - revoked + ConsentSource: + type: string + description: |- + Where the subject gave the consent. + + - registration: the c1 acceptance of RegisterAccount. + - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064). + - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. + + A c4 given when sending an application (PRD Q9) is planned as an additional value. + enum: + - registration + - consent_settings + - invitation_acceptance + ConsentRevocationSource: + type: string + description: |- + Who recorded a revocation. + + - consent_settings: the subject revoked the consent in the product. + - support_request: an operator recorded a revocation that the subject requested through support. + enum: + - consent_settings + - support_request + ConsentOrganization: + type: object + description: 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 current name. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: Name of the organization in the consent text at the time of the consent. Plain text; clients show it as text, never as HTML. + ConsentRecord: + type: object + description: 'One record of the consent ledger as its subject reads it: the purpose, the text version the subject accepted, where and when the consent was given, its state, and the revocation. A c4 record also names the organization, the contact fields, and the invitation with its terms version; these fields are null for every other purpose. The server also stores the SHA-256 hash of exactly the text the subject saw, which a client never sends or receives.' + additionalProperties: false + required: + - id + - purpose + - state + - text_version + - source + - granted_at + - revoked_at + - revocation_source + - organization + - fields + - invitation_id + - invitation_terms_version + properties: + id: + type: string + format: uuid + description: Identifier of the record. + purpose: + $ref: '#/components/schemas/ConsentPurposeCode' + state: + $ref: '#/components/schemas/ConsentState' + text_version: + description: Version of the consent text that the subject accepted. + allOf: + - $ref: '#/components/schemas/ConsentTextVersion' + source: + $ref: '#/components/schemas/ConsentSource' + granted_at: + $ref: '#/components/schemas/Timestamp' + revoked_at: + description: Moment of the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + revocation_source: + description: Who recorded the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: '#/components/schemas/ConsentRevocationSource' + - type: 'null' + organization: + description: Organization that a c4 consent allows to read the fields, with the name the consent text showed, or null for every other purpose. + oneOf: + - $ref: '#/components/schemas/ConsentOrganization' + - type: 'null' + fields: + type: + - array + - 'null' + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies another. + items: + $ref: '#/components/schemas/ContactFieldKind' + invitation_id: + type: + - string + - 'null' + format: uuid + description: Invitation whose acceptance gave a c4 consent, or null for every other purpose. + invitation_terms_version: + description: Terms version that the acceptance accepted, or null for every other purpose. + oneOf: + - $ref: '#/components/schemas/InvitationTermsVersion' + - type: 'null' + ConsentRecordList: + type: object + description: One page of the consent ledger of the current account, newest grant first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Records of the page. + items: + $ref: '#/components/schemas/ConsentRecord' + page: + $ref: '#/components/schemas/PageInfo' HealthResponse: type: object additionalProperties: false @@ -10012,6 +10217,65 @@ components: granted_at: '2026-10-06T15:00:00Z' revoked_at: '2026-10-07T10:00:00Z' revocation_reason: participation_cancelled + ConsentRecordListPage: + summary: The whole consent history of a candidate on one page + description: C1 was accepted at registration and again for a newer text version, so the first record is superseded; the version c1-2026-10-05 is an illustration, since the migration publishes only c1-2026-10-01 so far. C2 was granted and revoked. C4 was given in the acceptance of one invitation with the email only; the organization name is the one the consent text showed. + value: + items: + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + purpose: c4 + state: active + text_version: c4-2026-10-01 + source: invitation_acceptance + granted_at: '2026-10-06T10:15:00Z' + revoked_at: null + revocation_source: null + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + fields: + - email + invitation_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + invitation_terms_version: 3 + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + purpose: c1 + state: active + text_version: c1-2026-10-05 + source: consent_settings + granted_at: '2026-10-05T12:00:00Z' + revoked_at: null + revocation_source: null + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + purpose: c2 + state: revoked + text_version: c2-2026-10-01 + source: consent_settings + granted_at: '2026-10-02T09:00:00Z' + revoked_at: '2026-10-04T18:30:00Z' + revocation_source: consent_settings + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + - id: 01928f7a-6f7a-7b8c-9d0e-1f2a3b4c5d50 + purpose: c1 + state: superseded + text_version: c1-2026-10-01 + source: registration + granted_at: '2026-10-01T08:00:00Z' + revoked_at: null + revocation_source: null + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + page: + has_more: false + next_cursor: null SupportCaseListPage: summary: The last page of the case summaries of the current account value: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index c7ada19..194073a 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -40,6 +40,11 @@ tags: withdrawal and cancellation, and the contact grant. Contacts are readable only through an active grant, in a response separate from the terms. + - name: consent + description: >- + The consent ledger of the current account: the independent consents + C1-C5 with their text versions, sources, states, and revocations. The + ledger is append-only and returns only the caller's own records. - name: support description: >- Support cases of the current account: questions, complaints, appeals @@ -112,6 +117,8 @@ paths: $ref: ./routes/candidate_invitation_decline.yml /api/v1/me/invitations/{invitation_id}/cancel: $ref: ./routes/candidate_invitation_cancel.yml + /api/v1/me/consents: + $ref: ./routes/consents.yml /api/v1/me/support-cases: $ref: ./routes/support_cases.yml /api/v1/me/support-cases/{case_id}: @@ -578,6 +585,20 @@ components: $ref: ./components/schemas.yml#/ContactFullName ContactDisclosure: $ref: ./components/schemas.yml#/ContactDisclosure + ConsentPurposeCode: + $ref: ./components/schemas.yml#/ConsentPurposeCode + ConsentState: + $ref: ./components/schemas.yml#/ConsentState + ConsentSource: + $ref: ./components/schemas.yml#/ConsentSource + ConsentRevocationSource: + $ref: ./components/schemas.yml#/ConsentRevocationSource + ConsentOrganization: + $ref: ./components/schemas.yml#/ConsentOrganization + ConsentRecord: + $ref: ./components/schemas.yml#/ConsentRecord + ConsentRecordList: + $ref: ./components/schemas.yml#/ConsentRecordList parameters: IdempotencyKey: $ref: ./components/parameters.yml#/IdempotencyKey diff --git a/api/core/routes/consents.yml b/api/core/routes/consents.yml new file mode 100644 index 0000000..9bdfdae --- /dev/null +++ b/api/core/routes/consents.yml @@ -0,0 +1,45 @@ +get: + operationId: ListMyConsents + summary: List the consents of the current account with their history. + description: |- + Requires the session cookie of a candidate or an employer account. The subject comes from the session, never from a request parameter, so the response holds only the caller's own consents: no request can name another account, and records of other accounts are never listed. Returns a page of the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with cursor pagination. + + The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the source, and the grant time; the server also stores the hash of exactly the text the subject saw. A newer text version of the same purpose is a new record, and the earlier one becomes `superseded` without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one organization, once; a later grant is a new record. Purposes are independent. + + 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 (TASK-088). + + Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 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: + - sessionCookie: [] + tags: + - consent + parameters: + - name: state + in: query + required: false + description: Lists only the records in this state; omit it for the whole history. + schema: + $ref: ../components/schemas.yml#/ConsentState + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the consent ledger of the current account. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentRecordList + examples: + history: + $ref: ../components/examples.yml#/ConsentRecordListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + default: + $ref: ../components/responses.yml#/Problem diff --git a/backend/db/migrations/00009_create_consent_ledger.sql b/backend/db/migrations/00009_create_consent_ledger.sql new file mode 100644 index 0000000..767071d --- /dev/null +++ b/backend/db/migrations/00009_create_consent_ledger.sql @@ -0,0 +1,413 @@ +-- +goose Up +-- Versioned consent ledger for the independent consents C1-C5 (PRD FR01, +-- FR12, and 7.3): the published consent texts and an append-only record of +-- every grant and revocation. Purposes are independent: a grant or a +-- revocation of one purpose never changes another. +-- +-- consent_texts holds the published text of each purpose and version. A +-- grant references the text it was given for, so a client cannot invent a +-- version and the stored hash always belongs to a published text. +CREATE TABLE consent_texts ( + -- c1 personal data processing, c2 publication of the candidate card, c3 + -- automatic categorization, c4 transfer of selected contact data to one + -- organization, c5 import of FSP results. + purpose text NOT NULL, + -- Identifier that clients see as ConsentTextVersion, such as + -- "c1-2026-10-01". + version text NOT NULL, + -- Exact text in plain UTF-8. The C4 text contains the placeholder + -- {organization}, which the shown text replaces with the name of the + -- organization. + body text NOT NULL, + -- SHA-256 of the UTF-8 bytes of body, 32 raw bytes. + body_sha256 bytea NOT NULL, + -- "demo" marks a synthetic text for the demonstration on synthetic data + -- without a legal review; "operator" a text published by the actual + -- personal data operator, required before real data are accepted. + kind text NOT NULL, + -- The text applies to grants given at or after this time. The current + -- text of a purpose is the one with the latest published_at that is not + -- after the grant time. + published_at timestamptz NOT NULL, + CONSTRAINT consent_texts_pkey PRIMARY KEY (purpose, version), + -- Target of the hash binding of consent_records. + CONSTRAINT consent_texts_purpose_version_body_sha256_key UNIQUE ( + purpose, version, body_sha256 + ), + CONSTRAINT consent_texts_purpose_published_at_key UNIQUE ( + purpose, published_at + ), + CONSTRAINT consent_texts_purpose_known CHECK ( + purpose IN ('c1', 'c2', 'c3', 'c4', 'c5') + ), + CONSTRAINT consent_texts_version_format CHECK ( + version ~ '^[A-Za-z0-9._-]{1,64}$' + ), + CONSTRAINT consent_texts_body_length CHECK ( + char_length(body) BETWEEN 1 AND 100000 + ), + -- The database encoding is fixed for the life of a database, so + -- convert_to gives the same bytes on every evaluation. + CONSTRAINT consent_texts_body_sha256_matches CHECK ( + body_sha256 = sha256(convert_to(body, 'UTF8')) + ), + -- Only the C4 text names an organization. + CONSTRAINT consent_texts_organization_placeholder CHECK ( + (purpose = 'c4') = (strpos(body, '{organization}') > 0) + ), + CONSTRAINT consent_texts_kind_known CHECK (kind IN ('demo', 'operator')) +); + +-- Refuses every UPDATE, DELETE, and TRUNCATE of consent texts: a grant +-- proves which text the subject saw only while that text stays unchanged. +-- A changed text is a new version. The error uses SQLSTATE 23000 and the +-- constraint name consent_texts_immutable, which the adapter maps without +-- reading the message. +-- +goose StatementBegin +CREATE FUNCTION consent_texts_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'consent_texts_immutable', + TABLE = 'consent_texts', + MESSAGE = 'consent texts are immutable: publish a new version instead'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_texts_refuse_update_delete +BEFORE UPDATE OR DELETE ON consent_texts +FOR EACH ROW EXECUTE FUNCTION consent_texts_refuse_change(); + +CREATE TRIGGER consent_texts_refuse_truncate +BEFORE TRUNCATE ON consent_texts +FOR EACH STATEMENT EXECUTE FUNCTION consent_texts_refuse_change(); + +-- Demonstration texts, version 1 of every purpose. They are synthetic and +-- carry no legal review; the operator publishes its own texts as new +-- versions in a later migration before real data are accepted (PRD 7.3). +INSERT INTO consent_texts ( + purpose, version, body, body_sha256, kind, published_at +) +SELECT + seed.purpose, + seed.version, + seed.body, + sha256(convert_to(seed.body, 'UTF8')), + 'demo', + '2026-10-01T00:00:00Z'::timestamptz +FROM ( + VALUES + ( + 'c1', + 'c1-2026-10-01', + 'I consent to the processing of my personal data for registration ' + || 'and the use of the service.' || E'\n\n' + || 'The full text is published by the operator.' + ), + ( + 'c2', + 'c2-2026-10-01', + 'I consent to the publication of my candidate card with the fields ' + || 'I select in the publication settings.' || E'\n\n' + || 'The full text is published by the operator.' + ), + ( + 'c3', + 'c3-2026-10-01', + 'I consent to the automatic categorization of my assessment ' + || 'results. Without this consent I can request a manual assessment ' + || 'by the same rubric.' || E'\n\n' + || 'The full text is published by the operator.' + ), + ( + 'c4', + 'c4-2026-10-01', + 'I consent to the transfer of the contact data I select to ' + || '{organization} for this invitation.' || E'\n\n' + || 'The full text is published by the operator.' + ), + ( + 'c5', + 'c5-2026-10-01', + 'I consent to the import of my FSP results into my profile.' + || E'\n\n' + || 'The full text is published by the operator.' + ) +) AS seed (purpose, version, body); + +-- Reports whether a C4 field set is canonical: one to four distinct known +-- contact kinds (ContactFieldKind) in ascending byte order without NULLs. +-- A canonical form makes equal sets equal arrays. +-- +goose StatementBegin +CREATE FUNCTION consent_field_set_is_canonical(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + array_ndims(fields) = 1 + AND cardinality(fields) BETWEEN 1 AND 4 + AND array_position(fields, NULL) IS NULL + AND fields <@ ARRAY['email', 'full_name', 'phone', 'telegram']::text [] + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd + +-- One row per grant. A grant is never updated except for the one-time +-- revocation stamp: a new text version or a grant after a revocation is a +-- new row, so the history of a purpose is the sequence of its rows. Every +-- time comes from the application clock. +-- +-- The rows are personal data of the subject: never copy them into logs, +-- metrics, or events beyond the record ID and purpose. +CREATE TABLE consent_records ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + -- The account that gave the consent. + subject_id uuid NOT NULL, + purpose text NOT NULL, + text_version text NOT NULL, + -- SHA-256 of exactly the text the subject saw, 32 raw bytes. For C1-C3 + -- and C5 it equals the hash of the published text; for C4 it is the + -- hash of the published text with organization_name filled in, which a + -- trigger checks. + text_hash bytea NOT NULL, + -- The hash that must equal the published text: text_hash except for + -- C4, NULL for C4, so the composite foreign key below skips C4. + published_text_hash bytea GENERATED ALWAYS AS ( + CASE WHEN purpose <> 'c4' THEN text_hash END + ) STORED, + -- Where the grant was given: registration (C1 only), consent_settings + -- (C1-C3 and C5), or invitation_acceptance (C4 only). + source text NOT NULL, + -- C4 scope: the organization, the name of the organization as the + -- shown text named it (a snapshot that a later rename never changes), + -- the canonical set of contact kinds, and the invitation and its terms + -- version that the acceptance accepted. NULL for every other purpose. + -- The organization and invitation tables do not exist yet; their + -- foreign keys arrive with them. + organization_id uuid, + organization_name text, + field_set text [], + invitation_id uuid, + invitation_terms_version bigint, + granted_at timestamptz NOT NULL, + -- Set once; the row is never updated again. + revoked_at timestamptz, + -- consent_settings: the subject revoked it in the product; + -- support_request: an operator recorded a revocation the subject asked + -- for through support. + revocation_source text, + CONSTRAINT consent_records_pkey PRIMARY KEY (id), + -- Consent evidence must outlive a careless account delete: an account + -- with consent history cannot be deleted until the deleting procedure + -- handles the ledger explicitly (PRD 7.3 keeps consents for three + -- years). The unverified account cleanup deletes the records of the + -- accounts it removes in the same statement, and the re-registration of + -- an unverified account deletes its registration C1. + CONSTRAINT consent_records_subject_id_fkey FOREIGN KEY (subject_id) + REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT consent_records_text_fkey FOREIGN KEY ( + purpose, text_version + ) REFERENCES consent_texts (purpose, version), + -- MATCH SIMPLE skips the check when published_text_hash is NULL (C4). + CONSTRAINT consent_records_published_text_fkey FOREIGN KEY ( + purpose, text_version, published_text_hash + ) REFERENCES consent_texts (purpose, version, body_sha256), + CONSTRAINT consent_records_purpose_known CHECK ( + purpose IN ('c1', 'c2', 'c3', 'c4', 'c5') + ), + CONSTRAINT consent_records_text_version_format CHECK ( + text_version ~ '^[A-Za-z0-9._-]{1,64}$' + ), + CONSTRAINT consent_records_text_hash_sha256 CHECK ( + octet_length(text_hash) = 32 + ), + CONSTRAINT consent_records_source_of_purpose CHECK ( + (purpose = 'c1' AND source IN ('registration', 'consent_settings')) + OR (purpose IN ('c2', 'c3', 'c5') AND source = 'consent_settings') + OR (purpose = 'c4' AND source = 'invitation_acceptance') + ), + -- C4 always has its scope; no other purpose has one. + CONSTRAINT consent_records_c4_scope CHECK ( + ( + purpose = 'c4' + AND organization_id IS NOT NULL + AND organization_name IS NOT NULL + AND char_length(organization_name) BETWEEN 1 AND 200 + AND organization_name !~ '[[:cntrl:]]' + AND field_set IS NOT NULL + AND consent_field_set_is_canonical(field_set) + AND invitation_id IS NOT NULL + AND invitation_terms_version IS NOT NULL + AND invitation_terms_version > 0 + ) + OR ( + purpose <> 'c4' + AND organization_id IS NULL + AND organization_name IS NULL + AND field_set IS NULL + AND invitation_id IS NULL + AND invitation_terms_version IS NULL + ) + ), + CONSTRAINT consent_records_revocation_stamp CHECK ( + (revoked_at IS NULL) = (revocation_source IS NULL) + AND ( + revocation_source IS NULL + OR revocation_source IN ('consent_settings', 'support_request') + ) + AND (revoked_at IS NULL OR revoked_at >= granted_at) + ) +); + +-- Serves the subject's history, newest first, and the foreign key from +-- users. +CREATE INDEX consent_records_subject_granted_idx +ON consent_records (subject_id, granted_at DESC, id DESC); + +-- One unrevoked grant per subject, purpose, and text version: repeating a +-- grant of the same version returns the existing record. A newer version is +-- a new row next to the older one. +CREATE UNIQUE INDEX consent_records_active_version_key +ON consent_records (subject_id, purpose, text_version) +WHERE revoked_at IS NULL AND purpose <> 'c4'; + +-- One C4 grant per invitation, revoked or not: a repeated acceptance +-- returns the existing record, and a revoked C4 never comes back. +CREATE UNIQUE INDEX consent_records_invitation_key +ON consent_records (invitation_id) +WHERE invitation_id IS NOT NULL; + +-- Serves the current C4 grants of a subject for one organization and their +-- revocation. +CREATE INDEX consent_records_active_organization_idx +ON consent_records (subject_id, organization_id) +WHERE purpose = 'c4' AND revoked_at IS NULL; + +-- Refuses a grant for a text version that is not published at the grant +-- time (SQLSTATE 23514, constraint consent_records_text_published) and a C4 +-- grant whose hash is not the hash of the published text with its +-- organization_name filled in (23514, consent_records_c4_text_hash). A +-- version that does not exist at all is left to the foreign key, and a C4 +-- row without a name to consent_records_c4_scope. +-- +goose StatementBegin +CREATE FUNCTION consent_records_require_published_text() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM consent_texts AS text + WHERE + text.purpose = NEW.purpose + AND text.version = NEW.text_version + AND text.published_at > NEW.granted_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'consent_records_text_published', + TABLE = 'consent_records', + MESSAGE = 'the consent text is not published at the grant time'; + END IF; + IF NEW.purpose = 'c4' AND NEW.organization_name IS NOT NULL AND EXISTS ( + SELECT 1 FROM consent_texts AS text + WHERE + text.purpose = NEW.purpose + AND text.version = NEW.text_version + AND sha256(convert_to( + replace(text.body, '{organization}', NEW.organization_name), + 'UTF8' + )) IS DISTINCT FROM NEW.text_hash + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'consent_records_c4_text_hash', + TABLE = 'consent_records', + MESSAGE = 'the C4 hash does not match the published text for the organization name'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_records_require_published_text +BEFORE INSERT ON consent_records +FOR EACH ROW EXECUTE FUNCTION consent_records_require_published_text(); + +-- Allows exactly one UPDATE of a record: setting revoked_at and +-- revocation_source on an unrevoked record, with every other column +-- unchanged. Every other UPDATE is refused with SQLSTATE 23000 and the +-- constraint name consent_records_immutable; the message quotes no row +-- values. Deletes are guarded separately below. +-- +goose StatementBegin +CREATE FUNCTION consent_records_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.revoked_at IS NOT NULL + OR NEW.revoked_at IS NULL + OR ( + NEW.id, NEW.subject_id, NEW.purpose, NEW.text_version, + NEW.text_hash, NEW.source, NEW.organization_id, + NEW.organization_name, NEW.field_set, + NEW.invitation_id, NEW.invitation_terms_version, NEW.granted_at + ) IS DISTINCT FROM ( + OLD.id, OLD.subject_id, OLD.purpose, OLD.text_version, + OLD.text_hash, OLD.source, OLD.organization_id, + OLD.organization_name, OLD.field_set, + OLD.invitation_id, OLD.invitation_terms_version, OLD.granted_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'consent_records_immutable', + TABLE = 'consent_records', + MESSAGE = 'consent records are append-only: only an unrevoked record can be revoked, once'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_records_refuse_change +BEFORE UPDATE ON consent_records +FOR EACH ROW EXECUTE FUNCTION consent_records_refuse_change(); + +-- Allows deleting a record only while its subject is not a confirmed +-- account: the unverified account cleanup and the re-registration of an +-- unverified account. The ledger of a confirmed account is consent +-- evidence and stays (SQLSTATE 23000, constraint consent_records_retained). +-- The retention rule for consents (PRD 7.3, three years) and the account +-- deletion procedure will extend this condition in their own migration. +-- TRUNCATE fires no row trigger and stays allowed for test isolation. +-- +goose StatementBegin +CREATE FUNCTION consent_records_refuse_delete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM users + WHERE users.id = OLD.subject_id AND users.email_verified_at IS NOT NULL + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'consent_records_retained', + TABLE = 'consent_records', + MESSAGE = 'consent records of a confirmed account are retained'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_records_refuse_delete +BEFORE DELETE ON consent_records +FOR EACH ROW EXECUTE FUNCTION consent_records_refuse_delete(); + +-- +goose Down +DROP TABLE consent_records; +DROP TABLE consent_texts; +DROP FUNCTION consent_records_refuse_delete(); +DROP FUNCTION consent_records_refuse_change(); +DROP FUNCTION consent_records_require_published_text(); +DROP FUNCTION consent_field_set_is_canonical(text []); +DROP FUNCTION consent_texts_refuse_change(); diff --git a/backend/db/queries/consents.sql b/backend/db/queries/consents.sql new file mode 100644 index 0000000..214d497 --- /dev/null +++ b/backend/db/queries/consents.sql @@ -0,0 +1,377 @@ +-- name: GetConsentText :one +SELECT + purpose, + version, + body, + body_sha256, + kind, + published_at +FROM consent_texts +WHERE + purpose = sqlc.arg(purpose) + AND version = sqlc.arg(version); + +-- The text of a purpose that applies at a time: the latest publication not +-- after it. +-- name: GetCurrentConsentText :one +SELECT + purpose, + version, + body, + body_sha256, + kind, + published_at +FROM consent_texts +WHERE + purpose = sqlc.arg(purpose) + AND published_at <= sqlc.arg(at) +ORDER BY published_at DESC +LIMIT 1; + +-- Records a grant of C1, C2, C3, or C5. An unrevoked record of the same +-- subject, purpose, and text version already exists when no row returns; +-- the insert then changes nothing and does not abort the transaction. +-- name: InsertConsentRecord :one +INSERT INTO consent_records ( + id, + subject_id, + purpose, + text_version, + text_hash, + source, + granted_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(subject_id), + sqlc.arg(purpose), + sqlc.arg(text_version), + sqlc.arg(text_hash), + sqlc.arg(source), + sqlc.arg(granted_at) +) +ON CONFLICT (subject_id, purpose, text_version) +WHERE revoked_at IS NULL AND purpose <> 'c4' +DO NOTHING +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + ( + CASE + WHEN exists( + SELECT 1 FROM consent_records AS newer + WHERE + newer.subject_id = consent_records.subject_id + AND newer.purpose = consent_records.purpose + AND newer.revoked_at IS NULL + AND (newer.granted_at, newer.id) + > (consent_records.granted_at, consent_records.id) + ) THEN 'superseded' + ELSE 'active' + END + )::text AS state; + +-- Records a C4 grant with its scope. The invitation already has a C4 record +-- when no row returns; the insert then changes nothing and does not abort +-- the transaction. +-- name: InsertContactConsentRecord :one +INSERT INTO consent_records ( + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(subject_id), + 'c4', + sqlc.arg(text_version), + sqlc.arg(text_hash), + 'invitation_acceptance', + sqlc.arg(organization_id), + sqlc.arg(organization_name), + sqlc.arg(field_set)::text [], + sqlc.arg(invitation_id), + sqlc.arg(invitation_terms_version), + sqlc.arg(granted_at) +) +ON CONFLICT (invitation_id) WHERE invitation_id IS NOT NULL +DO NOTHING +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state; + +-- name: GetUnrevokedConsentRecordByVersion :one +SELECT + record.id, + record.subject_id, + record.purpose, + record.text_version, + record.text_hash, + record.source, + record.organization_id, + record.organization_name, + record.field_set, + record.invitation_id, + record.invitation_terms_version, + record.granted_at, + record.revoked_at, + record.revocation_source, + ( + CASE + WHEN exists( + SELECT 1 FROM consent_records AS newer + WHERE + newer.subject_id = record.subject_id + AND newer.purpose = record.purpose + AND newer.revoked_at IS NULL + AND (newer.granted_at, newer.id) + > (record.granted_at, record.id) + ) THEN 'superseded' + ELSE 'active' + END + )::text AS state +FROM consent_records AS record +WHERE + record.subject_id = sqlc.arg(subject_id) + AND record.purpose = sqlc.arg(purpose) + AND record.text_version = sqlc.arg(text_version) + AND record.revoked_at IS NULL; + +-- name: GetContactConsentRecordByInvitation :one +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + ( + CASE WHEN revoked_at IS NULL THEN 'active' ELSE 'revoked' END + )::text AS state +FROM consent_records +WHERE + subject_id = sqlc.arg(subject_id) + AND invitation_id = sqlc.arg(invitation_id); + +-- The newest unrevoked record of a purpose other than C4. +-- name: GetCurrentConsentRecord :one +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state +FROM consent_records +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = sqlc.arg(purpose) + AND purpose <> 'c4' + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC +LIMIT 1; + +-- name: ListCurrentContactConsentRecords :many +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state +FROM consent_records +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = 'c4' + AND organization_id = sqlc.arg(organization_id) + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC; + +-- Revokes every unrevoked record of a purpose other than C4, superseded ones +-- included, and returns them. A revocation time before the grant time, from +-- clock skew between instances, is stamped at the grant time instead. +-- name: RevokeConsentRecords :many +UPDATE consent_records +SET + revoked_at = greatest(sqlc.arg(revoked_at)::timestamptz, granted_at), + revocation_source = sqlc.arg(revocation_source) +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = sqlc.arg(purpose) + AND purpose <> 'c4' + AND revoked_at IS NULL +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'revoked'::text AS state; + +-- Revokes every unrevoked C4 record of the subject for one organization and +-- returns them, with the same clamp of the revocation time as above. +-- name: RevokeContactConsentRecords :many +UPDATE consent_records +SET + revoked_at = greatest(sqlc.arg(revoked_at)::timestamptz, granted_at), + revocation_source = sqlc.arg(revocation_source) +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = 'c4' + AND organization_id = sqlc.arg(organization_id) + AND revoked_at IS NULL +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'revoked'::text AS state; + +-- One page of the subject's ledger, newest grant first, optionally limited +-- to one state. Every record query is scoped by the subject, so a caller +-- never reads or revokes another subject's consent. The state is computed, +-- never stored: revoked once revoked_at is set; superseded when a newer +-- unrevoked record of the same subject and purpose exists (never for C4, +-- whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of +-- the last record of the previous page. +-- name: ListConsentRecords :many +WITH ledger AS ( + SELECT + record.id, + record.subject_id, + record.purpose, + record.text_version, + record.text_hash, + record.source, + record.organization_id, + record.organization_name, + record.field_set, + record.invitation_id, + record.invitation_terms_version, + record.granted_at, + record.revoked_at, + record.revocation_source, + ( + CASE + WHEN record.revoked_at IS NOT NULL THEN 'revoked' + WHEN record.purpose <> 'c4' AND exists( + SELECT 1 FROM consent_records AS newer + WHERE + newer.subject_id = record.subject_id + AND newer.purpose = record.purpose + AND newer.revoked_at IS NULL + AND (newer.granted_at, newer.id) + > (record.granted_at, record.id) + ) THEN 'superseded' + ELSE 'active' + END + )::text AS state + FROM consent_records AS record + WHERE record.subject_id = sqlc.arg(subject_id) +) + +SELECT + ledger.id, + ledger.subject_id, + ledger.purpose, + ledger.text_version, + ledger.text_hash, + ledger.source, + ledger.organization_id, + ledger.organization_name, + ledger.field_set, + ledger.invitation_id, + ledger.invitation_terms_version, + ledger.granted_at, + ledger.revoked_at, + ledger.revocation_source, + ledger.state +FROM ledger +WHERE + (sqlc.narg(state)::text IS NULL OR ledger.state = sqlc.narg(state)::text) + AND ( + sqlc.narg(after_granted_at)::timestamptz IS NULL + OR (ledger.granted_at, ledger.id) < ( + sqlc.narg(after_granted_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY ledger.granted_at DESC, ledger.id DESC +LIMIT sqlc.arg(row_limit); diff --git a/backend/db/queries/identity.sql b/backend/db/queries/identity.sql index 098d4b7..496a134 100644 --- a/backend/db/queries/identity.sql +++ b/backend/db/queries/identity.sql @@ -64,35 +64,64 @@ WHERE email_normalized = sqlc.arg(email_normalized); -- Replaces the registration of an unverified account and advances the -- registration version in the same statement, so no caller can choose it. -- The version check rejects a writer that read an older row; a verified --- account never changes. +-- account never changes. The same statement deletes the C1 that the earlier +-- registration of this account recorded, so the consent of an earlier +-- registrant never stands for the new one; the new registration records its +-- own C1 in the same transaction. A version conflict deletes nothing. -- name: UpdateUserRegistration :one -UPDATE users -SET - email = sqlc.arg(email), - password_hash = sqlc.arg(password_hash), - scenario = sqlc.arg(scenario), - onboarding_step = sqlc.arg(onboarding_step), - registration_version = registration_version + 1, - last_registered_at = sqlc.arg(last_registered_at), - updated_at = sqlc.arg(updated_at), - version = version + 1 -WHERE - id = sqlc.arg(id) - AND version = sqlc.arg(expected_version) - AND email_verified_at IS NULL -RETURNING - id, - email, - email_normalized, - password_hash, - scenario, - onboarding_step, - email_verified_at, - registration_version, - last_registered_at, - version, - created_at, - updated_at; +WITH updated AS ( + UPDATE users + SET + email = sqlc.arg(email), + password_hash = sqlc.arg(password_hash), + scenario = sqlc.arg(scenario), + onboarding_step = sqlc.arg(onboarding_step), + registration_version = registration_version + 1, + last_registered_at = sqlc.arg(last_registered_at), + updated_at = sqlc.arg(updated_at), + version = version + 1 + WHERE + users.id = sqlc.arg(id) + AND users.version = sqlc.arg(expected_version) + AND users.email_verified_at IS NULL + RETURNING + users.id, + users.email, + users.email_normalized, + users.password_hash, + users.scenario, + users.onboarding_step, + users.email_verified_at, + users.registration_version, + users.last_registered_at, + users.version, + users.created_at, + users.updated_at +), + +discarded_consent AS ( + DELETE FROM consent_records + USING updated + WHERE + consent_records.subject_id = updated.id + AND consent_records.purpose = 'c1' + AND consent_records.source = 'registration' +) + +SELECT + updated.id, + updated.email, + updated.email_normalized, + updated.password_hash, + updated.scenario, + updated.onboarding_step, + updated.email_verified_at, + updated.registration_version, + updated.last_registered_at, + updated.version, + updated.created_at, + updated.updated_at +FROM updated; -- Verifies the email only for the registration version the consumed token -- was issued for. @@ -121,14 +150,17 @@ RETURNING updated_at; -- Deletes one batch of accounts that stayed unverified since before cutoff, --- oldest first, with their tokens, sessions, mail requests, and mail --- deliveries (and through the deliveries their attempts). Every lock is taken +-- oldest first, with their tokens, sessions, mail requests, mail deliveries +-- (and through the deliveries their attempts), and consent records. The +-- consent records reference the account with ON DELETE RESTRICT, so they are +-- deleted explicitly in the same statement: a registration never confirmed +-- by its email owner is not kept as consent evidence. Every lock is taken -- with SKIP LOCKED, so the statement never waits: an account whose row is --- locked, for example by a re-registration, a token insert, or a delivery --- insert, is skipped, and so is an account with any token, session, mail --- request, or delivery row locked, for example by a confirmation that --- consumed a token, the delivery consumer, or a worker recording an attempt. --- Skipped accounts stay for the next run. +-- locked, for example by a re-registration, a token insert, a delivery +-- insert, or a consent insert, is skipped, and so is an account with any +-- token, session, mail request, delivery, or consent row locked, for example +-- by a confirmation that consumed a token, the delivery consumer, or a +-- worker recording an attempt. Skipped accounts stay for the next run. -- Taking the account lock before the token locks is the reverse of the -- documented order, which is safe only because no lock here waits. -- name: DeleteUnverifiedUsersRegisteredBefore :execrows @@ -171,8 +203,15 @@ locked_delivery AS ( FOR UPDATE SKIP LOCKED ), --- An account qualifies only when every token, session, mail request, and --- delivery row visible to the statement was locked above. +locked_consent AS ( + SELECT consent.subject_id + FROM consent_records AS consent + WHERE consent.subject_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +-- An account qualifies only when every token, session, mail request, +-- delivery, and consent row visible to the statement was locked above. deletable AS ( SELECT candidate.id FROM candidate @@ -205,6 +244,21 @@ deletable AS ( SELECT count(*) FROM locked_delivery WHERE locked_delivery.recipient_user_id = candidate.id ) + AND ( + SELECT count(*) FROM consent_records AS consent + WHERE consent.subject_id = candidate.id + ) = ( + SELECT count(*) FROM locked_consent + WHERE locked_consent.subject_id = candidate.id + ) +), + +-- The restricting foreign key is checked at the end of the statement, after +-- these rows are gone. +deleted_consent AS ( + DELETE FROM consent_records + USING deletable + WHERE consent_records.subject_id = deletable.id ) DELETE FROM users diff --git a/backend/integration_test/consent_ledger_test.go b/backend/integration_test/consent_ledger_test.go new file mode 100644 index 0000000..beca907 --- /dev/null +++ b/backend/integration_test/consent_ledger_test.go @@ -0,0 +1,984 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "slices" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + consentTestTimeout = 3 * time.Minute + // consentDemoVersionSuffix completes the version of every demo text that + // migration 00009 publishes, such as "c1-2026-10-01". + consentDemoVersionSuffix = "-2026-10-01" + // consentSecondC1Body is a later C1 text that the test publishes the + // way a migration would, as consentSecondC1Version. + consentSecondC1Body = "I consent to the processing of my personal data, version two." + consentOrganizationName = "Acme Synthetic LLC" + consentPageSize = 10 + // concurrentConsentGrants grants one version at once, each on its own + // connection. + concurrentConsentGrants = 8 + consentRaceRounds = 20 + consentCheckViolation = "23514" + consentForeignKeyViolation = "23503" + consentIntegrityViolation = "23000" + // consentRestrictViolation is raised by ON DELETE RESTRICT. + consentRestrictViolation = "23001" +) + +const consentSecondC1Version domain.ConsentTextVersion = "c1-2026-10-05" + +var ( + consentRecordsTable = pgx.Identifier{"consent_records"} + // consentTables reference users, so every TRUNCATE of users names them. + consentTables = []pgx.Identifier{consentRecordsTable} +) + +// consentFixture works on the bootstrap database. The ledger rows are +// truncated between subtests; the published texts are immutable and shared. +type consentFixture struct { + ctx context.Context + pool *pgxpool.Pool + identity identityFixture + store *postgresadapter.ConsentStore + transactor *postgresadapter.Transactor + // now is a fixed application time after every published text, truncated + // to microseconds like the stored times. + now time.Time +} + +func TestConsentLedger(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), consentTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + fixture := consentFixture{ + ctx: ctx, + pool: pool, + identity: identityFixture{ + ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now, + }, + store: postgresadapter.NewConsentStore(pool), + transactor: postgresadapter.NewTransactor(pool), + now: now, + } + // A second C1 text, published as a migration would publish it. + if _, err := pool.Exec(ctx, ` + INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at) + VALUES ('c1', $1, $2, sha256(convert_to($2, 'UTF8')), 'demo', $3)`, + string(consentSecondC1Version), consentSecondC1Body, now.Add(-24*time.Hour)); err != nil { + t.Fatalf("publish the second C1 text: %v", err) + } + reset := func(t *testing.T) { + t.Helper() + // Every table that references users must be truncated with it. + truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables, consentTables)...) + } + + t.Run("migration publishes one demo text per purpose bound to its hash", func(t *testing.T) { + texts := fixture.store.ConsentTexts() + for _, purpose := range []domain.ConsentPurpose{"c2", "c3", "c4", "c5"} { + text, err := texts.Current(ctx, purpose, now) + if err != nil { + t.Fatalf("Current(%s) error = %v", purpose, err) + } + if string(text.Version()) != string(purpose)+consentDemoVersionSuffix || text.Kind() != domain.ConsentTextKindDemo || + text.Hash() != domain.HashConsentText(text.Body()) { + t.Fatalf("Current(%s) = %s %s %x, want the demo text with its hash", purpose, text.Version(), text.Kind(), text.Hash()) + } + } + current, err := texts.Current(ctx, domain.ConsentPurposePersonalData, now) + if err != nil || current.Version() != consentSecondC1Version { + t.Fatalf("Current(c1) = %s, %v, want the later publication", current.Version(), err) + } + first, err := texts.Current(ctx, domain.ConsentPurposePersonalData, now.Add(-48*time.Hour)) + if err != nil || first.Version() != "c1-2026-10-01" { + t.Fatalf("Current(c1, before the second text) = %s, %v, want c1-2026-10-01", first.Version(), err) + } + if _, err := texts.Current(ctx, domain.ConsentPurposePersonalData, time.Date(2026, 9, 30, 0, 0, 0, 0, time.UTC)); !errors.Is(err, outbound.ErrConsentTextNotFound) { + t.Fatalf("Current(before every text) error = %v, want ErrConsentTextNotFound", err) + } + if _, err := texts.Get(ctx, domain.ConsentPurposePublication, "c2-1999-01-01"); !errors.Is(err, outbound.ErrConsentTextNotFound) { + t.Fatalf("Get(unknown version) error = %v, want ErrConsentTextNotFound", err) + } + // A version belongs to its purpose. + if _, err := texts.Get(ctx, domain.ConsentPurposePublication, "c1-2026-10-01"); !errors.Is(err, outbound.ErrConsentTextNotFound) { + t.Fatalf("Get(version of another purpose) error = %v, want ErrConsentTextNotFound", err) + } + }) + + t.Run("versions and purposes keep their own history", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "history@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + firstC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-72*time.Hour)) + publication := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now.Add(-2*time.Hour)) + before := fixture.rawRecord(t, firstC1.ID()) + secondC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, consentSecondC1Version, domain.ConsentSourceConsentSettings, now.Add(-time.Hour)) + + if before != fixture.rawRecord(t, firstC1.ID()) { + t.Fatal("a newer version changed the stored record of the earlier version") + } + current, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposePersonalData) + if err != nil || current.ID() != secondC1.ID() { + t.Fatalf("Current(c1) = %s, %v, want the newer version", current, err) + } + page := fixture.list(t, subject.ID, "") + assertConsentIDs(t, page.Records, secondC1.ID(), publication.ID(), firstC1.ID()) + assertConsentStates(t, page, domain.ConsentStateActive, domain.ConsentStateActive, domain.ConsentStateSuperseded) + + // Repeating a grant of a version that is still unrevoked stores nothing. + grant := fixture.newGrant(t, subject.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceConsentSettings, now) + repeated, created, err := ledger.Grant(ctx, grant) + if err != nil || created || repeated.ID() != firstC1.ID() || repeated.State() != domain.ConsentStateSuperseded { + t.Fatalf("Grant(repeat) = %s, %v, %v, want the existing superseded record", repeated, created, err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 3) + + // Purposes are independent: revoking C2 leaves C1 as it was. + revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePublication, uuid.Nil, now) + assertConsentIDs(t, revoked, publication.ID()) + if current, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposePersonalData); err != nil || current.ID() != secondC1.ID() { + t.Fatalf("Current(c1) after revoking C2 = %s, %v, want it unchanged", current, err) + } + }) + + t.Run("revocation stamps once and a new grant is a new record", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "revoke@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + first := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, "c3-2026-10-01", domain.ConsentSourceConsentSettings, now.Add(-time.Hour)) + + revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, uuid.Nil, now) + assertConsentIDs(t, revoked, first.ID()) + if revokedAt, ok := revoked[0].RevokedAt(); !ok || !revokedAt.Equal(now) || revoked[0].RevocationSource() != domain.ConsentRevocationSourceConsentSettings { + t.Fatalf("revocation = %v %v %q, want the stamp", revokedAt, ok, revoked[0].RevocationSource()) + } + // A repeat finds nothing to revoke and keeps the first stamp. + if again := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, uuid.Nil, now.Add(time.Minute)); len(again) != 0 { + t.Fatalf("second Revoke() = %v, want nothing", again) + } + if _, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposeAutoCategorization); !errors.Is(err, outbound.ErrConsentNotFound) { + t.Fatalf("Current(revoked) error = %v, want ErrConsentNotFound", err) + } + + regranted := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, "c3-2026-10-01", domain.ConsentSourceConsentSettings, now.Add(2*time.Minute)) + if regranted.ID() == first.ID() { + t.Fatal("a grant after a revocation reused the revoked record") + } + page := fixture.list(t, subject.ID, "") + assertConsentIDs(t, page.Records, regranted.ID(), first.ID()) + assertConsentStates(t, page, domain.ConsentStateActive, domain.ConsentStateRevoked) + if revokedAt, _ := page.Records[1].RevokedAt(); !revokedAt.Equal(now) { + t.Fatalf("revoked record stamp = %v, want the first revocation %v", revokedAt, now) + } + + // Revoking a purpose closes superseded records too. + olderC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-48*time.Hour)) + newerC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, consentSecondC1Version, domain.ConsentSourceConsentSettings, now) + closed := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePersonalData, uuid.Nil, now.Add(time.Hour)) + if len(closed) != 2 || !slices.ContainsFunc(closed, func(r domain.ConsentRecord) bool { return r.ID() == olderC1.ID() }) || + !slices.ContainsFunc(closed, func(r domain.ConsentRecord) bool { return r.ID() == newerC1.ID() }) { + t.Fatalf("Revoke(c1) = %v, want both C1 records", closed) + } + }) + + t.Run("C4 requires its scope and records it once per invitation", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "contact@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + other := fixture.identity.createUser(t, "other-contact@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + organization, otherOrganization := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + invitation := uuid.Must(uuid.NewV7()) + + // The generic grant refuses C4, and the scoped grant refuses a missing scope. + if _, err := domain.NewConsentGrant(domain.ConsentGrantInput{ + SubjectID: subject.ID, Purpose: domain.ConsentPurposeContactDisclosure, TextVersion: "c4-2026-10-01", + TextHash: domain.HashConsentText("x"), Source: domain.ConsentSourceInvitationAcceptance, GrantedAt: now, + }); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("NewConsentGrant(C4) error = %v, want ErrInvalidConsent", err) + } + if _, err := domain.NewContactConsentGrant(domain.ContactConsentGrantInput{ + SubjectID: subject.ID, OrganizationName: consentOrganizationName, InvitationID: invitation, InvitationTermsVersion: 1, + Text: fixture.text(t, domain.ConsentPurposeContactDisclosure), GrantedAt: now, + }); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("NewContactConsentGrant(no organization, no fields) error = %v, want ErrInvalidConsent", err) + } + + grant := fixture.newContactGrant(t, subject.ID, organization, invitation, now, domain.ContactFieldPhone, domain.ContactFieldEmail) + record, created, err := ledger.GrantContact(ctx, grant) + if err != nil || !created { + t.Fatalf("GrantContact() = %v, %v, want a new record", created, err) + } + if record.Purpose() != domain.ConsentPurposeContactDisclosure || record.OrganizationID() != organization || + record.OrganizationName() != consentOrganizationName || record.InvitationID() != invitation || + record.InvitationTermsVersion() != 2 || record.Source() != domain.ConsentSourceInvitationAcceptance || + fmt.Sprint(record.Fields().Fields()) != "[email phone]" || record.TextHash() != grant.TextHash() { + t.Fatalf("C4 record = %s with scope %s %s %v, want the granted scope", record, record.OrganizationID(), record.InvitationID(), record.Fields().Fields()) + } + // The shown text names the organization, so its hash is not the hash + // of the published template. + template := fixture.text(t, domain.ConsentPurposeContactDisclosure) + if record.TextHash() == template.Hash() { + t.Fatal("the C4 record must keep the hash of the shown text, not of the template") + } + + repeat := fixture.newContactGrant(t, subject.ID, organization, invitation, now.Add(time.Minute), domain.ContactFieldEmail) + again, created, err := ledger.GrantContact(ctx, repeat) + if err != nil || created || again.ID() != record.ID() || !again.Fields().Equal(record.Fields()) { + t.Fatalf("GrantContact(repeat) = %s, %v, %v, want the existing record unchanged", again, created, err) + } + taken := fixture.newContactGrant(t, other.ID, organization, invitation, now, domain.ContactFieldEmail) + if _, _, err := ledger.GrantContact(ctx, taken); !errors.Is(err, outbound.ErrConsentInvitationTaken) { + t.Fatalf("GrantContact(invitation of another subject) error = %v, want ErrConsentInvitationTaken", err) + } + + second := fixture.newContactGrant(t, subject.ID, otherOrganization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldTelegram) + secondRecord, _, err := ledger.GrantContact(ctx, second) + if err != nil { + t.Fatalf("GrantContact(other organization) error = %v", err) + } + currentA, err := ledger.CurrentContact(ctx, subject.ID, organization) + if err != nil { + t.Fatalf("CurrentContact(A) error = %v", err) + } + assertConsentIDs(t, currentA, record.ID()) + + // C4 is revoked per organization; another organization keeps its consent. + revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposeContactDisclosure, organization, now.Add(time.Hour)) + assertConsentIDs(t, revoked, record.ID()) + if currentA, err := ledger.CurrentContact(ctx, subject.ID, organization); err != nil || len(currentA) != 0 { + t.Fatalf("CurrentContact(A) after revocation = %v, %v, want none", currentA, err) + } + currentB, err := ledger.CurrentContact(ctx, subject.ID, otherOrganization) + if err != nil { + t.Fatalf("CurrentContact(B) error = %v", err) + } + assertConsentIDs(t, currentB, secondRecord.ID()) + // The revoked invitation consent never comes back as a new grant. + comeback, created, err := ledger.GrantContact(ctx, fixture.newContactGrant(t, subject.ID, organization, invitation, now.Add(2*time.Hour), domain.ContactFieldEmail)) + if err != nil || created || comeback.State() != domain.ConsentStateRevoked { + t.Fatalf("GrantContact(revoked invitation) = %s, %v, %v, want the revoked record", comeback, created, err) + } + }) + + t.Run("the repository refuses a foreign subject and unbound texts", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "owner@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + stranger := fixture.identity.createUser(t, "stranger@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + publicationText := fixture.text(t, domain.ConsentPurposePublication) + grantWith := func(subjectID uuid.UUID, version domain.ConsentTextVersion, hash domain.ConsentTextHash, at time.Time) error { + grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{ + SubjectID: subjectID, Purpose: domain.ConsentPurposePublication, TextVersion: version, TextHash: hash, + Source: domain.ConsentSourceConsentSettings, GrantedAt: at, + }) + if err != nil { + return err + } + _, _, err = ledger.Grant(ctx, grant) + return err + } + for _, test := range []struct { + name string + err error + want error + }{ + {"unknown subject", grantWith(uuid.Must(uuid.NewV7()), publicationText.Version(), publicationText.Hash(), now), outbound.ErrUserNotFound}, + {"empty version", grantWith(subject.ID, "", publicationText.Hash(), now), domain.ErrInvalidConsentText}, + {"malformed version", grantWith(subject.ID, "c2 2026", publicationText.Hash(), now), domain.ErrInvalidConsentText}, + {"empty hash", grantWith(subject.ID, publicationText.Version(), domain.ConsentTextHash{}, now), domain.ErrInvalidConsentText}, + {"invented version", grantWith(subject.ID, "c2-2099-01-01", publicationText.Hash(), now), outbound.ErrConsentTextNotFound}, + {"version of another purpose", grantWith(subject.ID, "c3-2026-10-01", publicationText.Hash(), now), outbound.ErrConsentTextNotFound}, + {"hash of another text", grantWith(subject.ID, publicationText.Version(), domain.HashConsentText("edited text"), now), outbound.ErrConsentTextMismatch}, + {"grant before publication", grantWith(subject.ID, publicationText.Version(), publicationText.Hash(), publicationText.PublishedAt().Add(-time.Second)), outbound.ErrConsentTextNotPublished}, + } { + if !errors.Is(test.err, test.want) { + t.Fatalf("Grant(%s) error = %v, want %v", test.name, test.err, test.want) + } + } + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + + // Reads and revocations are scoped by the subject: the stranger + // neither sees nor revokes the owner's consent. + owned := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, publicationText.Version(), domain.ConsentSourceConsentSettings, now) + if revoked := fixture.revoke(t, ledger, stranger.ID, domain.ConsentPurposePublication, uuid.Nil, now.Add(time.Minute)); len(revoked) != 0 { + t.Fatalf("Revoke(stranger) = %v, want nothing", revoked) + } + if _, err := ledger.Current(ctx, stranger.ID, domain.ConsentPurposePublication); !errors.Is(err, outbound.ErrConsentNotFound) { + t.Fatalf("Current(stranger) error = %v, want ErrConsentNotFound", err) + } + if current, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposePublication); err != nil || current.ID() != owned.ID() { + t.Fatalf("Current(owner) = %s, %v, want the owner's record", current, err) + } + }) + + t.Run("the database refuses invalid rows written around the repository", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "raw@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + publicationHash := fixture.text(t, domain.ConsentPurposePublication).Hash() + insert := func(purpose, version string, hash []byte, source string, organization *uuid.UUID, fields []string, revocation *string) error { + var invitation *uuid.UUID + var terms *int64 + if organization != nil { + id, version := uuid.Must(uuid.NewV7()), int64(1) + invitation, terms = &id, &version + } + var revokedAt *time.Time + if revocation != nil { + revokedAt = &now + if *revocation == "" { + revocation = nil + } + } + _, err := pool.Exec(ctx, ` + INSERT INTO consent_records ( + id, subject_id, purpose, text_version, text_hash, source, organization_id, + field_set, invitation_id, invitation_terms_version, granted_at, revoked_at, revocation_source + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`, + uuid.Must(uuid.NewV7()), subject.ID, purpose, version, hash, source, organization, + fields, invitation, terms, now, revokedAt, revocation) + return err + } + organization := uuid.Must(uuid.NewV7()) + empty := "" + for _, test := range []struct { + name string + err error + code string + constraint string + }{ + {"empty version", insert("c2", "", publicationHash[:], "consent_settings", nil, nil, nil), consentCheckViolation, "consent_records_text_version_format"}, + {"empty hash", insert("c2", "c2-2026-10-01", []byte{}, "consent_settings", nil, nil, nil), consentCheckViolation, "consent_records_text_hash_sha256"}, + {"short hash", insert("c2", "c2-2026-10-01", publicationHash[:31], "consent_settings", nil, nil, nil), consentCheckViolation, "consent_records_text_hash_sha256"}, + {"C4 without a scope", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", nil, nil, nil), consentCheckViolation, "consent_records_c4_scope"}, + {"C4 with an empty field set", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{}, nil), consentCheckViolation, "consent_records_c4_scope"}, + {"C4 with a repeated field", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{"email", "email"}, nil), consentCheckViolation, "consent_records_c4_scope"}, + {"C4 with an unknown field", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{"address"}, nil), consentCheckViolation, "consent_records_c4_scope"}, + {"C2 with a scope", insert("c2", "c2-2026-10-01", publicationHash[:], "consent_settings", &organization, []string{"email"}, nil), consentCheckViolation, "consent_records_c4_scope"}, + {"C2 from the registration", insert("c2", "c2-2026-10-01", publicationHash[:], "registration", nil, nil, nil), consentCheckViolation, "consent_records_source_of_purpose"}, + {"revocation without a source", insert("c2", "c2-2026-10-01", publicationHash[:], "consent_settings", nil, nil, &empty), consentCheckViolation, "consent_records_revocation_stamp"}, + {"hash of another text", insert("c3", "c3-2026-10-01", publicationHash[:], "consent_settings", nil, nil, nil), consentForeignKeyViolation, "consent_records_published_text_fkey"}, + } { + assertSQLError(t, test.name, test.err, test.code, test.constraint) + } + + ledger := fixture.store.ConsentLedger() + record := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now) + _, err := pool.Exec(ctx, `UPDATE consent_records SET text_version = 'c2-2026-10-02' WHERE id = $1`, record.ID()) + assertSQLError(t, "update of a granted record", err, consentIntegrityViolation, "consent_records_immutable") + _, err = pool.Exec(ctx, `UPDATE consent_records SET revoked_at = granted_at, revocation_source = 'consent_settings', granted_at = granted_at - interval '1 day' WHERE id = $1`, record.ID()) + assertSQLError(t, "revocation that also moves the grant", err, consentIntegrityViolation, "consent_records_immutable") + fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePublication, uuid.Nil, now) + _, err = pool.Exec(ctx, `UPDATE consent_records SET revoked_at = revoked_at + interval '1 hour' WHERE id = $1`, record.ID()) + assertSQLError(t, "second revocation stamp", err, consentIntegrityViolation, "consent_records_immutable") + _, err = pool.Exec(ctx, `UPDATE consent_texts SET body = body || '.' WHERE purpose = 'c2'`) + assertSQLError(t, "update of a published text", err, consentIntegrityViolation, "consent_texts_immutable") + _, err = pool.Exec(ctx, `DELETE FROM consent_texts WHERE purpose = 'c2'`) + assertSQLError(t, "delete of a published text", err, consentIntegrityViolation, "consent_texts_immutable") + // Consent evidence outlives a careless account delete. + _, err = pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, subject.ID) + assertSQLError(t, "delete of an account with consent history", err, consentRestrictViolation, "consent_records_subject_id_fkey") + }) + + t.Run("the read model returns only the caller's own records page by page", func(t *testing.T) { + reset(t) + owner := fixture.identity.createUser(t, "reader@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + stranger := fixture.identity.createUser(t, "neighbour@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + strangerRecord := fixture.grant(t, ledger, stranger.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-30*time.Minute)) + var owned []uuid.UUID + for index, purpose := range []domain.ConsentPurpose{"c1", "c2", "c3", "c5"} { + record := fixture.grant(t, ledger, owner.ID, purpose, domain.ConsentTextVersion(string(purpose)+consentDemoVersionSuffix), + domain.ConsentSourceConsentSettings, now.Add(time.Duration(index-10)*time.Minute)) + owned = append([]uuid.UUID{record.ID()}, owned...) + } + fixture.revoke(t, ledger, owner.ID, domain.ConsentPurposeAutoCategorization, uuid.Nil, now) + + var seen []uuid.UUID + query := outbound.ConsentListQuery{SubjectID: owner.ID, Limit: 3} + for range 3 { + page, err := ledger.List(ctx, query) + if err != nil { + t.Fatalf("List() error = %v", err) + } + for _, record := range page.Records { + if record.SubjectID() != owner.ID { + t.Fatalf("List(owner) returned %s of another subject", record) + } + seen = append(seen, record.ID()) + } + if !page.HasMore { + break + } + position := outbound.ConsentPositionOf(page.Records[len(page.Records)-1]) + query.After = &position + } + if !slices.Equal(seen, owned) || slices.Contains(seen, strangerRecord.ID()) { + t.Fatalf("pages = %v, want exactly the owner's records newest first %v", seen, owned) + } + active := fixture.list(t, owner.ID, domain.ConsentStateActive) + if len(active.Records) != 3 || slices.ContainsFunc(active.Records, func(r domain.ConsentRecord) bool { return r.Purpose() == domain.ConsentPurposeAutoCategorization }) { + t.Fatalf("List(active) = %v, want the three unrevoked purposes", active.Records) + } + revoked := fixture.list(t, owner.ID, domain.ConsentStateRevoked) + if len(revoked.Records) != 1 || revoked.Records[0].Purpose() != domain.ConsentPurposeAutoCategorization { + t.Fatalf("List(revoked) = %v, want the revoked C3", revoked.Records) + } + if empty := fixture.list(t, uuid.Must(uuid.NewV7()), ""); len(empty.Records) != 0 || empty.HasMore { + t.Fatalf("List(unknown subject) = %v, want an empty page", empty.Records) + } + }) + + t.Run("a C4 grant commits and rolls back with its business transaction", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "accept@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + organization := uuid.Must(uuid.NewV7()) + + rolledBack := fixture.newContactGrant(t, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail) + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if _, created, err := unit.ConsentLedger().GrantContact(ctx, rolledBack); err != nil || !created { + return fmt.Errorf("grant inside the acceptance: created %v: %w", created, err) + } + // A later step of the acceptance fails, for example the state + // transition or the contact grant. + return errForcedRollback + }) + if !errors.Is(err, errForcedRollback) { + t.Fatalf("WithinTransaction() error = %v, want the forced rollback", err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + + // A failing statement after the grant aborts the whole acceptance. + failing := fixture.newContactGrant(t, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail) + unknownSubject := fixture.newContactGrant(t, uuid.Must(uuid.NewV7()), organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail) + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if _, _, err := unit.ConsentLedger().GrantContact(ctx, failing); err != nil { + return err + } + _, _, err := unit.ConsentLedger().GrantContact(ctx, unknownSubject) + return err + }) + if !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("WithinTransaction(failing step) error = %v, want ErrUserNotFound", err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + + committed := fixture.newContactGrant(t, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail, domain.ContactFieldFullName) + var record domain.ConsentRecord + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + record, _, err = unit.ConsentLedger().GrantContact(ctx, committed) + if err != nil { + return err + } + // The same transaction sees its own grant before the commit. + current, err := unit.ConsentLedger().CurrentContact(ctx, subject.ID, organization) + if err != nil || len(current) != 1 { + return fmt.Errorf("read own grant: %d records: %w", len(current), err) + } + return nil + }) + if err != nil { + t.Fatalf("WithinTransaction(commit) error = %v", err) + } + current, err := fixture.store.ConsentLedger().CurrentContact(ctx, subject.ID, organization) + if err != nil { + t.Fatalf("CurrentContact() error = %v", err) + } + assertConsentIDs(t, current, record.ID()) + }) + + t.Run("the unverified account cleanup removes the ledger of the accounts it deletes", func(t *testing.T) { + reset(t) + users := fixture.identity.store.Users() + ledger := fixture.store.ConsentLedger() + cutoff := now.Add(-time.Hour) + stale := fixture.identity.createUser(t, "stale-consent@example.com", domain.ScenarioCandidate, cutoff.Add(-time.Hour)) + fixture.grant(t, ledger, stale.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, cutoff.Add(-time.Hour)) + verified := fixture.identity.createUser(t, "verified-consent@example.com", domain.ScenarioCandidate, cutoff.Add(-2*time.Hour)) + kept := fixture.grant(t, ledger, verified.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, cutoff.Add(-2*time.Hour)) + if _, err := users.MarkEmailVerified(ctx, verified.ID, verified.RegistrationVersion, cutoff.Add(-90*time.Minute)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + + deleted, err := users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil || deleted != 1 { + t.Fatalf("DeleteUnverifiedRegisteredBefore() = %d, %v, want 1", deleted, err) + } + if _, err := users.GetByID(ctx, stale.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(stale) error = %v, want ErrUserNotFound", err) + } + page := fixture.list(t, verified.ID, "") + assertConsentIDs(t, page.Records, kept.ID()) + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + }) + + t.Run("the database checks the C4 hash against the organization name snapshot", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "snapshot@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + text := fixture.text(t, domain.ConsentPurposeContactDisclosure) + shownFor := func(name string) []byte { + shown, err := text.RenderForOrganization(name) + if err != nil { + t.Fatalf("RenderForOrganization(%q) error = %v", name, err) + } + hash := domain.HashConsentText(shown) + return hash[:] + } + insert := func(purpose, name string, hash []byte) error { + var organization, invitation *uuid.UUID + var fields []string + var terms *int64 + source := "consent_settings" + version := purpose + consentDemoVersionSuffix + if purpose == "c4" { + organizationID, invitationID, termsVersion := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), int64(1) + organization, invitation, terms, fields, source = &organizationID, &invitationID, &termsVersion, []string{"email"}, "invitation_acceptance" + } + _, err := pool.Exec(ctx, ` + INSERT INTO consent_records ( + id, subject_id, purpose, text_version, text_hash, source, organization_id, organization_name, + field_set, invitation_id, invitation_terms_version, granted_at + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, + uuid.Must(uuid.NewV7()), subject.ID, purpose, version, hash, source, organization, name, + fields, invitation, terms, now) + return err + } + personalData := fixture.text(t, domain.ConsentPurposePersonalData) + personalHash := personalData.Hash() + assertSQLError(t, "hash of another organization name", insert("c4", consentOrganizationName, shownFor("Other LLC")), + consentCheckViolation, "consent_records_c4_text_hash") + assertSQLError(t, "name other than the shown one", insert("c4", "Other LLC", shownFor(consentOrganizationName)), + consentCheckViolation, "consent_records_c4_text_hash") + templateHash := text.Hash() + assertSQLError(t, "hash of the template", insert("c4", consentOrganizationName, templateHash[:]), + consentCheckViolation, "consent_records_c4_text_hash") + assertSQLError(t, "C4 without a name", func() error { + _, err := pool.Exec(ctx, ` + INSERT INTO consent_records ( + id, subject_id, purpose, text_version, text_hash, source, organization_id, field_set, + invitation_id, invitation_terms_version, granted_at + ) VALUES ($1, $2, 'c4', 'c4-2026-10-01', $3, 'invitation_acceptance', $4, '{email}', $5, 1, $6)`, + uuid.Must(uuid.NewV7()), subject.ID, shownFor(consentOrganizationName), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), now) + return err + }(), consentCheckViolation, "consent_records_c4_scope") + assertSQLError(t, "C1 with an organization name", insert("c1", consentOrganizationName, personalHash[:]), + consentCheckViolation, "consent_records_c4_scope") + if err := insert("c4", consentOrganizationName, shownFor(consentOrganizationName)); err != nil { + t.Fatalf("insert the hash of the shown text: %v", err) + } + + // The organization is renamed between two acceptances: each record + // keeps the name its own text showed, and its hash still proves that + // text. + ledger := fixture.store.ConsentLedger() + organization := uuid.Must(uuid.NewV7()) + before, _, err := ledger.GrantContact(ctx, fixture.newNamedContactGrant(t, consentOrganizationName, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail)) + if err != nil { + t.Fatalf("GrantContact(before the rename) error = %v", err) + } + const renamed = "Acme Renamed LLC" + after, _, err := ledger.GrantContact(ctx, fixture.newNamedContactGrant(t, renamed, subject.ID, organization, uuid.Must(uuid.NewV7()), now.Add(time.Minute), domain.ContactFieldPhone)) + if err != nil { + t.Fatalf("GrantContact(after the rename) error = %v", err) + } + current, err := ledger.CurrentContact(ctx, subject.ID, organization) + if err != nil { + t.Fatalf("CurrentContact() error = %v", err) + } + assertConsentIDs(t, current, after.ID(), before.ID()) + for index, want := range []string{renamed, consentOrganizationName} { + record := current[index] + if record.OrganizationName() != want { + t.Fatalf("record %s name = %q, want the snapshot %q", record, record.OrganizationName(), want) + } + if hash := record.TextHash(); !slices.Equal(shownFor(record.OrganizationName()), hash[:]) { + t.Fatalf("record %s hash does not prove the text shown with its snapshot", record) + } + } + }) + + t.Run("a revocation before the grant time is stamped at the grant time", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "skew@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + record := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now) + revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePublication, uuid.Nil, now.Add(-time.Hour)) + assertConsentIDs(t, revoked, record.ID()) + if revokedAt, _ := revoked[0].RevokedAt(); !revokedAt.Equal(now) { + t.Fatalf("revoked_at = %v, want the grant time %v", revokedAt, now) + } + }) + + t.Run("only the consent of an unconfirmed account can be deleted", func(t *testing.T) { + reset(t) + ledger := fixture.store.ConsentLedger() + confirmed := fixture.identity.createUser(t, "confirmed@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + retained := fixture.grant(t, ledger, confirmed.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-72*time.Hour)) + if _, err := fixture.identity.store.Users().MarkEmailVerified(ctx, confirmed.ID, confirmed.RegistrationVersion, now.Add(-71*time.Hour)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + unconfirmed := fixture.identity.createUser(t, "unconfirmed@example.com", domain.ScenarioCandidate, now.Add(-time.Hour)) + discardable := fixture.grant(t, ledger, unconfirmed.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-time.Hour)) + + _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1`, retained.ID()) + assertSQLError(t, "delete of a confirmed account's consent", err, consentIntegrityViolation, "consent_records_retained") + if _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1`, discardable.ID()); err != nil { + t.Fatalf("delete of an unconfirmed account's consent: %v", err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + }) + + t.Run("re-registration of an unverified account replaces its registration C1", func(t *testing.T) { + reset(t) + ledger := fixture.store.ConsentLedger() + first := fixture.identity.createUser(t, "reregister@example.com", domain.ScenarioCandidate, now.Add(-2*time.Hour)) + earlier := fixture.grant(t, ledger, first.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-2*time.Hour)) + + changed, err := first.ReRegister(fixture.identity.registration(t, "reregister@example.com", domain.ScenarioEmployer, now)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + var replacement domain.ConsentRecord + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if _, err := unit.Users().UpdateRegistration(ctx, changed); err != nil { + return err + } + grant := fixture.newGrant(t, first.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now) + var created bool + replacement, created, err = unit.ConsentLedger().Grant(ctx, grant) + if err == nil && !created { + return errors.New("the new registration reused the earlier registrant's C1") + } + return err + }) + if err != nil { + t.Fatalf("re-registration transaction error = %v", err) + } + page := fixture.list(t, first.ID, "") + assertConsentIDs(t, page.Records, replacement.ID()) + if replacement.ID() == earlier.ID() { + t.Fatal("the earlier registrant's C1 survived the re-registration") + } + + // A stale re-registration changes nothing and deletes nothing. + if _, err := fixture.identity.store.Users().UpdateRegistration(ctx, changed); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("UpdateRegistration(stale) error = %v, want ErrUserVersionConflict", err) + } + assertConsentIDs(t, fixture.list(t, first.ID, "").Records, replacement.ID()) + + // A verified account is never re-registered, so its C1 stays. + verified := fixture.identity.createUser(t, "verified-reregister@example.com", domain.ScenarioCandidate, now.Add(-2*time.Hour)) + kept := fixture.grant(t, ledger, verified.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-2*time.Hour)) + if _, err := fixture.identity.store.Users().MarkEmailVerified(ctx, verified.ID, verified.RegistrationVersion, now.Add(-time.Hour)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + stale, err := verified.ReRegister(fixture.identity.registration(t, "verified-reregister@example.com", domain.ScenarioEmployer, now)) + if err != nil { + t.Fatalf("ReRegister(the unverified copy) error = %v", err) + } + if _, err := fixture.identity.store.Users().UpdateRegistration(ctx, stale); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("UpdateRegistration(verified) error = %v, want ErrUserVersionConflict", err) + } + assertConsentIDs(t, fixture.list(t, verified.ID, "").Records, kept.ID()) + }) + + t.Run("concurrent grants of one version store one record", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "concurrent@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := postgresadapter.NewConsentStore(env.newPoolWithMaxConns(ctx, t, concurrentConsentGrants)).ConsentLedger() + grants := make([]domain.ConsentGrant, concurrentConsentGrants) + for index := range grants { + grants[index] = fixture.newGrant(t, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now) + } + records := make([]domain.ConsentRecord, len(grants)) + createdFlags := make([]bool, len(grants)) + errs := make([]error, len(grants)) + start := make(chan struct{}) + var group sync.WaitGroup + for index, grant := range grants { + group.Go(func() { + <-start + records[index], createdFlags[index], errs[index] = ledger.Grant(ctx, grant) + }) + } + close(start) + group.Wait() + created := 0 + for index, err := range errs { + if err != nil { + t.Fatalf("Grant %d error = %v", index, err) + } + if createdFlags[index] { + created++ + } + if records[index].ID() != records[0].ID() { + t.Fatalf("Grant %d returned %s, want the one record %s", index, records[index], records[0]) + } + } + if created != 1 { + t.Fatalf("%d grants created a record, want exactly 1", created) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + }) + + t.Run("a grant racing a revocation leaves at most one unrevoked record of the version", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "race@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := postgresadapter.NewConsentStore(env.newPoolWithMaxConns(ctx, t, 2)).ConsentLedger() + fixture.grant(t, ledger, subject.ID, domain.ConsentPurposeFSPImport, "c5-2026-10-01", domain.ConsentSourceConsentSettings, now) + for round := range consentRaceRounds { + at := now.Add(time.Duration(round+1) * time.Minute) + grant := fixture.newGrant(t, subject.ID, domain.ConsentPurposeFSPImport, "c5-2026-10-01", domain.ConsentSourceConsentSettings, at) + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: subject.ID, Purpose: domain.ConsentPurposeFSPImport, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: at, + }) + if err != nil { + t.Fatalf("NewConsentRevocation() error = %v", err) + } + var grantErr, revokeErr error + start := make(chan struct{}) + var group sync.WaitGroup + group.Go(func() { <-start; _, _, grantErr = ledger.Grant(ctx, grant) }) + group.Go(func() { <-start; _, revokeErr = ledger.Revoke(ctx, revocation) }) + close(start) + group.Wait() + // The only documented race outcome is a conflict the caller retries. + if grantErr != nil && !errors.Is(grantErr, outbound.ErrTransactionConflict) { + t.Fatalf("round %d Grant() error = %v", round, grantErr) + } + if revokeErr != nil { + t.Fatalf("round %d Revoke() error = %v", round, revokeErr) + } + var unrevoked int + if err := pool.QueryRow(ctx, ` + SELECT count(*) FROM consent_records + WHERE subject_id = $1 AND purpose = 'c5' AND revoked_at IS NULL`, subject.ID).Scan(&unrevoked); err != nil { + t.Fatalf("count unrevoked records: %v", err) + } + if unrevoked > 1 { + t.Fatalf("round %d left %d unrevoked records of one version", round, unrevoked) + } + } + }) + + t.Run("the cleanup skips an account whose consent row is locked", func(t *testing.T) { + reset(t) + cutoff := now.Add(-time.Hour) + stale := fixture.identity.createUser(t, "locked-consent@example.com", domain.ScenarioCandidate, cutoff.Add(-time.Hour)) + fixture.grant(t, fixture.store.ConsentLedger(), stale.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, cutoff.Add(-time.Hour)) + // Only the consent row is locked: a revocation in a transaction that + // stays open and rolls back. + holder := startHeldTransaction(ctx, t, postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, 2)), func(ctx context.Context, unit outbound.UnitOfWork) error { + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: stale.ID, Purpose: domain.ConsentPurposePersonalData, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: cutoff, + }) + if err != nil { + return err + } + revoked, err := unit.ConsentLedger().Revoke(ctx, revocation) + if err == nil && len(revoked) != 1 { + return fmt.Errorf("revoked %d records, want 1", len(revoked)) + } + return err + }, false) + holder.awaitHeld(ctx, t) + + impatient := postgresadapter.NewIdentityStore(env.newPoolWithLockTimeout(ctx, t, cleanupLockTimeout)).Users() + deleted, err := impatient.DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil || deleted != 0 { + t.Fatalf("DeleteUnverifiedRegisteredBefore(consent locked) = %d, %v, want 0 without waiting", deleted, err) + } + if err := holder.finish(); !errors.Is(err, errForcedRollback) { + t.Fatalf("holder error = %v, want the forced rollback", err) + } + deleted, err = impatient.DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil || deleted != 1 { + t.Fatalf("DeleteUnverifiedRegisteredBefore(unlocked) = %d, %v, want 1", deleted, err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + }) +} + +func (fixture consentFixture) text(t *testing.T, purpose domain.ConsentPurpose) domain.ConsentText { + t.Helper() + text, err := fixture.store.ConsentTexts().Current(fixture.ctx, purpose, fixture.now) + if err != nil { + t.Fatalf("ConsentTexts().Current(%s) error = %v", purpose, err) + } + return text +} + +func (fixture consentFixture) newGrant( + t *testing.T, + subject uuid.UUID, + purpose domain.ConsentPurpose, + version domain.ConsentTextVersion, + source domain.ConsentSource, + at time.Time, +) domain.ConsentGrant { + t.Helper() + text, err := fixture.store.ConsentTexts().Get(fixture.ctx, purpose, version) + if err != nil { + t.Fatalf("ConsentTexts().Get(%s, %s) error = %v", purpose, version, err) + } + grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{ + SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), TextHash: text.Hash(), Source: source, GrantedAt: at, + }) + if err != nil { + t.Fatalf("NewConsentGrant() error = %v", err) + } + return grant +} + +func (fixture consentFixture) grant( + t *testing.T, + ledger outbound.ConsentLedger, + subject uuid.UUID, + purpose domain.ConsentPurpose, + version domain.ConsentTextVersion, + source domain.ConsentSource, + at time.Time, +) domain.ConsentRecord { + t.Helper() + record, created, err := ledger.Grant(fixture.ctx, fixture.newGrant(t, subject, purpose, version, source, at)) + if err != nil || !created { + t.Fatalf("Grant(%s %s) = %v, %v, want a new record", purpose, version, created, err) + } + return record +} + +// newContactGrant builds the C4 grant of an acceptance of terms version 2 +// for the organization named consentOrganizationName. +func (fixture consentFixture) newContactGrant( + t *testing.T, + subject, organization, invitation uuid.UUID, + at time.Time, + fields ...domain.ContactField, +) domain.ContactConsentGrant { + t.Helper() + return fixture.newNamedContactGrant(t, consentOrganizationName, subject, organization, invitation, at, fields...) +} + +// newNamedContactGrant builds the C4 grant of an acceptance of terms version +// 2 for the organization shown under name; the domain hashes the text as +// shown. +func (fixture consentFixture) newNamedContactGrant( + t *testing.T, + name string, + subject, organization, invitation uuid.UUID, + at time.Time, + fields ...domain.ContactField, +) domain.ContactConsentGrant { + t.Helper() + set, err := domain.NewContactFieldSet(fields...) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + grant, err := domain.NewContactConsentGrant(domain.ContactConsentGrantInput{ + SubjectID: subject, OrganizationID: organization, OrganizationName: name, Fields: set, InvitationID: invitation, + InvitationTermsVersion: 2, Text: fixture.text(t, domain.ConsentPurposeContactDisclosure), GrantedAt: at, + }) + if err != nil { + t.Fatalf("NewContactConsentGrant() error = %v", err) + } + return grant +} + +func (fixture consentFixture) revoke( + t *testing.T, + ledger outbound.ConsentLedger, + subject uuid.UUID, + purpose domain.ConsentPurpose, + organization uuid.UUID, + at time.Time, +) []domain.ConsentRecord { + t.Helper() + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: subject, Purpose: purpose, OrganizationID: organization, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: at, + }) + if err != nil { + t.Fatalf("NewConsentRevocation() error = %v", err) + } + revoked, err := ledger.Revoke(fixture.ctx, revocation) + if err != nil { + t.Fatalf("Revoke(%s) error = %v", purpose, err) + } + for _, record := range revoked { + if record.State() != domain.ConsentStateRevoked { + t.Fatalf("Revoke(%s) returned %s, want revoked records", purpose, record) + } + } + return revoked +} + +func (fixture consentFixture) list(t *testing.T, subject uuid.UUID, state domain.ConsentState) outbound.ConsentPage { + t.Helper() + page, err := fixture.store.ConsentLedger().List(fixture.ctx, outbound.ConsentListQuery{SubjectID: subject, State: state, Limit: consentPageSize}) + if err != nil { + t.Fatalf("List() error = %v", err) + } + return page +} + +// rawRecord returns the whole stored row as JSON, so a test can prove that +// a row stayed byte-for-byte the same. +func (fixture consentFixture) rawRecord(t *testing.T, id uuid.UUID) string { + t.Helper() + var row string + if err := fixture.pool.QueryRow(fixture.ctx, `SELECT row_to_json(stored)::text FROM consent_records AS stored WHERE stored.id = $1`, id).Scan(&row); err != nil { + t.Fatalf("read consent record: %v", err) + } + return row +} + +func assertConsentIDs(t *testing.T, records []domain.ConsentRecord, want ...uuid.UUID) { + t.Helper() + got := make([]uuid.UUID, 0, len(records)) + for _, record := range records { + got = append(got, record.ID()) + } + if !slices.Equal(got, want) { + t.Fatalf("record IDs = %v, want %v", got, want) + } +} + +func assertConsentStates(t *testing.T, page outbound.ConsentPage, want ...domain.ConsentState) { + t.Helper() + got := make([]domain.ConsentState, 0, len(page.Records)) + for _, record := range page.Records { + got = append(got, record.State()) + } + if !slices.Equal(got, want) { + t.Fatalf("record states = %v, want %v", got, want) + } +} + +func assertSQLError(t *testing.T, name string, err error, code, constraint string) { + t.Helper() + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != code || pgError.ConstraintName != constraint { + t.Fatalf("%s: error = %v, want SQLSTATE %s on %s", name, err, code, constraint) + } +} diff --git a/backend/integration_test/delivery_test.go b/backend/integration_test/delivery_test.go index 7fe6a4f..27c9ef5 100644 --- a/backend/integration_test/delivery_test.go +++ b/backend/integration_test/delivery_test.go @@ -134,7 +134,7 @@ func TestMailDelivery(t *testing.T) { {"consumer_processed_events"}, {"consumer_dead_letters"}, }, deliveryTables...) - truncateTables(ctx, t, pool, append(tables, identityTables...)...) + truncateTables(ctx, t, pool, append(append(tables, identityTables...), consentTables...)...) } t.Run("one event processed twice through the consumer creates one delivery", func(t *testing.T) { diff --git a/backend/integration_test/identity_test.go b/backend/integration_test/identity_test.go index 3afd995..3e1f0aa 100644 --- a/backend/integration_test/identity_test.go +++ b/backend/integration_test/identity_test.go @@ -70,8 +70,9 @@ func TestIdentityRepositories(t *testing.T) { // Subtests share tables and run sequentially; each starts from empty tables. reset := func(t *testing.T) { t.Helper() - // The deliveries reference users, so TRUNCATE must name them too. - truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables)...) + // The deliveries and consent records reference users, so TRUNCATE + // must name them too. + truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables, consentTables)...) } t.Run("stores an account and finds it by ID and by any case of its email", func(t *testing.T) { diff --git a/backend/integration_test/mail_quota_test.go b/backend/integration_test/mail_quota_test.go index da3a00e..4f7e288 100644 --- a/backend/integration_test/mail_quota_test.go +++ b/backend/integration_test/mail_quota_test.go @@ -62,7 +62,7 @@ func TestMailQuota(t *testing.T) { harness.recipients = &deliveryHarness{env: env, pool: pool, identity: postgresadapter.NewIdentityStore(pool), logs: harness.logs} reset := func(t *testing.T, now time.Time) domain.User { t.Helper() - truncateTables(ctx, t, pool, append([]pgx.Identifier{mailQuotaUsageTable, mailQuotaReservationsTable}, append(deliveryTables, identityTables...)...)...) + truncateTables(ctx, t, pool, append([]pgx.Identifier{mailQuotaUsageTable, mailQuotaReservationsTable}, append(append(deliveryTables, identityTables...), consentTables...)...)...) harness.now = now harness.recipients.now = now return harness.recipients.createRecipient(ctx, t, true) 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 6aedbb8..b57978a 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -5223,6 +5223,237 @@ func (s *Server) handleGetSpecializationCatalogRequest(args [0]string, argsEscap } } +// handleListMyConsentsRequest handles ListMyConsents operation. +// +// Requires the session cookie of a candidate or an employer account. The subject comes from the +// session, never from a request parameter, so the response holds only the caller's own consents: no +// request can name another account, and records of other accounts are never listed. Returns a page of +// the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with +// cursor pagination. +// +// The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the +// source, and the grant time; the server also stores the hash of exactly the text the subject saw. A +// newer text version of the same purpose is a new record, and the earlier one becomes `superseded` +// without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one +// organization, once; a later grant is a new record. Purposes are independent. +// +// 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 (TASK-088). +// +// Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations +// of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed +// `limit`, `cursor`, or `state` answers 400 validation_failed. +// +// GET /api/v1/me/consents +func (s *Server) handleListMyConsentsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ListMyConsents"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/consents"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyConsentsOperation, + 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: ListMyConsentsOperation, + ID: "ListMyConsents", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ListMyConsentsOperation, 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 := decodeListMyConsentsParams(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 ListMyConsentsRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ListMyConsentsOperation, + OperationSummary: "List the consents of the current account with their history.", + OperationID: "ListMyConsents", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "state", + In: "query", + }: params.State, + { + Name: "limit", + In: "query", + }: params.Limit, + { + Name: "cursor", + In: "query", + }: params.Cursor, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = ListMyConsentsParams + Response = ListMyConsentsRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackListMyConsentsParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ListMyConsents(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ListMyConsents(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 := encodeListMyConsentsResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleListMyInvitationsRequest handles ListMyInvitations operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from 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 7c73702..832094b 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -85,6 +85,10 @@ type GetOrganizationNeedRes interface { getOrganizationNeedRes() } +type ListMyConsentsRes interface { + listMyConsentsRes() +} + type ListMyInvitationsRes interface { listMyInvitationsRes() } 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 b37ae40..6c240b5 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -7165,6 +7165,119 @@ func (s *ConfirmEmailForbidden) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *ConsentOrganization) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ConsentOrganization) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("name") + e.Str(s.Name) + } +} + +var jsonFieldsNameOfConsentOrganization = [2]string{ + 0: "id", + 1: "name", +} + +// Decode decodes ConsentOrganization from json. +func (s *ConsentOrganization) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentOrganization 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 "name": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Name = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"name\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ConsentOrganization") + } + // 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(jsonFieldsNameOfConsentOrganization) { + name = jsonFieldsNameOfConsentOrganization[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 *ConsentOrganization) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentOrganization) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ConsentPurpose as json. func (s ConsentPurpose) Encode(e *jx.Encoder) { e.Str(string(s)) @@ -7203,6 +7316,582 @@ func (s *ConsentPurpose) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ConsentPurposeCode as json. +func (s ConsentPurposeCode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ConsentPurposeCode from json. +func (s *ConsentPurposeCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentPurposeCode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ConsentPurposeCode(v) { + case ConsentPurposeCodeC1: + *s = ConsentPurposeCodeC1 + case ConsentPurposeCodeC2: + *s = ConsentPurposeCodeC2 + case ConsentPurposeCodeC3: + *s = ConsentPurposeCodeC3 + case ConsentPurposeCodeC4: + *s = ConsentPurposeCodeC4 + case ConsentPurposeCodeC5: + *s = ConsentPurposeCodeC5 + default: + *s = ConsentPurposeCode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ConsentPurposeCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentPurposeCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ConsentRecord) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ConsentRecord) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("purpose") + s.Purpose.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("text_version") + s.TextVersion.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } + { + e.FieldStart("granted_at") + s.GrantedAt.Encode(e) + } + { + e.FieldStart("revoked_at") + s.RevokedAt.Encode(e) + } + { + e.FieldStart("revocation_source") + s.RevocationSource.Encode(e) + } + { + e.FieldStart("organization") + s.Organization.Encode(e) + } + { + e.FieldStart("fields") + if s.Fields == nil { + e.Null() + } else { + e.ArrStart() + for _, elem := range s.Fields { + elem.Encode(e) + } + e.ArrEnd() + } + } + { + e.FieldStart("invitation_id") + s.InvitationID.Encode(e) + } + { + e.FieldStart("invitation_terms_version") + s.InvitationTermsVersion.Encode(e) + } +} + +var jsonFieldsNameOfConsentRecord = [12]string{ + 0: "id", + 1: "purpose", + 2: "state", + 3: "text_version", + 4: "source", + 5: "granted_at", + 6: "revoked_at", + 7: "revocation_source", + 8: "organization", + 9: "fields", + 10: "invitation_id", + 11: "invitation_terms_version", +} + +// Decode decodes ConsentRecord from json. +func (s *ConsentRecord) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentRecord to nil") + } + var requiredBitSet [2]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 "purpose": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Purpose.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"purpose\"") + } + case "state": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "text_version": + requiredBitSet[0] |= 1 << 3 + 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 "source": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + case "granted_at": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.GrantedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"granted_at\"") + } + case "revoked_at": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.RevokedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"revoked_at\"") + } + case "revocation_source": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.RevocationSource.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"revocation_source\"") + } + case "organization": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.Organization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"organization\"") + } + case "fields": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + switch tt := d.Next(); tt { + case jx.Null: + if err := d.Skip(); err != nil { + return err + } + default: + s.Fields = make([]ContactFieldKind, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ContactFieldKind + if err := elem.Decode(d); err != nil { + return err + } + s.Fields = append(s.Fields, elem) + return nil + }); err != nil { + return err + } + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"fields\"") + } + case "invitation_id": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.InvitationID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"invitation_id\"") + } + case "invitation_terms_version": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.InvitationTermsVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"invitation_terms_version\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ConsentRecord") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b11111111, + 0b00001111, + } { + 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(jsonFieldsNameOfConsentRecord) { + name = jsonFieldsNameOfConsentRecord[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 *ConsentRecord) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentRecord) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ConsentRecordList) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ConsentRecordList) encodeFields(e *jx.Encoder) { + { + e.FieldStart("items") + e.ArrStart() + for _, elem := range s.Items { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("page") + s.Page.Encode(e) + } +} + +var jsonFieldsNameOfConsentRecordList = [2]string{ + 0: "items", + 1: "page", +} + +// Decode decodes ConsentRecordList from json. +func (s *ConsentRecordList) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentRecordList to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "items": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Items = make([]ConsentRecord, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ConsentRecord + if err := elem.Decode(d); err != nil { + return err + } + s.Items = append(s.Items, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"items\"") + } + case "page": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Page.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"page\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ConsentRecordList") + } + // 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(jsonFieldsNameOfConsentRecordList) { + name = jsonFieldsNameOfConsentRecordList[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 *ConsentRecordList) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentRecordList) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConsentRevocationSource as json. +func (s ConsentRevocationSource) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ConsentRevocationSource from json. +func (s *ConsentRevocationSource) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentRevocationSource to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ConsentRevocationSource(v) { + case ConsentRevocationSourceConsentSettings: + *s = ConsentRevocationSourceConsentSettings + case ConsentRevocationSourceSupportRequest: + *s = ConsentRevocationSourceSupportRequest + default: + *s = ConsentRevocationSource(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ConsentRevocationSource) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentRevocationSource) 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)) +} + +// Decode decodes ConsentSource from json. +func (s *ConsentSource) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentSource to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ConsentSource(v) { + case ConsentSourceRegistration: + *s = ConsentSourceRegistration + case ConsentSourceConsentSettings: + *s = ConsentSourceConsentSettings + case ConsentSourceInvitationAcceptance: + *s = ConsentSourceInvitationAcceptance + default: + *s = ConsentSource(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ConsentSource) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentSource) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConsentState as json. +func (s ConsentState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ConsentState from json. +func (s *ConsentState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ConsentState(v) { + case ConsentStateActive: + *s = ConsentStateActive + case ConsentStateSuperseded: + *s = ConsentStateSuperseded + case ConsentStateRevoked: + *s = ConsentStateRevoked + default: + *s = ConsentState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ConsentState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *ConsentText) Encode(e *jx.Encoder) { e.ObjStart() @@ -15058,6 +15747,82 @@ func (s *ItemContent) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ListMyConsentsBadRequest as json. +func (s *ListMyConsentsBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyConsentsBadRequest from json. +func (s *ListMyConsentsBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyConsentsBadRequest 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 = ListMyConsentsBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyConsentsBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyConsentsBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyConsentsUnauthorized as json. +func (s *ListMyConsentsUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyConsentsUnauthorized from json. +func (s *ListMyConsentsUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyConsentsUnauthorized 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 = ListMyConsentsUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyConsentsUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyConsentsUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ListMyInvitationsBadRequest as json. func (s *ListMyInvitationsBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -21368,6 +22133,94 @@ func (s *NilCandidateExperience) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ConsentOrganization as json. +func (o NilConsentOrganization) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ConsentOrganization from json. +func (o *NilConsentOrganization) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilConsentOrganization to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ConsentOrganization + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilConsentOrganization) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilConsentOrganization) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConsentRevocationSource as json. +func (o NilConsentRevocationSource) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes ConsentRevocationSource from json. +func (o *NilConsentRevocationSource) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilConsentRevocationSource to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ConsentRevocationSource + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilConsentRevocationSource) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilConsentRevocationSource) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ContactAccessBlock as json. func (o NilContactAccessBlock) Encode(e *jx.Encoder) { if o.Null { @@ -22076,6 +22929,50 @@ func (s *NilInvitationNeedReference) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes InvitationTermsVersion as json. +func (o NilInvitationTermsVersion) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes InvitationTermsVersion from json. +func (o *NilInvitationTermsVersion) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilInvitationTermsVersion to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v InvitationTermsVersion + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilInvitationTermsVersion) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilInvitationTermsVersion) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes NeedDomainName as json. func (o NilNeedDomainName) Encode(e *jx.Encoder) { if o.Null { 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 f693f4c..5c31024 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -29,6 +29,7 @@ const ( GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts" GetOrganizationNeedOperation OperationName = "GetOrganizationNeed" GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog" + ListMyConsentsOperation OperationName = "ListMyConsents" ListMyInvitationsOperation OperationName = "ListMyInvitations" ListMySupportCasesOperation OperationName = "ListMySupportCases" ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations" 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 8598d34..a2fdc0a 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -1819,6 +1819,249 @@ func decodeGetOrganizationNeedParams(args [2]string, argsEscaped bool, r *http.R return params, nil } +// ListMyConsentsParams is parameters of ListMyConsents operation. +type ListMyConsentsParams struct { + // Lists only the records in this state; omit it for the whole history. + State OptConsentState `json:",omitempty,omitzero"` + // Maximum number of items in the page. The server may return fewer items even when more remain; use + // `page.has_more` to detect the end. + Limit OptInt32 `json:",omitempty,omitzero"` + // Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the + // first page. A malformed or foreign cursor returns 400 with code validation_failed. + Cursor OptString `json:",omitempty,omitzero"` +} + +func unpackListMyConsentsParams(packed middleware.Parameters) (params ListMyConsentsParams) { + { + key := middleware.ParameterKey{ + Name: "state", + In: "query", + } + if v, ok := packed[key]; ok { + params.State = v.(OptConsentState) + } + } + { + key := middleware.ParameterKey{ + Name: "limit", + In: "query", + } + if v, ok := packed[key]; ok { + params.Limit = v.(OptInt32) + } + } + { + key := middleware.ParameterKey{ + Name: "cursor", + In: "query", + } + if v, ok := packed[key]; ok { + params.Cursor = v.(OptString) + } + } + return params +} + +func decodeListMyConsentsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyConsentsParams, _ error) { + q := uri.NewQueryDecoder(r.URL.Query()) + // Decode query: state. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "state", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotStateVal ConsentState + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + paramsDotStateVal = ConsentState(c) + return nil + }(); err != nil { + return err + } + params.State.SetTo(paramsDotStateVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.State.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "state", + In: "query", + Err: err, + } + } + // Set default value for query: limit. + { + val := int32(20) + params.Limit.SetTo(val) + } + // Decode query: limit. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "limit", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotLimitVal int32 + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToInt32(val) + if err != nil { + return err + } + + paramsDotLimitVal = c + return nil + }(); err != nil { + return err + } + params.Limit.SetTo(paramsDotLimitVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Limit.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 100, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "limit", + In: "query", + Err: err, + } + } + // Decode query: cursor. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "cursor", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotCursorVal string + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + paramsDotCursorVal = c + return nil + }(); err != nil { + return err + } + params.Cursor.SetTo(paramsDotCursorVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Cursor.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 512, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "cursor", + In: "query", + Err: err, + } + } + return params, nil +} + // ListMyInvitationsParams is parameters of ListMyInvitations operation. type ListMyInvitationsParams struct { // Maximum number of items in the page. The server may return fewer items even when more remain; use 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 771867f..68908c9 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 @@ -2031,6 +2031,65 @@ func encodeGetSpecializationCatalogResponse(response *SpecializationCatalog, w h return nil } +func encodeListMyConsentsResponse(response ListMyConsentsRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *ConsentRecordListHeaders: + 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 *ListMyConsentsBadRequest: + 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 *ListMyConsentsUnauthorized: + 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 encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CandidateInvitationListHeaders: 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 f13025d..aa8cb0a 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,16 +11,16 @@ import ( ) var ( - rn45AllowedHeaders = map[string]string{ + rn46AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn7AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn43AllowedHeaders = map[string]string{ + rn44AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn40AllowedHeaders = map[string]string{ + rn41AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn24AllowedHeaders = map[string]string{ @@ -29,7 +29,7 @@ var ( rn9AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn48AllowedHeaders = map[string]string{ + rn49AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn19AllowedHeaders = map[string]string{ @@ -44,7 +44,7 @@ var ( rn16AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn49AllowedHeaders = map[string]string{ + rn50AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } rn30AllowedHeaders = map[string]string{ @@ -59,13 +59,13 @@ var ( rn34AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } - rn42AllowedHeaders = map[string]string{ + rn43AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn47AllowedHeaders = map[string]string{ + rn48AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn50AllowedHeaders = map[string]string{ + rn51AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn15AllowedHeaders = map[string]string{ @@ -228,7 +228,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn45AllowedHeaders, + allowedHeaders: rn46AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -305,7 +305,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn43AllowedHeaders, + allowedHeaders: rn44AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -329,7 +329,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn40AllowedHeaders, + allowedHeaders: rn41AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -482,7 +482,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn48AllowedHeaders, + allowedHeaders: rn49AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -578,6 +578,31 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } + 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" if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" { @@ -748,7 +773,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn49AllowedHeaders, + allowedHeaders: rn50AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1031,7 +1056,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn42AllowedHeaders, + allowedHeaders: rn43AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1059,7 +1084,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn47AllowedHeaders, + allowedHeaders: rn48AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1089,7 +1114,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn50AllowedHeaders, + allowedHeaders: rn51AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1755,6 +1780,31 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } + 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" if l := len("invitations"); len(elem) >= l && elem[0:l] == "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 1ed1d03..c22d57f 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -3353,6 +3353,39 @@ type ConfirmEmailForbidden Problem func (*ConfirmEmailForbidden) confirmEmailRes() {} +// 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 +// current name. +// Ref: #/components/schemas/ConsentOrganization +type ConsentOrganization struct { + // Identifier of the organization. + ID uuid.UUID `json:"id"` + // Name of the organization in the consent text at the time of the consent. Plain text; clients show it + // as text, never as HTML. + Name string `json:"name"` +} + +// GetID returns the value of ID. +func (s *ConsentOrganization) GetID() uuid.UUID { + return s.ID +} + +// GetName returns the value of Name. +func (s *ConsentOrganization) GetName() string { + return s.Name +} + +// SetID sets the value of ID. +func (s *ConsentOrganization) SetID(val uuid.UUID) { + s.ID = val +} + +// SetName sets the value of Name. +func (s *ConsentOrganization) SetName(val string) { + s.Name = val +} + // 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. // Ref: #/components/schemas/ConsentPurpose @@ -3390,6 +3423,452 @@ func (s *ConsentPurpose) UnmarshalText(data []byte) error { } } +// One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes +// another. +// +// - c1: processing of personal data, given at registration. +// - 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 (TASK-088), not of this +// record. Adding a field scope to c2 records later is an additive change. +// - c3: automatic categorization. Without it the candidate can request a manual assessment by the +// same rubric. +// - c4: transfer of the selected contact data to one organization, currently given only in an +// invitation acceptance. +// - c5: import of FSP results. +// +// ConsentPurpose lists the subset whose text the client may read before an account exists. +// Ref: #/components/schemas/ConsentPurposeCode +type ConsentPurposeCode string + +const ( + ConsentPurposeCodeC1 ConsentPurposeCode = "c1" + ConsentPurposeCodeC2 ConsentPurposeCode = "c2" + ConsentPurposeCodeC3 ConsentPurposeCode = "c3" + ConsentPurposeCodeC4 ConsentPurposeCode = "c4" + ConsentPurposeCodeC5 ConsentPurposeCode = "c5" +) + +// AllValues returns all ConsentPurposeCode values. +func (ConsentPurposeCode) AllValues() []ConsentPurposeCode { + return []ConsentPurposeCode{ + ConsentPurposeCodeC1, + ConsentPurposeCodeC2, + ConsentPurposeCodeC3, + ConsentPurposeCodeC4, + ConsentPurposeCodeC5, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ConsentPurposeCode) MarshalText() ([]byte, error) { + switch s { + case ConsentPurposeCodeC1: + return []byte(s), nil + case ConsentPurposeCodeC2: + return []byte(s), nil + case ConsentPurposeCodeC3: + return []byte(s), nil + case ConsentPurposeCodeC4: + return []byte(s), nil + case ConsentPurposeCodeC5: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ConsentPurposeCode) UnmarshalText(data []byte) error { + switch ConsentPurposeCode(data) { + case ConsentPurposeCodeC1: + *s = ConsentPurposeCodeC1 + return nil + case ConsentPurposeCodeC2: + *s = ConsentPurposeCodeC2 + return nil + case ConsentPurposeCodeC3: + *s = ConsentPurposeCodeC3 + return nil + case ConsentPurposeCodeC4: + *s = ConsentPurposeCodeC4 + return nil + case ConsentPurposeCodeC5: + *s = ConsentPurposeCodeC5 + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One record of the consent ledger as its subject reads it: the purpose, the text version the subject +// accepted, where and when the consent was given, its state, and the revocation. A c4 record also +// names the organization, the contact fields, and the invitation with its terms version; these fields +// are null for every other purpose. The server also stores the SHA-256 hash of exactly the text the +// subject saw, which a client never sends or receives. +// Ref: #/components/schemas/ConsentRecord +type ConsentRecord struct { + // Identifier of the record. + ID uuid.UUID `json:"id"` + Purpose ConsentPurposeCode `json:"purpose"` + State ConsentState `json:"state"` + // Version of the consent text that the subject accepted. + TextVersion ConsentTextVersion `json:"text_version"` + Source ConsentSource `json:"source"` + GrantedAt Timestamp `json:"granted_at"` + // Moment of the revocation, or null unless `state` is `revoked`. + RevokedAt NilTimestamp `json:"revoked_at"` + // Who recorded the revocation, or null unless `state` is `revoked`. + RevocationSource NilConsentRevocationSource `json:"revocation_source"` + // Organization that a c4 consent allows to read the fields, with the name the consent text showed, or + // null for every other purpose. + Organization NilConsentOrganization `json:"organization"` + // Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies + // another. + Fields []ContactFieldKind `json:"fields"` + // Invitation whose acceptance gave a c4 consent, or null for every other purpose. + InvitationID NilUUID `json:"invitation_id"` + // Terms version that the acceptance accepted, or null for every other purpose. + InvitationTermsVersion NilInvitationTermsVersion `json:"invitation_terms_version"` +} + +// GetID returns the value of ID. +func (s *ConsentRecord) GetID() uuid.UUID { + return s.ID +} + +// GetPurpose returns the value of Purpose. +func (s *ConsentRecord) GetPurpose() ConsentPurposeCode { + return s.Purpose +} + +// GetState returns the value of State. +func (s *ConsentRecord) GetState() ConsentState { + return s.State +} + +// GetTextVersion returns the value of TextVersion. +func (s *ConsentRecord) GetTextVersion() ConsentTextVersion { + return s.TextVersion +} + +// GetSource returns the value of Source. +func (s *ConsentRecord) GetSource() ConsentSource { + return s.Source +} + +// GetGrantedAt returns the value of GrantedAt. +func (s *ConsentRecord) GetGrantedAt() Timestamp { + return s.GrantedAt +} + +// GetRevokedAt returns the value of RevokedAt. +func (s *ConsentRecord) GetRevokedAt() NilTimestamp { + return s.RevokedAt +} + +// GetRevocationSource returns the value of RevocationSource. +func (s *ConsentRecord) GetRevocationSource() NilConsentRevocationSource { + return s.RevocationSource +} + +// GetOrganization returns the value of Organization. +func (s *ConsentRecord) GetOrganization() NilConsentOrganization { + return s.Organization +} + +// GetFields returns the value of Fields. +func (s *ConsentRecord) GetFields() []ContactFieldKind { + return s.Fields +} + +// GetInvitationID returns the value of InvitationID. +func (s *ConsentRecord) GetInvitationID() NilUUID { + return s.InvitationID +} + +// GetInvitationTermsVersion returns the value of InvitationTermsVersion. +func (s *ConsentRecord) GetInvitationTermsVersion() NilInvitationTermsVersion { + return s.InvitationTermsVersion +} + +// SetID sets the value of ID. +func (s *ConsentRecord) SetID(val uuid.UUID) { + s.ID = val +} + +// SetPurpose sets the value of Purpose. +func (s *ConsentRecord) SetPurpose(val ConsentPurposeCode) { + s.Purpose = val +} + +// SetState sets the value of State. +func (s *ConsentRecord) SetState(val ConsentState) { + s.State = val +} + +// SetTextVersion sets the value of TextVersion. +func (s *ConsentRecord) SetTextVersion(val ConsentTextVersion) { + s.TextVersion = val +} + +// SetSource sets the value of Source. +func (s *ConsentRecord) SetSource(val ConsentSource) { + s.Source = val +} + +// SetGrantedAt sets the value of GrantedAt. +func (s *ConsentRecord) SetGrantedAt(val Timestamp) { + s.GrantedAt = val +} + +// SetRevokedAt sets the value of RevokedAt. +func (s *ConsentRecord) SetRevokedAt(val NilTimestamp) { + s.RevokedAt = val +} + +// SetRevocationSource sets the value of RevocationSource. +func (s *ConsentRecord) SetRevocationSource(val NilConsentRevocationSource) { + s.RevocationSource = val +} + +// SetOrganization sets the value of Organization. +func (s *ConsentRecord) SetOrganization(val NilConsentOrganization) { + s.Organization = val +} + +// SetFields sets the value of Fields. +func (s *ConsentRecord) SetFields(val []ContactFieldKind) { + s.Fields = val +} + +// SetInvitationID sets the value of InvitationID. +func (s *ConsentRecord) SetInvitationID(val NilUUID) { + s.InvitationID = val +} + +// SetInvitationTermsVersion sets the value of InvitationTermsVersion. +func (s *ConsentRecord) SetInvitationTermsVersion(val NilInvitationTermsVersion) { + s.InvitationTermsVersion = val +} + +// One page of the consent ledger of the current account, newest grant first. +// Ref: #/components/schemas/ConsentRecordList +type ConsentRecordList struct { + // Records of the page. + Items []ConsentRecord `json:"items"` + Page PageInfo `json:"page"` +} + +// GetItems returns the value of Items. +func (s *ConsentRecordList) GetItems() []ConsentRecord { + return s.Items +} + +// GetPage returns the value of Page. +func (s *ConsentRecordList) GetPage() PageInfo { + return s.Page +} + +// SetItems sets the value of Items. +func (s *ConsentRecordList) SetItems(val []ConsentRecord) { + s.Items = val +} + +// SetPage sets the value of Page. +func (s *ConsentRecordList) SetPage(val PageInfo) { + s.Page = val +} + +// ConsentRecordListHeaders wraps ConsentRecordList with response headers. +type ConsentRecordListHeaders struct { + CacheControl CacheControlNoStore + Response ConsentRecordList +} + +// GetCacheControl returns the value of CacheControl. +func (s *ConsentRecordListHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *ConsentRecordListHeaders) GetResponse() ConsentRecordList { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *ConsentRecordListHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *ConsentRecordListHeaders) SetResponse(val ConsentRecordList) { + s.Response = val +} + +func (*ConsentRecordListHeaders) listMyConsentsRes() {} + +// Who recorded a revocation. +// +// - consent_settings: the subject revoked the consent in the product. +// - support_request: an operator recorded a revocation that the subject requested through support. +// +// Ref: #/components/schemas/ConsentRevocationSource +type ConsentRevocationSource string + +const ( + ConsentRevocationSourceConsentSettings ConsentRevocationSource = "consent_settings" + ConsentRevocationSourceSupportRequest ConsentRevocationSource = "support_request" +) + +// AllValues returns all ConsentRevocationSource values. +func (ConsentRevocationSource) AllValues() []ConsentRevocationSource { + return []ConsentRevocationSource{ + ConsentRevocationSourceConsentSettings, + ConsentRevocationSourceSupportRequest, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ConsentRevocationSource) MarshalText() ([]byte, error) { + switch s { + case ConsentRevocationSourceConsentSettings: + return []byte(s), nil + case ConsentRevocationSourceSupportRequest: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ConsentRevocationSource) UnmarshalText(data []byte) error { + switch ConsentRevocationSource(data) { + case ConsentRevocationSourceConsentSettings: + *s = ConsentRevocationSourceConsentSettings + return nil + case ConsentRevocationSourceSupportRequest: + *s = ConsentRevocationSourceSupportRequest + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Where the subject gave the consent. +// +// - registration: the c1 acceptance of RegisterAccount. +// - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 +// and TASK-064). +// - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. +// +// A c4 given when sending an application (PRD Q9) is planned as an additional value. +// Ref: #/components/schemas/ConsentSource +type ConsentSource string + +const ( + ConsentSourceRegistration ConsentSource = "registration" + ConsentSourceConsentSettings ConsentSource = "consent_settings" + ConsentSourceInvitationAcceptance ConsentSource = "invitation_acceptance" +) + +// AllValues returns all ConsentSource values. +func (ConsentSource) AllValues() []ConsentSource { + return []ConsentSource{ + ConsentSourceRegistration, + ConsentSourceConsentSettings, + ConsentSourceInvitationAcceptance, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ConsentSource) MarshalText() ([]byte, error) { + switch s { + case ConsentSourceRegistration: + return []byte(s), nil + case ConsentSourceConsentSettings: + return []byte(s), nil + case ConsentSourceInvitationAcceptance: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ConsentSource) UnmarshalText(data []byte) error { + switch ConsentSource(data) { + case ConsentSourceRegistration: + *s = ConsentSourceRegistration + return nil + case ConsentSourceConsentSettings: + *s = ConsentSourceConsentSettings + return nil + case ConsentSourceInvitationAcceptance: + *s = ConsentSourceInvitationAcceptance + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// State of a consent record, computed from the ledger. +// +// - active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its +// purpose; every unrevoked c4 record is active, one per accepted invitation. +// - superseded: the subject later accepted another text version of the same purpose and has not +// revoked either. The record stays as evidence for its own time; it never applies to c4. +// - revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later +// grant is a new record and never reopens it. +// +// Ref: #/components/schemas/ConsentState +type ConsentState string + +const ( + ConsentStateActive ConsentState = "active" + ConsentStateSuperseded ConsentState = "superseded" + ConsentStateRevoked ConsentState = "revoked" +) + +// AllValues returns all ConsentState values. +func (ConsentState) AllValues() []ConsentState { + return []ConsentState{ + ConsentStateActive, + ConsentStateSuperseded, + ConsentStateRevoked, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ConsentState) MarshalText() ([]byte, error) { + switch s { + case ConsentStateActive: + return []byte(s), nil + case ConsentStateSuperseded: + return []byte(s), nil + case ConsentStateRevoked: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ConsentState) UnmarshalText(data []byte) error { + switch ConsentState(data) { + case ConsentStateActive: + *s = ConsentStateActive + return nil + case ConsentStateSuperseded: + *s = ConsentStateSuperseded + return nil + case ConsentStateRevoked: + *s = ConsentStateRevoked + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Currently published consent text. The server stores an acceptance with `text_version` and the hash // of exactly this text. // Ref: #/components/schemas/ConsentText @@ -6367,6 +6846,14 @@ func NewPracticeItemContentItemContent(v PracticeItemContent) ItemContent { return s } +type ListMyConsentsBadRequest Problem + +func (*ListMyConsentsBadRequest) listMyConsentsRes() {} + +type ListMyConsentsUnauthorized Problem + +func (*ListMyConsentsUnauthorized) listMyConsentsRes() {} + type ListMyInvitationsBadRequest Problem func (*ListMyInvitationsBadRequest) listMyInvitationsRes() {} @@ -9105,6 +9592,96 @@ func (o NilCandidateExperience) Or(d CandidateExperience) CandidateExperience { return d } +// NewNilConsentOrganization returns new NilConsentOrganization with value set to v. +func NewNilConsentOrganization(v ConsentOrganization) NilConsentOrganization { + return NilConsentOrganization{ + Value: v, + } +} + +// NilConsentOrganization is nullable ConsentOrganization. +type NilConsentOrganization struct { + Value ConsentOrganization + Null bool +} + +// SetTo sets value to v. +func (o *NilConsentOrganization) SetTo(v ConsentOrganization) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilConsentOrganization) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilConsentOrganization) SetToNull() { + o.Null = true + var v ConsentOrganization + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilConsentOrganization) Get() (v ConsentOrganization, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilConsentOrganization) Or(d ConsentOrganization) ConsentOrganization { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilConsentRevocationSource returns new NilConsentRevocationSource with value set to v. +func NewNilConsentRevocationSource(v ConsentRevocationSource) NilConsentRevocationSource { + return NilConsentRevocationSource{ + Value: v, + } +} + +// NilConsentRevocationSource is nullable ConsentRevocationSource. +type NilConsentRevocationSource struct { + Value ConsentRevocationSource + Null bool +} + +// SetTo sets value to v. +func (o *NilConsentRevocationSource) SetTo(v ConsentRevocationSource) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilConsentRevocationSource) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilConsentRevocationSource) SetToNull() { + o.Null = true + var v ConsentRevocationSource + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilConsentRevocationSource) Get() (v ConsentRevocationSource, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilConsentRevocationSource) Or(d ConsentRevocationSource) ConsentRevocationSource { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilContactAccessBlock returns new NilContactAccessBlock with value set to v. func NewNilContactAccessBlock(v ContactAccessBlock) NilContactAccessBlock { return NilContactAccessBlock{ @@ -9825,6 +10402,51 @@ func (o NilInvitationNeedReference) Or(d InvitationNeedReference) InvitationNeed return d } +// NewNilInvitationTermsVersion returns new NilInvitationTermsVersion with value set to v. +func NewNilInvitationTermsVersion(v InvitationTermsVersion) NilInvitationTermsVersion { + return NilInvitationTermsVersion{ + Value: v, + } +} + +// NilInvitationTermsVersion is nullable InvitationTermsVersion. +type NilInvitationTermsVersion struct { + Value InvitationTermsVersion + Null bool +} + +// SetTo sets value to v. +func (o *NilInvitationTermsVersion) SetTo(v InvitationTermsVersion) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilInvitationTermsVersion) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilInvitationTermsVersion) SetToNull() { + o.Null = true + var v InvitationTermsVersion + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilInvitationTermsVersion) Get() (v InvitationTermsVersion, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilInvitationTermsVersion) Or(d InvitationTermsVersion) InvitationTermsVersion { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilNeedDomainName returns new NilNeedDomainName with value set to v. func NewNilNeedDomainName(v NeedDomainName) NilNeedDomainName { return NilNeedDomainName{ @@ -11114,6 +11736,52 @@ func (s *OnboardingStep) UnmarshalText(data []byte) error { } } +// NewOptConsentState returns new OptConsentState with value set to v. +func NewOptConsentState(v ConsentState) OptConsentState { + return OptConsentState{ + Value: v, + Set: true, + } +} + +// OptConsentState is optional ConsentState. +type OptConsentState struct { + Value ConsentState + Set bool +} + +// IsSet returns true if OptConsentState was set. +func (o OptConsentState) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptConsentState) Reset() { + var v ConsentState + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptConsentState) SetTo(v ConsentState) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptConsentState) Get() (v ConsentState, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptConsentState) Or(d ConsentState) ConsentState { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewOptInt32 returns new OptInt32 with value set to v. func NewOptInt32(v int32) OptInt32 { return OptInt32{ 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 071d6f5..e64cec3 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -75,6 +75,7 @@ var operationRolesSessionCookie = map[string][]string{ GetOrganizationInvitationOperation: []string{}, GetOrganizationInvitationContactsOperation: []string{}, GetOrganizationNeedOperation: []string{}, + ListMyConsentsOperation: []string{}, ListMyInvitationsOperation: []string{}, ListMySupportCasesOperation: []string{}, ListOrganizationInvitationsOperation: []string{}, 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 d13d6d2..5360930 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -718,6 +718,35 @@ type Handler interface { // // GET /api/v1/specializations GetSpecializationCatalog(ctx context.Context) (*SpecializationCatalog, error) + // ListMyConsents implements ListMyConsents operation. + // + // Requires the session cookie of a candidate or an employer account. The subject comes from the + // session, never from a request parameter, so the response holds only the caller's own consents: no + // request can name another account, and records of other accounts are never listed. Returns a page of + // the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with + // cursor pagination. + // + // The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the + // source, and the grant time; the server also stores the hash of exactly the text the subject saw. A + // newer text version of the same purpose is a new record, and the earlier one becomes `superseded` + // without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one + // organization, once; a later grant is a new record. Purposes are independent. + // + // 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 (TASK-088). + // + // Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations + // of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation. + // + // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed + // `limit`, `cursor`, or `state` answers 400 validation_failed. + // + // GET /api/v1/me/consents + ListMyConsents(ctx context.Context, params ListMyConsentsParams) (ListMyConsentsRes, error) // ListMyInvitations implements ListMyInvitations operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from 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 1f99eac..1c5c3c7 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -792,6 +792,38 @@ func (UnimplementedHandler) GetSpecializationCatalog(ctx context.Context) (r *Sp return r, ht.ErrNotImplemented } +// ListMyConsents implements ListMyConsents operation. +// +// Requires the session cookie of a candidate or an employer account. The subject comes from the +// session, never from a request parameter, so the response holds only the caller's own consents: no +// request can name another account, and records of other accounts are never listed. Returns a page of +// the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with +// cursor pagination. +// +// The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the +// source, and the grant time; the server also stores the hash of exactly the text the subject saw. A +// newer text version of the same purpose is a new record, and the earlier one becomes `superseded` +// without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one +// organization, once; a later grant is a new record. Purposes are independent. +// +// 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 (TASK-088). +// +// Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations +// of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed +// `limit`, `cursor`, or `state` answers 400 validation_failed. +// +// GET /api/v1/me/consents +func (UnimplementedHandler) ListMyConsents(ctx context.Context, params ListMyConsentsParams) (r ListMyConsentsRes, _ error) { + return r, ht.ErrNotImplemented +} + // ListMyInvitations implements ListMyInvitations operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from 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 5d1d22b..48fd99c 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -3405,6 +3405,41 @@ func (s *ConfirmEmailForbidden) Validate() error { return nil } +func (s *ConsentOrganization) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Name)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "name", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s ConsentPurpose) Validate() error { switch s { case "c1": @@ -3414,6 +3449,302 @@ func (s ConsentPurpose) Validate() error { } } +func (s ConsentPurposeCode) Validate() error { + switch s { + case "c1": + return nil + case "c2": + return nil + case "c3": + return nil + case "c4": + return nil + case "c5": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ConsentRecord) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Purpose.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "purpose", + Error: err, + }) + } + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + 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.Source.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if err := func() error { + if value, ok := s.RevocationSource.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "revocation_source", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Organization.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "organization", + Error: err, + }) + } + if err := func() error { + if s.Fields == nil { + return nil // null + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4, + MaxLengthSet: true, + }).ValidateLength(len(s.Fields)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.Fields); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Fields { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "fields", + Error: err, + }) + } + if err := func() error { + if value, ok := s.InvitationTermsVersion.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "invitation_terms_version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ConsentRecordList) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Items == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 100, + MaxLengthSet: true, + }).ValidateLength(len(s.Items)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Items { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "items", + Error: err, + }) + } + if err := func() error { + if err := s.Page.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "page", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ConsentRecordListHeaders) 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 ConsentRevocationSource) Validate() error { + switch s { + case "consent_settings": + return nil + case "support_request": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s ConsentSource) Validate() error { + switch s { + case "registration": + return nil + case "consent_settings": + return nil + case "invitation_acceptance": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s ConsentState) Validate() error { + switch s { + case "active": + return nil + case "superseded": + return nil + case "revoked": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *ConsentText) Validate() error { if s == nil { return validate.ErrNilPointer @@ -6139,6 +6470,22 @@ func (s ItemContent) Validate() error { } } +func (s *ListMyConsentsBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyConsentsUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *ListMyInvitationsBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index bc7cdcb..337b6a6 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -9,6 +9,7 @@ import ( "log/slog" "net/http" "net/http/httptest" + "reflect" "strings" "testing" "time" @@ -1884,6 +1885,94 @@ func TestInvitationDTOsCarryNoContactOrMinimum(t *testing.T) { } } +// myConsentsPath is the consent ledger of the session account. +const myConsentsPath = "/api/v1/me/consents" + +// The schema alone must accept the read of the own ledger with an optional +// state filter and reject an unknown state and malformed page parameters. +// Security accepts the session here, so the request reaches validation; a +// valid request then answers 501 until the ledger read is implemented. +func TestConsentSchemaValidationPrecedesImplementation(t *testing.T) { + session := map[string]string{"Cookie": testSessionCookie} + for _, test := range []struct { + name string + query string + pointer string + }{ + {name: "the whole history", query: ""}, + {name: "the active consents", query: "?state=active"}, + {name: "the revoked consents of the next page", query: "?state=revoked&limit=50&cursor=b3BhcXVlLWN1cnNvcg"}, + {name: "an unknown state", query: "?state=granted", pointer: "/state"}, + {name: "a purpose instead of a state", query: "?state=c4", pointer: "/state"}, + {name: "a limit over 100", query: "?limit=101", pointer: "/limit"}, + {name: "a malformed cursor", query: "?cursor=not%20a%20cursor", pointer: "/cursor"}, + } { + t.Run(test.name, func(t *testing.T) { + logger := slog.New(slog.DiscardHandler) + healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + response := serveIdentityRequest(t, router, identityRequest{method: http.MethodGet, path: myConsentsPath + test.query, headers: session}) + + if test.pointer == "" { + requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented) + return + } + body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed) + want := api.ProblemFieldError{In: api.ProblemFieldLocationQuery, Pointer: test.pointer, Code: "invalid"} + for _, field := range body.Errors { + if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code { + return + } + } + t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want) + }) + } +} + +// The ledger read requires a session; DenyAllSecurity grants none, with or +// without a cookie, and a request cannot name another subject instead. +func TestConsentAccessBeforeImplementation(t *testing.T) { + for _, test := range []identityRequest{ + {method: http.MethodGet, path: myConsentsPath}, + {method: http.MethodGet, path: myConsentsPath + "?state=active", headers: map[string]string{"Cookie": testSessionCookie}}, + {method: http.MethodGet, path: myConsentsPath + "?subject_id=01928f7a-0000-7000-8000-00000000c0de", headers: map[string]string{"Cookie": testSessionCookie}}, + } { + t.Run(test.method+" "+test.path, func(t *testing.T) { + router := newTestRouter(t, func(context.Context) error { return nil }) + requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated) + }) + } +} + +// The read model never carries the stored text hash, a subject, or a contact +// value, and its parameters cannot select a subject. +func TestConsentDTOsCarryNoHashSubjectOrContact(t *testing.T) { + private := []string{"text_hash", "hash", "body_sha256", "subject_id", "user_id", "account_id", "email", "phone", "telegram", "full_name"} + for _, dto := range []any{api.ConsentRecord{}, api.ConsentRecordList{}, api.ConsentOrganization{}} { + assertNoJSONFields(t, dto, private) + } + params := reflect.TypeFor[api.ListMyConsentsParams]() + names := make([]string, 0, params.NumField()) + for i := range params.NumField() { + names = append(names, params.Field(i).Name) + } + if got := strings.Join(names, ","); got != "State,Limit,Cursor" { + t.Fatalf("ListMyConsentsParams fields = %s, want only the state filter and the page", got) + } + + // The documented example is a valid response of the generated server. + var page api.ConsentRecordList + if err := page.UnmarshalJSON(supportCaseExample(t, "ConsentRecordListPage")); err != nil { + t.Fatalf("decode the ConsentRecordListPage example: %v", err) + } + if err := page.Validate(); err != nil { + t.Fatalf("validate the ConsentRecordListPage example: %v", err) + } +} + func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) { var logs bytes.Buffer logger := slog.New(slog.NewJSONHandler(&logs, nil)) diff --git a/backend/internal/adapter/secondary/postgres/consents.go b/backend/internal/adapter/secondary/postgres/consents.go new file mode 100644 index 0000000..78427af --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/consents.go @@ -0,0 +1,376 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// consentConstraintErrors maps the consent constraints whose violation is a +// caller-visible outcome to port sentinels by SQLSTATE and constraint name, +// 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, + // 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, + {integrityConstraintViolationCode, "consent_records_retained"}: outbound.ErrConsentRecordImmutable, + {integrityConstraintViolationCode, "consent_records_immutable"}: outbound.ErrConsentRecordImmutable, +} + +// mapConsentError turns a known consent constraint or trigger error into its +// port sentinel and keeps the constraint name. Any other PostgreSQL error is +// replaced by its SQLSTATE and constraint name, because its detail can quote +// the subject, the organization, or the field set. Deadlocks and +// serialization failures also match ErrTransactionConflict. A connection +// error loses the pgx prefix that names the database user and database. +func mapConsentError(err error) error { + var pgError *pgconn.PgError + if !errors.As(err, &pgError) { + return sanitizeConnectError(err) + } + if sentinel, ok := consentConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok { + return fmt.Errorf("postgres.mapConsentError - violate constraint %s: %w", pgError.ConstraintName, sentinel) + } + return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}) +} + +// ConsentStore provides the consent repositories outside a transaction. +// Every call runs as its own statement on a pool connection. Called with a +// context that belongs to a Transactor callback, it fails with +// outbound.ErrNestedTransaction; use the UnitOfWork accessors there. +type ConsentStore struct { + queries *sqlc.Queries +} + +func NewConsentStore(pool *pgxpool.Pool) *ConsentStore { + return &ConsentStore{queries: sqlc.New(standaloneDB{pool: pool})} +} + +var ( + _ outbound.ConsentRepositories = (*ConsentStore)(nil) + _ outbound.ConsentRepositories = (*UnitOfWork)(nil) +) + +func (store *ConsentStore) ConsentTexts() outbound.ConsentTextRepository { + return consentTextRepository{queries: store.queries} +} + +func (store *ConsentStore) ConsentLedger() outbound.ConsentLedger { + return consentLedger{queries: store.queries} +} + +func (unit *UnitOfWork) ConsentTexts() outbound.ConsentTextRepository { + return consentTextRepository{queries: unit.queries} +} + +func (unit *UnitOfWork) ConsentLedger() outbound.ConsentLedger { + return consentLedger{queries: unit.queries} +} + +type consentTextRepository struct { + queries *sqlc.Queries +} + +func (repository consentTextRepository) Get( + ctx context.Context, + purpose domain.ConsentPurpose, + version domain.ConsentTextVersion, +) (domain.ConsentText, error) { + row, err := repository.queries.GetConsentText(ctx, sqlc.GetConsentTextParams{Purpose: string(purpose), Version: string(version)}) + if err != nil { + return domain.ConsentText{}, fmt.Errorf("consentTextRepository.Get - select consent text: %w", mapConsentNoRows(err, outbound.ErrConsentTextNotFound)) + } + return consentTextFromRow(row) +} + +func (repository consentTextRepository) Current(ctx context.Context, purpose domain.ConsentPurpose, at time.Time) (domain.ConsentText, error) { + if err := requireTime("consentTextRepository.Current", at, domain.ErrInvalidConsentText); err != nil { + return domain.ConsentText{}, err + } + row, err := repository.queries.GetCurrentConsentText(ctx, sqlc.GetCurrentConsentTextParams{Purpose: string(purpose), At: pgTime(at)}) + if err != nil { + return domain.ConsentText{}, fmt.Errorf("consentTextRepository.Current - select consent text: %w", mapConsentNoRows(err, outbound.ErrConsentTextNotFound)) + } + return consentTextFromRow(row) +} + +func consentTextFromRow(row sqlc.ConsentText) (domain.ConsentText, error) { + text, err := domain.RestoreConsentText(domain.StoredConsentText{ + Purpose: row.Purpose, + Version: row.Version, + Body: row.Body, + Hash: row.BodySha256, + Kind: row.Kind, + PublishedAt: row.PublishedAt.Time, + }) + if err != nil { + return domain.ConsentText{}, fmt.Errorf("postgres.consentTextFromRow - restore consent text: %w", err) + } + return text, nil +} + +type consentLedger struct { + queries *sqlc.Queries +} + +var _ outbound.ConsentLedger = consentLedger{} + +func (ledger consentLedger) Grant(ctx context.Context, grant domain.ConsentGrant) (domain.ConsentRecord, bool, error) { + if grant.IsZero() { + return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - grant was not built by domain.NewConsentGrant: %w", domain.ErrInvalidConsent) + } + hash := grant.TextHash() + row, err := ledger.queries.InsertConsentRecord(ctx, sqlc.InsertConsentRecordParams{ + ID: pgUUID(grant.ID()), + SubjectID: pgUUID(grant.SubjectID()), + Purpose: string(grant.Purpose()), + TextVersion: string(grant.TextVersion()), + TextHash: hash[:], + Source: string(grant.Source()), + GrantedAt: pgTime(grant.GrantedAt()), + }) + if err == nil { + record, err := consentRecordFromRow(consentRecordRow(row)) + return record, err == nil, err + } + if !errors.Is(err, pgx.ErrNoRows) { + return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - insert consent record: %w", mapConsentError(err)) + } + existing, err := ledger.queries.GetUnrevokedConsentRecordByVersion(ctx, sqlc.GetUnrevokedConsentRecordByVersionParams{ + SubjectID: pgUUID(grant.SubjectID()), + Purpose: string(grant.Purpose()), + TextVersion: string(grant.TextVersion()), + }) + if errors.Is(err, pgx.ErrNoRows) { + // The conflicting record was revoked between the two statements. A + // retry of the operation inserts a new record. + return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - conflicting record was revoked concurrently: %w", outbound.ErrTransactionConflict) + } + if err != nil { + return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - select existing consent record: %w", mapConsentError(err)) + } + record, err := consentRecordFromRow(consentRecordRow(existing)) + return record, false, err +} + +func (ledger consentLedger) GrantContact(ctx context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) { + if grant.IsZero() { + return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - grant was not built by domain.NewContactConsentGrant: %w", domain.ErrInvalidConsent) + } + hash := grant.TextHash() + row, err := ledger.queries.InsertContactConsentRecord(ctx, sqlc.InsertContactConsentRecordParams{ + ID: pgUUID(grant.ID()), + SubjectID: pgUUID(grant.SubjectID()), + TextVersion: string(grant.TextVersion()), + TextHash: hash[:], + OrganizationID: pgUUID(grant.OrganizationID()), + OrganizationName: pgtype.Text{String: grant.OrganizationName(), Valid: true}, + FieldSet: contactFieldStrings(grant.Fields()), + InvitationID: pgUUID(grant.InvitationID()), + InvitationTermsVersion: pgtype.Int8{Int64: grant.InvitationTermsVersion(), Valid: true}, + GrantedAt: pgTime(grant.GrantedAt()), + }) + if err == nil { + record, err := consentRecordFromRow(consentRecordRow(row)) + return record, err == nil, err + } + if !errors.Is(err, pgx.ErrNoRows) { + return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - insert consent record: %w", mapConsentError(err)) + } + existing, err := ledger.queries.GetContactConsentRecordByInvitation(ctx, sqlc.GetContactConsentRecordByInvitationParams{ + SubjectID: pgUUID(grant.SubjectID()), + InvitationID: pgUUID(grant.InvitationID()), + }) + if errors.Is(err, pgx.ErrNoRows) { + return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - select existing consent record: %w", outbound.ErrConsentInvitationTaken) + } + if err != nil { + return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - select existing consent record: %w", mapConsentError(err)) + } + record, err := consentRecordFromRow(consentRecordRow(existing)) + return record, false, err +} + +func (ledger consentLedger) Revoke(ctx context.Context, revocation domain.ConsentRevocation) ([]domain.ConsentRecord, error) { + if revocation.IsZero() { + return nil, fmt.Errorf("consentLedger.Revoke - revocation was not built by domain.NewConsentRevocation: %w", domain.ErrInvalidConsent) + } + source := pgtype.Text{String: string(revocation.Source()), Valid: true} + if revocation.Purpose().OrganizationScoped() { + rows, err := ledger.queries.RevokeContactConsentRecords(ctx, sqlc.RevokeContactConsentRecordsParams{ + RevokedAt: pgTime(revocation.RevokedAt()), + RevocationSource: source, + SubjectID: pgUUID(revocation.SubjectID()), + OrganizationID: pgUUID(revocation.OrganizationID()), + }) + if err != nil { + return nil, fmt.Errorf("consentLedger.Revoke - revoke contact consent records: %w", mapConsentError(err)) + } + return consentRecordsFromRows(rows, func(row sqlc.RevokeContactConsentRecordsRow) consentRecordRow { return consentRecordRow(row) }) + } + rows, err := ledger.queries.RevokeConsentRecords(ctx, sqlc.RevokeConsentRecordsParams{ + RevokedAt: pgTime(revocation.RevokedAt()), + RevocationSource: source, + SubjectID: pgUUID(revocation.SubjectID()), + Purpose: string(revocation.Purpose()), + }) + if err != nil { + return nil, fmt.Errorf("consentLedger.Revoke - revoke consent records: %w", mapConsentError(err)) + } + return consentRecordsFromRows(rows, func(row sqlc.RevokeConsentRecordsRow) consentRecordRow { return consentRecordRow(row) }) +} + +func (ledger consentLedger) Current(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) { + if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil { + return domain.ConsentRecord{}, fmt.Errorf("consentLedger.Current - validate purpose: %w", err) + } + if purpose.OrganizationScoped() { + return domain.ConsentRecord{}, fmt.Errorf("consentLedger.Current - C4 is read per organization with CurrentContact: %w", domain.ErrInvalidConsent) + } + row, err := ledger.queries.GetCurrentConsentRecord(ctx, sqlc.GetCurrentConsentRecordParams{SubjectID: pgUUID(subjectID), Purpose: string(purpose)}) + if err != nil { + return domain.ConsentRecord{}, fmt.Errorf("consentLedger.Current - select consent record: %w", mapConsentNoRows(err, outbound.ErrConsentNotFound)) + } + return consentRecordFromRow(consentRecordRow(row)) +} + +func (ledger consentLedger) CurrentContact(ctx context.Context, subjectID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) { + rows, err := ledger.queries.ListCurrentContactConsentRecords(ctx, sqlc.ListCurrentContactConsentRecordsParams{ + SubjectID: pgUUID(subjectID), + OrganizationID: pgUUID(organizationID), + }) + if err != nil { + return nil, fmt.Errorf("consentLedger.CurrentContact - select consent records: %w", mapConsentError(err)) + } + return consentRecordsFromRows(rows, func(row sqlc.ListCurrentContactConsentRecordsRow) consentRecordRow { return consentRecordRow(row) }) +} + +func (ledger consentLedger) List(ctx context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) { + const location = "consentLedger.List" + if query.SubjectID == uuid.Nil { + return outbound.ConsentPage{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, domain.ErrInvalidConsent) + } + if query.Limit < 1 || query.Limit > outbound.MaxConsentPageSize { + return outbound.ConsentPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxConsentPageSize, domain.ErrInvalidConsent) + } + params := sqlc.ListConsentRecordsParams{ + SubjectID: pgUUID(query.SubjectID), + // One extra row tells whether another page follows. + RowLimit: query.Limit + 1, + } + if query.State != "" { + if _, err := domain.ParseConsentState(string(query.State)); err != nil { + return outbound.ConsentPage{}, fmt.Errorf("%s - validate state: %w", location, err) + } + params.State = pgtype.Text{String: string(query.State), Valid: true} + } + if query.After != nil { + if err := requireTime(location, query.After.GrantedAt, domain.ErrInvalidConsent); err != nil { + return outbound.ConsentPage{}, err + } + params.AfterGrantedAt = pgTime(query.After.GrantedAt) + params.AfterID = pgUUID(query.After.ID) + } + rows, err := ledger.queries.ListConsentRecords(ctx, params) + if err != nil { + return outbound.ConsentPage{}, fmt.Errorf("%s - select consent records: %w", location, mapConsentError(err)) + } + page := outbound.ConsentPage{HasMore: len(rows) > int(query.Limit)} + if page.HasMore { + rows = rows[:query.Limit] + } + page.Records, err = consentRecordsFromRows(rows, func(row sqlc.ListConsentRecordsRow) consentRecordRow { return consentRecordRow(row) }) + if err != nil { + return outbound.ConsentPage{}, err + } + return page, nil +} + +// consentRecordRow has the columns that every record query returns. The +// generated row types of those queries convert to it. +type consentRecordRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + State string +} + +func consentRecordFromRow(row consentRecordRow) (domain.ConsentRecord, error) { + record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{ + ID: optionalUUID(row.ID), + SubjectID: optionalUUID(row.SubjectID), + Purpose: row.Purpose, + TextVersion: row.TextVersion, + TextHash: row.TextHash, + Source: row.Source, + State: row.State, + GrantedAt: row.GrantedAt.Time, + RevokedAt: optionalTime(row.RevokedAt), + RevocationSource: row.RevocationSource.String, + OrganizationID: optionalUUID(row.OrganizationID), + OrganizationName: row.OrganizationName.String, + FieldSet: row.FieldSet, + InvitationID: optionalUUID(row.InvitationID), + InvitationTermsVersion: row.InvitationTermsVersion.Int64, + }) + if err != nil { + return domain.ConsentRecord{}, fmt.Errorf("postgres.consentRecordFromRow - restore consent record: %w", err) + } + return record, nil +} + +func consentRecordsFromRows[Row any](rows []Row, convert func(Row) consentRecordRow) ([]domain.ConsentRecord, error) { + records := make([]domain.ConsentRecord, 0, len(rows)) + for _, row := range rows { + record, err := consentRecordFromRow(convert(row)) + if err != nil { + return nil, err + } + records = append(records, record) + } + return records, nil +} + +func contactFieldStrings(set domain.ContactFieldSet) []string { + fields := set.Fields() + values := make([]string, 0, len(fields)) + for _, field := range fields { + values = append(values, string(field)) + } + return values +} + +func mapConsentNoRows(err, sentinel error) error { + if errors.Is(err, pgx.ErrNoRows) { + return sentinel + } + return mapConsentError(err) +} diff --git a/backend/internal/adapter/secondary/postgres/consents_test.go b/backend/internal/adapter/secondary/postgres/consents_test.go new file mode 100644 index 0000000..be897c9 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/consents_test.go @@ -0,0 +1,211 @@ +package postgres + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// consentDetailMarker stands for a row value that a PostgreSQL detail can +// quote, such as the subject or the field set. +const consentDetailMarker = "Key (subject_id)=(01928f7a-0000-7000-8000-00000000c0de)" + +func TestMapConsentErrorRecognizesLedgerConstraints(t *testing.T) { + for _, test := range []struct { + code string + constraint string + want error + }{ + {code: foreignKeyViolationCode, constraint: "consent_records_subject_id_fkey", want: outbound.ErrUserNotFound}, + {code: foreignKeyViolationCode, constraint: "consent_records_text_fkey", want: outbound.ErrConsentTextNotFound}, + {code: foreignKeyViolationCode, constraint: "consent_records_published_text_fkey", want: outbound.ErrConsentTextMismatch}, + {code: checkViolationCode, constraint: "consent_records_text_published", want: outbound.ErrConsentTextNotPublished}, + {code: checkViolationCode, constraint: "consent_records_c4_text_hash", want: outbound.ErrConsentTextMismatch}, + {code: checkViolationCode, constraint: "consent_records_revocation_stamp", want: domain.ErrInvalidConsent}, + {code: integrityConstraintViolationCode, constraint: "consent_records_retained", want: outbound.ErrConsentRecordImmutable}, + {code: integrityConstraintViolationCode, constraint: "consent_records_immutable", want: outbound.ErrConsentRecordImmutable}, + } { + err := mapConsentError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: consentDetailMarker}) + if !errors.Is(err, test.want) { + t.Fatalf("mapConsentError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want) + } + if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "subject_id)=") { + t.Fatalf("mapConsentError(%s) = %v, want the constraint name and no detail", test.constraint, err) + } + } +} + +func TestMapConsentErrorDropsDetailOfOtherErrors(t *testing.T) { + // A CHECK violation that the domain should have prevented keeps only the + // SQLSTATE and the constraint, never the failing row. + original := &pgconn.PgError{Code: checkViolationCode, ConstraintName: "consent_records_c4_scope", Detail: "Failing row contains (" + consentDetailMarker + ", {email,phone})."} + err := mapConsentError(original) + var stateError sqlStateError + if !errors.As(err, &stateError) || stateError.SQLState() != checkViolationCode { + t.Fatalf("mapConsentError() = %v, want SQLSTATE %s", err, checkViolationCode) + } + if strings.Contains(err.Error(), "Failing row") || strings.Contains(err.Error(), "phone") { + t.Fatalf("mapConsentError() = %v, want no row values", err) + } + if err := mapConsentError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(err, outbound.ErrTransactionConflict) { + t.Fatalf("mapConsentError(deadlock) = %v, want ErrTransactionConflict", err) + } + if err := mapConsentError(context.Canceled); !errors.Is(err, context.Canceled) { + t.Fatalf("mapConsentError(context.Canceled) = %v, want the original error", err) + } +} + +func TestConsentLedgerRejectsInvalidInputBeforeQuerying(t *testing.T) { + // A ledger without queries proves that no statement runs. + ledger := consentLedger{} + ctx := t.Context() + subject := uuid.Must(uuid.NewV7()) + if _, _, err := ledger.Grant(ctx, domain.ConsentGrant{}); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("Grant(zero grant) error = %v, want ErrInvalidConsent", err) + } + if _, _, err := ledger.GrantContact(ctx, domain.ContactConsentGrant{}); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("GrantContact(zero grant) error = %v, want ErrInvalidConsent", err) + } + if _, err := ledger.Revoke(ctx, domain.ConsentRevocation{}); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("Revoke(zero revocation) error = %v, want ErrInvalidConsent", err) + } + if _, err := ledger.Current(ctx, subject, domain.ConsentPurposeContactDisclosure); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("Current(C4) error = %v, want ErrInvalidConsent", err) + } + if _, err := ledger.Current(ctx, subject, "c9"); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("Current(unknown purpose) error = %v, want ErrInvalidConsent", err) + } + for _, query := range []outbound.ConsentListQuery{ + {Limit: 10}, + {SubjectID: subject, Limit: 0}, + {SubjectID: subject, Limit: outbound.MaxConsentPageSize + 1}, + {SubjectID: subject, Limit: 10, State: "pending"}, + {SubjectID: subject, Limit: 10, After: &outbound.ConsentListPosition{ID: subject}}, + } { + if _, err := ledger.List(ctx, query); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("List(%+v) error = %v, want ErrInvalidConsent", query, err) + } + } + if _, err := (consentTextRepository{}).Current(ctx, domain.ConsentPurposePersonalData, time.Time{}); !errors.Is(err, domain.ErrInvalidConsentText) { + t.Fatalf("ConsentTexts.Current(zero time) error = %v, want ErrInvalidConsentText", err) + } +} + +// Every record query returns the same columns, so each generated row type +// converts to consentRecordRow. A query that changes its columns breaks this +// test at compile time instead of mapping a column wrongly. +var ( + _ = consentRecordRow(sqlc.InsertConsentRecordRow{}) + _ = consentRecordRow(sqlc.InsertContactConsentRecordRow{}) + _ = consentRecordRow(sqlc.GetUnrevokedConsentRecordByVersionRow{}) + _ = consentRecordRow(sqlc.GetContactConsentRecordByInvitationRow{}) + _ = consentRecordRow(sqlc.GetCurrentConsentRecordRow{}) + _ = consentRecordRow(sqlc.ListCurrentContactConsentRecordsRow{}) + _ = consentRecordRow(sqlc.RevokeConsentRecordsRow{}) + _ = consentRecordRow(sqlc.RevokeContactConsentRecordsRow{}) + _ = consentRecordRow(sqlc.ListConsentRecordsRow{}) +) + +func TestConsentRecordFromRowMapsNullableScope(t *testing.T) { + grantedAt := time.Date(2026, 10, 6, 9, 30, 0, 0, time.UTC) + hash := domain.HashConsentText("shown text") + subject := uuid.Must(uuid.NewV7()) + organization := uuid.Must(uuid.NewV7()) + invitation := uuid.Must(uuid.NewV7()) + + contact, err := consentRecordFromRow(consentRecordRow{ + ID: pgUUID(uuid.Must(uuid.NewV7())), + SubjectID: pgUUID(subject), + Purpose: "c4", + TextVersion: "c4-2026-10-01", + TextHash: hash[:], + Source: "invitation_acceptance", + OrganizationID: pgUUID(organization), + OrganizationName: pgtype.Text{String: "Acme", Valid: true}, + FieldSet: []string{"email", "phone"}, + InvitationID: pgUUID(invitation), + InvitationTermsVersion: pgtype.Int8{Int64: 3, Valid: true}, + GrantedAt: pgTime(grantedAt), + RevokedAt: pgTime(grantedAt.Add(time.Hour)), + RevocationSource: pgtype.Text{String: "consent_settings", Valid: true}, + State: "revoked", + }) + if err != nil { + t.Fatalf("consentRecordFromRow(C4) error = %v", err) + } + if contact.OrganizationID() != organization || contact.OrganizationName() != "Acme" || contact.InvitationID() != invitation || contact.InvitationTermsVersion() != 3 || + !contact.Fields().Contains(domain.ContactFieldPhone) || contact.Fields().Contains(domain.ContactFieldFullName) { + t.Fatalf("C4 scope = %s, %s, %d, %v; want the stored scope", contact.OrganizationID(), contact.InvitationID(), contact.InvitationTermsVersion(), contact.Fields().Fields()) + } + if revokedAt, revoked := contact.RevokedAt(); !revoked || !revokedAt.Equal(grantedAt.Add(time.Hour)) || contact.RevocationSource() != domain.ConsentRevocationSourceConsentSettings { + t.Fatalf("revocation = %v %v %q, want the stored stamp", revokedAt, revoked, contact.RevocationSource()) + } + + personalData, err := consentRecordFromRow(consentRecordRow{ + ID: pgUUID(uuid.Must(uuid.NewV7())), + SubjectID: pgUUID(subject), + Purpose: "c1", + TextVersion: "c1-2026-10-01", + TextHash: hash[:], + Source: "registration", + GrantedAt: pgTime(grantedAt), + State: "active", + }) + if err != nil { + t.Fatalf("consentRecordFromRow(C1) error = %v", err) + } + if personalData.OrganizationID() != uuid.Nil || !personalData.Fields().IsZero() || personalData.InvitationID() != uuid.Nil { + t.Fatalf("C1 scope = %s %v %s, want none", personalData.OrganizationID(), personalData.Fields().Fields(), personalData.InvitationID()) + } + if _, revoked := personalData.RevokedAt(); revoked || personalData.State() != domain.ConsentStateActive { + t.Fatalf("C1 state = %s, want active and unrevoked", personalData.State()) + } + + // A row changed outside the application fails instead of producing a + // record that breaks the ledger rules. + if _, err := consentRecordFromRow(consentRecordRow{ + ID: pgUUID(uuid.Must(uuid.NewV7())), SubjectID: pgUUID(subject), Purpose: "c2", TextVersion: "c2-2026-10-01", + TextHash: hash[:], Source: "consent_settings", OrganizationID: pgUUID(organization), GrantedAt: pgTime(grantedAt), State: "active", + }); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("consentRecordFromRow(C2 with an organization) error = %v, want ErrInvalidConsent", err) + } +} + +func TestContactFieldStringsKeepsCanonicalOrder(t *testing.T) { + set, err := domain.NewContactFieldSet(domain.ContactFieldTelegram, domain.ContactFieldFullName, domain.ContactFieldEmail) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + // The migration's consent_field_set_is_canonical accepts only ascending + // byte order, the order of PostgreSQL's "C" collation. + if got, want := strings.Join(contactFieldStrings(set), ","), "email,full_name,telegram"; got != want { + t.Fatalf("contactFieldStrings() = %s, want %s", got, want) + } +} + +func TestMapCleanupErrorReportsAConcurrentConsentAsARetryableConflict(t *testing.T) { + concurrent := mapCleanupError(&pgconn.PgError{Code: restrictViolationCode, ConstraintName: consentSubjectForeignKey, Detail: consentDetailMarker}) + if !errors.Is(concurrent, outbound.ErrTransactionConflict) || strings.Contains(concurrent.Error(), "subject_id)=") { + t.Fatalf("mapCleanupError(restrict) = %v, want ErrTransactionConflict without the detail", concurrent) + } + // Another restricting key, or the same key with another code, is no + // conflict. + for _, original := range []*pgconn.PgError{ + {Code: restrictViolationCode, ConstraintName: "other_fkey"}, + {Code: foreignKeyViolationCode, ConstraintName: consentSubjectForeignKey}, + } { + if err := mapCleanupError(original); errors.Is(err, outbound.ErrTransactionConflict) { + t.Fatalf("mapCleanupError(%s %s) = %v, want no conflict", original.Code, original.ConstraintName, err) + } + } +} diff --git a/backend/internal/adapter/secondary/postgres/identity.go b/backend/internal/adapter/secondary/postgres/identity.go index f2234a9..2f461e7 100644 --- a/backend/internal/adapter/secondary/postgres/identity.go +++ b/backend/internal/adapter/secondary/postgres/identity.go @@ -22,6 +22,11 @@ import ( const ( foreignKeyViolationCode = "23503" + // restrictViolationCode is raised by an ON DELETE RESTRICT foreign key. + restrictViolationCode = "23001" + // consentSubjectForeignKey restricts the delete of an account with + // consent records. + consentSubjectForeignKey = "consent_records_subject_id_fkey" // sessionTouchInterval is the minimum age of last_seen_at before Touch // writes it again. It bounds session writes to one per minute per session @@ -216,7 +221,9 @@ func (repository userRepository) UpdateRegistration(ctx context.Context, user do if err != nil { return domain.User{}, fmt.Errorf("userRepository.UpdateRegistration - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict)) } - return userFromRow(row) + // The statement returns the users columns through a CTE, so sqlc gives + // it its own row type with the same fields. + return userFromRow(sqlc.User(row)) } func (repository userRepository) MarkEmailVerified( @@ -251,11 +258,26 @@ func (repository userRepository) DeleteUnverifiedRegisteredBefore(ctx context.Co BatchLimit: limit, }) if err != nil { - return 0, fmt.Errorf("userRepository.DeleteUnverifiedRegisteredBefore - delete users: %w", mapIdentityError(err)) + return 0, fmt.Errorf("userRepository.DeleteUnverifiedRegisteredBefore - delete users: %w", mapCleanupError(err)) } return deleted, nil } +// mapCleanupError reports the restricting consent foreign key as a +// transaction conflict. The cleanup checks consent rows in its statement +// snapshot, so a consent committed for a candidate account after the +// snapshot but before the account lock passes that check and then fails +// the foreign key at the end of the statement. Nothing was deleted, and the +// next run sees the consent and skips or removes the account. +func mapCleanupError(err error) error { + var pgError *pgconn.PgError + if errors.As(err, &pgError) && pgError.Code == restrictViolationCode && pgError.ConstraintName == consentSubjectForeignKey { + return fmt.Errorf("postgres.mapCleanupError - consent recorded concurrently: %w: %w", + outbound.ErrTransactionConflict, &databaseError{code: pgError.Code, constraint: pgError.ConstraintName}) + } + return mapIdentityError(err) +} + func userFromRow(row sqlc.User) (domain.User, error) { email, err := domain.RestoreEmailAddress(row.Email, row.EmailNormalized) if err != nil { diff --git a/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go new file mode 100644 index 0000000..162e8ce --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go @@ -0,0 +1,961 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: consents.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const getConsentText = `-- name: GetConsentText :one +SELECT + purpose, + version, + body, + body_sha256, + kind, + published_at +FROM consent_texts +WHERE + purpose = $1 + AND version = $2 +` + +type GetConsentTextParams struct { + Purpose string + Version string +} + +func (q *Queries) GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error) { + row := q.db.QueryRow(ctx, getConsentText, arg.Purpose, arg.Version) + var i ConsentText + err := row.Scan( + &i.Purpose, + &i.Version, + &i.Body, + &i.BodySha256, + &i.Kind, + &i.PublishedAt, + ) + return i, err +} + +const getContactConsentRecordByInvitation = `-- name: GetContactConsentRecordByInvitation :one +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + ( + CASE WHEN revoked_at IS NULL THEN 'active' ELSE 'revoked' END + )::text AS state +FROM consent_records +WHERE + subject_id = $1 + AND invitation_id = $2 +` + +type GetContactConsentRecordByInvitationParams struct { + SubjectID pgtype.UUID + InvitationID pgtype.UUID +} + +type GetContactConsentRecordByInvitationRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + State string +} + +func (q *Queries) GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error) { + row := q.db.QueryRow(ctx, getContactConsentRecordByInvitation, arg.SubjectID, arg.InvitationID) + var i GetContactConsentRecordByInvitationRow + err := row.Scan( + &i.ID, + &i.SubjectID, + &i.Purpose, + &i.TextVersion, + &i.TextHash, + &i.Source, + &i.OrganizationID, + &i.OrganizationName, + &i.FieldSet, + &i.InvitationID, + &i.InvitationTermsVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationSource, + &i.State, + ) + return i, err +} + +const getCurrentConsentRecord = `-- name: GetCurrentConsentRecord :one +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state +FROM consent_records +WHERE + subject_id = $1 + AND purpose = $2 + AND purpose <> 'c4' + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC +LIMIT 1 +` + +type GetCurrentConsentRecordParams struct { + SubjectID pgtype.UUID + Purpose string +} + +type GetCurrentConsentRecordRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + State string +} + +// The newest unrevoked record of a purpose other than C4. +func (q *Queries) GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error) { + row := q.db.QueryRow(ctx, getCurrentConsentRecord, arg.SubjectID, arg.Purpose) + var i GetCurrentConsentRecordRow + err := row.Scan( + &i.ID, + &i.SubjectID, + &i.Purpose, + &i.TextVersion, + &i.TextHash, + &i.Source, + &i.OrganizationID, + &i.OrganizationName, + &i.FieldSet, + &i.InvitationID, + &i.InvitationTermsVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationSource, + &i.State, + ) + return i, err +} + +const getCurrentConsentText = `-- name: GetCurrentConsentText :one +SELECT + purpose, + version, + body, + body_sha256, + kind, + published_at +FROM consent_texts +WHERE + purpose = $1 + AND published_at <= $2 +ORDER BY published_at DESC +LIMIT 1 +` + +type GetCurrentConsentTextParams struct { + Purpose string + At pgtype.Timestamptz +} + +// The text of a purpose that applies at a time: the latest publication not +// after it. +func (q *Queries) GetCurrentConsentText(ctx context.Context, arg GetCurrentConsentTextParams) (ConsentText, error) { + row := q.db.QueryRow(ctx, getCurrentConsentText, arg.Purpose, arg.At) + var i ConsentText + err := row.Scan( + &i.Purpose, + &i.Version, + &i.Body, + &i.BodySha256, + &i.Kind, + &i.PublishedAt, + ) + return i, err +} + +const getUnrevokedConsentRecordByVersion = `-- name: GetUnrevokedConsentRecordByVersion :one +SELECT + record.id, + record.subject_id, + record.purpose, + record.text_version, + record.text_hash, + record.source, + record.organization_id, + record.organization_name, + record.field_set, + record.invitation_id, + record.invitation_terms_version, + record.granted_at, + record.revoked_at, + record.revocation_source, + ( + CASE + WHEN exists( + SELECT 1 FROM consent_records AS newer + WHERE + newer.subject_id = record.subject_id + AND newer.purpose = record.purpose + AND newer.revoked_at IS NULL + AND (newer.granted_at, newer.id) + > (record.granted_at, record.id) + ) THEN 'superseded' + ELSE 'active' + END + )::text AS state +FROM consent_records AS record +WHERE + record.subject_id = $1 + AND record.purpose = $2 + AND record.text_version = $3 + AND record.revoked_at IS NULL +` + +type GetUnrevokedConsentRecordByVersionParams struct { + SubjectID pgtype.UUID + Purpose string + TextVersion string +} + +type GetUnrevokedConsentRecordByVersionRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + State string +} + +func (q *Queries) GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error) { + row := q.db.QueryRow(ctx, getUnrevokedConsentRecordByVersion, arg.SubjectID, arg.Purpose, arg.TextVersion) + var i GetUnrevokedConsentRecordByVersionRow + err := row.Scan( + &i.ID, + &i.SubjectID, + &i.Purpose, + &i.TextVersion, + &i.TextHash, + &i.Source, + &i.OrganizationID, + &i.OrganizationName, + &i.FieldSet, + &i.InvitationID, + &i.InvitationTermsVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationSource, + &i.State, + ) + return i, err +} + +const insertConsentRecord = `-- name: InsertConsentRecord :one +INSERT INTO consent_records ( + id, + subject_id, + purpose, + text_version, + text_hash, + source, + granted_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7 +) +ON CONFLICT (subject_id, purpose, text_version) +WHERE revoked_at IS NULL AND purpose <> 'c4' +DO NOTHING +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + ( + CASE + WHEN exists( + SELECT 1 FROM consent_records AS newer + WHERE + newer.subject_id = consent_records.subject_id + AND newer.purpose = consent_records.purpose + AND newer.revoked_at IS NULL + AND (newer.granted_at, newer.id) + > (consent_records.granted_at, consent_records.id) + ) THEN 'superseded' + ELSE 'active' + END + )::text AS state +` + +type InsertConsentRecordParams struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + GrantedAt pgtype.Timestamptz +} + +type InsertConsentRecordRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + State string +} + +// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same +// subject, purpose, and text version already exists when no row returns; +// the insert then changes nothing and does not abort the transaction. +func (q *Queries) InsertConsentRecord(ctx context.Context, arg InsertConsentRecordParams) (InsertConsentRecordRow, error) { + row := q.db.QueryRow(ctx, insertConsentRecord, + arg.ID, + arg.SubjectID, + arg.Purpose, + arg.TextVersion, + arg.TextHash, + arg.Source, + arg.GrantedAt, + ) + var i InsertConsentRecordRow + err := row.Scan( + &i.ID, + &i.SubjectID, + &i.Purpose, + &i.TextVersion, + &i.TextHash, + &i.Source, + &i.OrganizationID, + &i.OrganizationName, + &i.FieldSet, + &i.InvitationID, + &i.InvitationTermsVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationSource, + &i.State, + ) + return i, err +} + +const insertContactConsentRecord = `-- name: InsertContactConsentRecord :one +INSERT INTO consent_records ( + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at +) VALUES ( + $1, + $2, + 'c4', + $3, + $4, + 'invitation_acceptance', + $5, + $6, + $7::text [], + $8, + $9, + $10 +) +ON CONFLICT (invitation_id) WHERE invitation_id IS NOT NULL +DO NOTHING +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state +` + +type InsertContactConsentRecordParams struct { + ID pgtype.UUID + SubjectID pgtype.UUID + TextVersion string + TextHash []byte + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz +} + +type InsertContactConsentRecordRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + State string +} + +// Records a C4 grant with its scope. The invitation already has a C4 record +// when no row returns; the insert then changes nothing and does not abort +// the transaction. +func (q *Queries) InsertContactConsentRecord(ctx context.Context, arg InsertContactConsentRecordParams) (InsertContactConsentRecordRow, error) { + row := q.db.QueryRow(ctx, insertContactConsentRecord, + arg.ID, + arg.SubjectID, + arg.TextVersion, + arg.TextHash, + arg.OrganizationID, + arg.OrganizationName, + arg.FieldSet, + arg.InvitationID, + arg.InvitationTermsVersion, + arg.GrantedAt, + ) + var i InsertContactConsentRecordRow + err := row.Scan( + &i.ID, + &i.SubjectID, + &i.Purpose, + &i.TextVersion, + &i.TextHash, + &i.Source, + &i.OrganizationID, + &i.OrganizationName, + &i.FieldSet, + &i.InvitationID, + &i.InvitationTermsVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationSource, + &i.State, + ) + return i, err +} + +const listConsentRecords = `-- name: ListConsentRecords :many +WITH ledger AS ( + SELECT + record.id, + record.subject_id, + record.purpose, + record.text_version, + record.text_hash, + record.source, + record.organization_id, + record.organization_name, + record.field_set, + record.invitation_id, + record.invitation_terms_version, + record.granted_at, + record.revoked_at, + record.revocation_source, + ( + CASE + WHEN record.revoked_at IS NOT NULL THEN 'revoked' + WHEN record.purpose <> 'c4' AND exists( + SELECT 1 FROM consent_records AS newer + WHERE + newer.subject_id = record.subject_id + AND newer.purpose = record.purpose + AND newer.revoked_at IS NULL + AND (newer.granted_at, newer.id) + > (record.granted_at, record.id) + ) THEN 'superseded' + ELSE 'active' + END + )::text AS state + FROM consent_records AS record + WHERE record.subject_id = $5 +) + +SELECT + ledger.id, + ledger.subject_id, + ledger.purpose, + ledger.text_version, + ledger.text_hash, + ledger.source, + ledger.organization_id, + ledger.organization_name, + ledger.field_set, + ledger.invitation_id, + ledger.invitation_terms_version, + ledger.granted_at, + ledger.revoked_at, + ledger.revocation_source, + ledger.state +FROM ledger +WHERE + ($1::text IS NULL OR ledger.state = $1::text) + AND ( + $2::timestamptz IS NULL + OR (ledger.granted_at, ledger.id) < ( + $2::timestamptz, + $3::uuid + ) + ) +ORDER BY ledger.granted_at DESC, ledger.id DESC +LIMIT $4 +` + +type ListConsentRecordsParams struct { + State pgtype.Text + AfterGrantedAt pgtype.Timestamptz + AfterID pgtype.UUID + RowLimit int32 + SubjectID pgtype.UUID +} + +type ListConsentRecordsRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + State string +} + +// One page of the subject's ledger, newest grant first, optionally limited +// to one state. Every record query is scoped by the subject, so a caller +// never reads or revokes another subject's consent. The state is computed, +// never stored: revoked once revoked_at is set; superseded when a newer +// unrevoked record of the same subject and purpose exists (never for C4, +// whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of +// the last record of the previous page. +func (q *Queries) ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error) { + rows, err := q.db.Query(ctx, listConsentRecords, + arg.State, + arg.AfterGrantedAt, + arg.AfterID, + arg.RowLimit, + arg.SubjectID, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListConsentRecordsRow + for rows.Next() { + var i ListConsentRecordsRow + if err := rows.Scan( + &i.ID, + &i.SubjectID, + &i.Purpose, + &i.TextVersion, + &i.TextHash, + &i.Source, + &i.OrganizationID, + &i.OrganizationName, + &i.FieldSet, + &i.InvitationID, + &i.InvitationTermsVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationSource, + &i.State, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listCurrentContactConsentRecords = `-- name: ListCurrentContactConsentRecords :many +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state +FROM consent_records +WHERE + subject_id = $1 + AND purpose = 'c4' + AND organization_id = $2 + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC +` + +type ListCurrentContactConsentRecordsParams struct { + SubjectID pgtype.UUID + OrganizationID pgtype.UUID +} + +type ListCurrentContactConsentRecordsRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + State string +} + +func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error) { + rows, err := q.db.Query(ctx, listCurrentContactConsentRecords, arg.SubjectID, arg.OrganizationID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListCurrentContactConsentRecordsRow + for rows.Next() { + var i ListCurrentContactConsentRecordsRow + if err := rows.Scan( + &i.ID, + &i.SubjectID, + &i.Purpose, + &i.TextVersion, + &i.TextHash, + &i.Source, + &i.OrganizationID, + &i.OrganizationName, + &i.FieldSet, + &i.InvitationID, + &i.InvitationTermsVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationSource, + &i.State, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const revokeConsentRecords = `-- name: RevokeConsentRecords :many +UPDATE consent_records +SET + revoked_at = greatest($1::timestamptz, granted_at), + revocation_source = $2 +WHERE + subject_id = $3 + AND purpose = $4 + AND purpose <> 'c4' + AND revoked_at IS NULL +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'revoked'::text AS state +` + +type RevokeConsentRecordsParams struct { + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + SubjectID pgtype.UUID + Purpose string +} + +type RevokeConsentRecordsRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + State string +} + +// Revokes every unrevoked record of a purpose other than C4, superseded ones +// included, and returns them. A revocation time before the grant time, from +// clock skew between instances, is stamped at the grant time instead. +func (q *Queries) RevokeConsentRecords(ctx context.Context, arg RevokeConsentRecordsParams) ([]RevokeConsentRecordsRow, error) { + rows, err := q.db.Query(ctx, revokeConsentRecords, + arg.RevokedAt, + arg.RevocationSource, + arg.SubjectID, + arg.Purpose, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []RevokeConsentRecordsRow + for rows.Next() { + var i RevokeConsentRecordsRow + if err := rows.Scan( + &i.ID, + &i.SubjectID, + &i.Purpose, + &i.TextVersion, + &i.TextHash, + &i.Source, + &i.OrganizationID, + &i.OrganizationName, + &i.FieldSet, + &i.InvitationID, + &i.InvitationTermsVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationSource, + &i.State, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const revokeContactConsentRecords = `-- name: RevokeContactConsentRecords :many +UPDATE consent_records +SET + revoked_at = greatest($1::timestamptz, granted_at), + revocation_source = $2 +WHERE + subject_id = $3 + AND purpose = 'c4' + AND organization_id = $4 + AND revoked_at IS NULL +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'revoked'::text AS state +` + +type RevokeContactConsentRecordsParams struct { + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + SubjectID pgtype.UUID + OrganizationID pgtype.UUID +} + +type RevokeContactConsentRecordsRow struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text + State string +} + +// Revokes every unrevoked C4 record of the subject for one organization and +// returns them, with the same clamp of the revocation time as above. +func (q *Queries) RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error) { + rows, err := q.db.Query(ctx, revokeContactConsentRecords, + arg.RevokedAt, + arg.RevocationSource, + arg.SubjectID, + arg.OrganizationID, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []RevokeContactConsentRecordsRow + for rows.Next() { + var i RevokeContactConsentRecordsRow + if err := rows.Scan( + &i.ID, + &i.SubjectID, + &i.Purpose, + &i.TextVersion, + &i.TextHash, + &i.Source, + &i.OrganizationID, + &i.OrganizationName, + &i.FieldSet, + &i.InvitationID, + &i.InvitationTermsVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationSource, + &i.State, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go index cd2e656..03d2005 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go @@ -107,6 +107,13 @@ locked_delivery AS ( FOR UPDATE SKIP LOCKED ), +locked_consent AS ( + SELECT consent.subject_id + FROM consent_records AS consent + WHERE consent.subject_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + deletable AS ( SELECT candidate.id FROM candidate @@ -139,6 +146,19 @@ deletable AS ( SELECT count(*) FROM locked_delivery WHERE locked_delivery.recipient_user_id = candidate.id ) + AND ( + SELECT count(*) FROM consent_records AS consent + WHERE consent.subject_id = candidate.id + ) = ( + SELECT count(*) FROM locked_consent + WHERE locked_consent.subject_id = candidate.id + ) +), + +deleted_consent AS ( + DELETE FROM consent_records + USING deletable + WHERE consent_records.subject_id = deletable.id ) DELETE FROM users @@ -152,18 +172,23 @@ type DeleteUnverifiedUsersRegisteredBeforeParams struct { } // Deletes one batch of accounts that stayed unverified since before cutoff, -// oldest first, with their tokens, sessions, mail requests, and mail -// deliveries (and through the deliveries their attempts). Every lock is taken +// oldest first, with their tokens, sessions, mail requests, mail deliveries +// (and through the deliveries their attempts), and consent records. The +// consent records reference the account with ON DELETE RESTRICT, so they are +// deleted explicitly in the same statement: a registration never confirmed +// by its email owner is not kept as consent evidence. Every lock is taken // with SKIP LOCKED, so the statement never waits: an account whose row is -// locked, for example by a re-registration, a token insert, or a delivery -// insert, is skipped, and so is an account with any token, session, mail -// request, or delivery row locked, for example by a confirmation that -// consumed a token, the delivery consumer, or a worker recording an attempt. -// Skipped accounts stay for the next run. +// locked, for example by a re-registration, a token insert, a delivery +// insert, or a consent insert, is skipped, and so is an account with any +// token, session, mail request, delivery, or consent row locked, for example +// by a confirmation that consumed a token, the delivery consumer, or a +// worker recording an attempt. Skipped accounts stay for the next run. // Taking the account lock before the token locks is the reverse of the // documented order, which is safe only because no lock here waits. -// An account qualifies only when every token, session, mail request, and -// delivery row visible to the statement was locked above. +// An account qualifies only when every token, session, mail request, +// delivery, and consent row visible to the statement was locked above. +// The restricting foreign key is checked at the end of the statement, after +// these rows are gone. func (q *Queries) DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) { result, err := q.db.Exec(ctx, deleteUnverifiedUsersRegisteredBefore, arg.Cutoff, arg.BatchLimit) if err != nil { @@ -646,33 +671,59 @@ func (q *Queries) TouchSession(ctx context.Context, arg TouchSessionParams) (Tou } const updateUserRegistration = `-- name: UpdateUserRegistration :one -UPDATE users -SET - email = $1, - password_hash = $2, - scenario = $3, - onboarding_step = $4, - registration_version = registration_version + 1, - last_registered_at = $5, - updated_at = $6, - version = version + 1 -WHERE - id = $7 - AND version = $8 - AND email_verified_at IS NULL -RETURNING - id, - email, - email_normalized, - password_hash, - scenario, - onboarding_step, - email_verified_at, - registration_version, - last_registered_at, - version, - created_at, - updated_at +WITH updated AS ( + UPDATE users + SET + email = $1, + password_hash = $2, + scenario = $3, + onboarding_step = $4, + registration_version = registration_version + 1, + last_registered_at = $5, + updated_at = $6, + version = version + 1 + WHERE + users.id = $7 + AND users.version = $8 + AND users.email_verified_at IS NULL + RETURNING + users.id, + users.email, + users.email_normalized, + users.password_hash, + users.scenario, + users.onboarding_step, + users.email_verified_at, + users.registration_version, + users.last_registered_at, + users.version, + users.created_at, + users.updated_at +), + +discarded_consent AS ( + DELETE FROM consent_records + USING updated + WHERE + consent_records.subject_id = updated.id + AND consent_records.purpose = 'c1' + AND consent_records.source = 'registration' +) + +SELECT + updated.id, + updated.email, + updated.email_normalized, + updated.password_hash, + updated.scenario, + updated.onboarding_step, + updated.email_verified_at, + updated.registration_version, + updated.last_registered_at, + updated.version, + updated.created_at, + updated.updated_at +FROM updated ` type UpdateUserRegistrationParams struct { @@ -686,11 +737,29 @@ type UpdateUserRegistrationParams struct { ExpectedVersion int64 } +type UpdateUserRegistrationRow struct { + ID pgtype.UUID + Email string + EmailNormalized string + PasswordHash string + Scenario string + OnboardingStep string + EmailVerifiedAt pgtype.Timestamptz + RegistrationVersion int64 + LastRegisteredAt pgtype.Timestamptz + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + // Replaces the registration of an unverified account and advances the // registration version in the same statement, so no caller can choose it. // The version check rejects a writer that read an older row; a verified -// account never changes. -func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error) { +// account never changes. The same statement deletes the C1 that the earlier +// registration of this account recorded, so the consent of an earlier +// registrant never stands for the new one; the new registration records its +// own C1 in the same transaction. A version conflict deletes nothing. +func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (UpdateUserRegistrationRow, error) { row := q.db.QueryRow(ctx, updateUserRegistration, arg.Email, arg.PasswordHash, @@ -701,7 +770,7 @@ func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegi arg.ID, arg.ExpectedVersion, ) - var i User + var i UpdateUserRegistrationRow err := row.Scan( &i.ID, &i.Email, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 0c1d55e..955027e 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -8,6 +8,33 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +type ConsentRecord struct { + ID pgtype.UUID + SubjectID pgtype.UUID + Purpose string + TextVersion string + TextHash []byte + PublishedTextHash []byte + Source string + OrganizationID pgtype.UUID + OrganizationName pgtype.Text + FieldSet []string + InvitationID pgtype.UUID + InvitationTermsVersion pgtype.Int8 + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationSource pgtype.Text +} + +type ConsentText struct { + Purpose string + Version string + Body string + BodySha256 []byte + Kind string + PublishedAt pgtype.Timestamptz +} + type ConsumerDeadLetter struct { ID int64 ConsumerName string diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index fc977b5..3c4f4c7 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -50,18 +50,23 @@ type Querier interface { ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error) DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error) // Deletes one batch of accounts that stayed unverified since before cutoff, - // oldest first, with their tokens, sessions, mail requests, and mail - // deliveries (and through the deliveries their attempts). Every lock is taken + // oldest first, with their tokens, sessions, mail requests, mail deliveries + // (and through the deliveries their attempts), and consent records. The + // consent records reference the account with ON DELETE RESTRICT, so they are + // deleted explicitly in the same statement: a registration never confirmed + // by its email owner is not kept as consent evidence. Every lock is taken // with SKIP LOCKED, so the statement never waits: an account whose row is - // locked, for example by a re-registration, a token insert, or a delivery - // insert, is skipped, and so is an account with any token, session, mail - // request, or delivery row locked, for example by a confirmation that - // consumed a token, the delivery consumer, or a worker recording an attempt. - // Skipped accounts stay for the next run. + // locked, for example by a re-registration, a token insert, a delivery + // insert, or a consent insert, is skipped, and so is an account with any + // token, session, mail request, delivery, or consent row locked, for example + // by a confirmation that consumed a token, the delivery consumer, or a + // worker recording an attempt. Skipped accounts stay for the next run. // Taking the account lock before the token locks is the reverse of the // documented order, which is safe only because no lock here waits. - // An account qualifies only when every token, session, mail request, and - // delivery row visible to the statement was locked above. + // An account qualifies only when every token, session, mail request, + // delivery, and consent row visible to the statement was locked above. + // The restricting foreign key is checked at the end of the statement, after + // these rows are gone. DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) // Lock order. Every transaction that writes mail_quota_usage first creates // and locks all the usage rows it will touch with EnsureMailQuotaRows and @@ -85,6 +90,13 @@ type Querier interface { // provider's idempotency window reuses it instead of counting again. FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error) GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) + GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error) + GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error) + // The newest unrevoked record of a purpose other than C4. + GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error) + // The text of a purpose that applies at a time: the latest publication not + // after it. + GetCurrentConsentText(ctx context.Context, arg GetCurrentConsentTextParams) (ConsentText, error) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error) // Among the versions of a family already effective at a time, the newest // publication wins. A version scheduled for later therefore never undoes a @@ -116,13 +128,22 @@ type Querier interface { // the handler transaction that holds its row lock: only that transaction // can have changed it, for example by canceling its own job. GetScheduledJobStatus(ctx context.Context, id int64) (string, error) + GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error) GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) + // Records a grant of C1, C2, C3, or C5. An unrevoked record of the same + // subject, purpose, and text version already exists when no row returns; + // the insert then changes nothing and does not abort the transaction. + InsertConsentRecord(ctx context.Context, arg InsertConsentRecordParams) (InsertConsentRecordRow, error) // Stores a record that a consumer could not apply. A second delivery of the // same record (same position and value) refreshes the outcome of its row: // after a rewind the handler may fail differently. A different value at a // reused position, after the topic was recreated, gets its own row. InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error + // Records a C4 grant with its scope. The invitation already has a C4 record + // when no row returns; the insert then changes nothing and does not abort + // the transaction. + InsertContactConsentRecord(ctx context.Context, arg InsertContactConsentRecordParams) (InsertContactConsentRecordRow, error) // Stores a new delivery. A delivery with the same ID already exists when the // same request is handled again; the statement then inserts nothing and // returns 0 rows, and the stored content stays as it was. While another @@ -158,6 +179,15 @@ type Querier interface { InsertSession(ctx context.Context, arg InsertSessionParams) error InsertUser(ctx context.Context, arg InsertUserParams) error InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) + // One page of the subject's ledger, newest grant first, optionally limited + // to one state. Every record query is scoped by the subject, so a caller + // never reads or revokes another subject's consent. The state is computed, + // never stored: revoked once revoked_at is set; superseded when a newer + // unrevoked record of the same subject and purpose exists (never for C4, + // whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of + // the last record of the previous page. + ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error) + ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error) ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error) // Lists the other accounts of a provider that have usage in a month, so // startup can warn about a renamed EMAIL_ACCOUNT. @@ -228,6 +258,13 @@ type Querier interface { // the job did not cause the failure. The same guard as the completion // applies, one (id, attempt) pair per job. It returns the IDs it released. ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error) + // Revokes every unrevoked record of a purpose other than C4, superseded ones + // included, and returns them. A revocation time before the grant time, from + // clock skew between instances, is stamped at the grant time instead. + RevokeConsentRecords(ctx context.Context, arg RevokeConsentRecordsParams) ([]RevokeConsentRecordsRow, error) + // Revokes every unrevoked C4 record of the subject for one organization and + // returns them, with the same clamp of the revocation time as above. + RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error) RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error) RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error) // Bounds a consumer transaction on the server, local to the transaction. @@ -270,8 +307,11 @@ type Querier interface { // Replaces the registration of an unverified account and advances the // registration version in the same statement, so no caller can choose it. // The version check rejects a writer that read an older row; a verified - // account never changes. - UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error) + // account never changes. The same statement deletes the C1 that the earlier + // registration of this account recorded, so the consent of an earlier + // registrant never stands for the new one; the new registration records its + // own C1 in the same transaction. A version conflict deletes nothing. + UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (UpdateUserRegistrationRow, error) } var _ Querier = (*Queries)(nil) diff --git a/backend/internal/domain/consent.go b/backend/internal/domain/consent.go new file mode 100644 index 0000000..a4f05ea --- /dev/null +++ b/backend/internal/domain/consent.go @@ -0,0 +1,865 @@ +package domain + +import ( + "crypto/sha256" + "errors" + "fmt" + "log/slog" + "regexp" + "slices" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/google/uuid" +) + +var ( + // ErrInvalidConsent reports a grant, revocation, or stored record that + // breaks a consent ledger rule. + ErrInvalidConsent = errors.New("invalid consent") + + // ErrInvalidConsentText reports a consent text, version, or hash that + // breaks a rule, including a stored text whose hash does not match its + // body. + ErrInvalidConsentText = errors.New("invalid consent text") +) + +const ( + // ConsentTextHashSize is the size of a SHA-256 digest. + ConsentTextHashSize = sha256.Size + + // ConsentTextOrganizationPlaceholder marks where the C4 text names the + // organization. Only the C4 text contains it. + ConsentTextOrganizationPlaceholder = "{organization}" + + // maxConsentTextRunes matches the contract bound of ConsentText.text. + maxConsentTextRunes = 100000 + // maxOrganizationNameRunes matches InvitationOrganization.name. + maxOrganizationNameRunes = 200 + // maxContactFields is the number of ContactField kinds. + maxContactFields = 4 +) + +// consentTextVersionPattern is the contract pattern of ConsentTextVersion +// with its length bound of 1 to 64 characters. +var consentTextVersionPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`) + +// ConsentPurpose is one of the independent consents C1-C5 of PRD FR01. A +// grant or revocation of one purpose never changes another. +type ConsentPurpose string + +const ( + // ConsentPurposePersonalData is C1, the processing of personal data, + // given at registration. + ConsentPurposePersonalData ConsentPurpose = "c1" + // ConsentPurposePublication is C2, the publication of the candidate card. + ConsentPurposePublication ConsentPurpose = "c2" + // ConsentPurposeAutoCategorization is C3, the automatic categorization. + ConsentPurposeAutoCategorization ConsentPurpose = "c3" + // ConsentPurposeContactDisclosure is C4, the transfer of selected contact + // data to one organization. It is always scoped; see ContactConsentGrant. + ConsentPurposeContactDisclosure ConsentPurpose = "c4" + // ConsentPurposeFSPImport is C5, the import of FSP results. + ConsentPurposeFSPImport ConsentPurpose = "c5" +) + +// ParseConsentPurpose accepts a known purpose. +func ParseConsentPurpose(value string) (ConsentPurpose, error) { + purpose := ConsentPurpose(value) + switch purpose { + case ConsentPurposePersonalData, ConsentPurposePublication, ConsentPurposeAutoCategorization, + ConsentPurposeContactDisclosure, ConsentPurposeFSPImport: + return purpose, nil + default: + return "", fmt.Errorf("domain.ParseConsentPurpose - unknown purpose: %w", ErrInvalidConsent) + } +} + +// OrganizationScoped reports whether a grant of the purpose names an +// organization and a contact field set. Only C4 does. +func (purpose ConsentPurpose) OrganizationScoped() bool { + return purpose == ConsentPurposeContactDisclosure +} + +// ConsentTextVersion identifies a published consent text, such as +// "c1-2026-10-01". +type ConsentTextVersion string + +// ParseConsentTextVersion accepts 1 to 64 characters A-Z, a-z, 0-9, ".", +// "_", and "-". +func ParseConsentTextVersion(value string) (ConsentTextVersion, error) { + if !consentTextVersionPattern.MatchString(value) { + return "", fmt.Errorf("domain.ParseConsentTextVersion - version must have 1 to 64 characters A-Z a-z 0-9 . _ -: %w", ErrInvalidConsentText) + } + return ConsentTextVersion(value), nil +} + +// ConsentTextHash is the SHA-256 digest of the UTF-8 bytes of exactly the +// text a subject saw. +type ConsentTextHash [ConsentTextHashSize]byte + +// HashConsentText returns the digest of text. +func HashConsentText(text string) ConsentTextHash { + return sha256.Sum256([]byte(text)) +} + +// ConsentTextHashFromBytes accepts a stored 32-byte digest. An empty, short, +// long, or all-zero value is refused. +func ConsentTextHashFromBytes(value []byte) (ConsentTextHash, error) { + var hash ConsentTextHash + if len(value) != len(hash) { + return hash, fmt.Errorf("domain.ConsentTextHashFromBytes - hash must have %d bytes: %w", ConsentTextHashSize, ErrInvalidConsentText) + } + copy(hash[:], value) + if hash.IsZero() { + return hash, fmt.Errorf("domain.ConsentTextHashFromBytes - hash must not be all zero: %w", ErrInvalidConsentText) + } + return hash, nil +} + +// IsZero reports the all-zero value, which marks a missing hash. +func (hash ConsentTextHash) IsZero() bool { return hash == ConsentTextHash{} } + +// ConsentTextKind tells a demonstration text from a text of the operator. +type ConsentTextKind string + +const ( + // ConsentTextKindDemo is a synthetic text for the demonstration on + // synthetic data, without a legal review. + ConsentTextKindDemo ConsentTextKind = "demo" + // ConsentTextKindOperator is a text published by the personal data + // operator, required before real data are accepted (PRD 7.3). + ConsentTextKindOperator ConsentTextKind = "operator" +) + +// ConsentText is one immutable published version of the text of a purpose. +type ConsentText struct { + purpose ConsentPurpose + version ConsentTextVersion + body string + hash ConsentTextHash + kind ConsentTextKind + publishedAt time.Time +} + +// StoredConsentText carries the columns of a stored text. +type StoredConsentText struct { + Purpose string + Version string + Body string + Hash []byte + Kind string + PublishedAt time.Time +} + +// RestoreConsentText validates a stored text, including that its hash is the +// digest of its body, so a row changed outside the application fails with +// ErrInvalidConsentText. +func RestoreConsentText(stored StoredConsentText) (ConsentText, error) { + const location = "domain.RestoreConsentText" + purpose, err := ParseConsentPurpose(stored.Purpose) + if err != nil { + return ConsentText{}, fmt.Errorf("%s - validate purpose: %w", location, err) + } + version, err := ParseConsentTextVersion(stored.Version) + if err != nil { + return ConsentText{}, fmt.Errorf("%s - validate version: %w", location, err) + } + hash, err := ConsentTextHashFromBytes(stored.Hash) + if err != nil { + return ConsentText{}, fmt.Errorf("%s - validate hash: %w", location, err) + } + kind := ConsentTextKind(stored.Kind) + switch { + case stored.Body == "" || !utf8.ValidString(stored.Body) || utf8.RuneCountInString(stored.Body) > maxConsentTextRunes: + return ConsentText{}, fmt.Errorf("%s - body must be valid UTF-8 of 1 to %d characters: %w", location, maxConsentTextRunes, ErrInvalidConsentText) + case HashConsentText(stored.Body) != hash: + return ConsentText{}, fmt.Errorf("%s - hash does not match the body: %w", location, ErrInvalidConsentText) + case purpose.OrganizationScoped() != strings.Contains(stored.Body, ConsentTextOrganizationPlaceholder): + return ConsentText{}, fmt.Errorf("%s - only the C4 text names the organization: %w", location, ErrInvalidConsentText) + case kind != ConsentTextKindDemo && kind != ConsentTextKindOperator: + return ConsentText{}, fmt.Errorf("%s - unknown kind: %w", location, ErrInvalidConsentText) + case stored.PublishedAt.IsZero(): + return ConsentText{}, fmt.Errorf("%s - publication time must be set: %w", location, ErrInvalidConsentText) + } + return ConsentText{ + purpose: purpose, + version: version, + body: stored.Body, + hash: hash, + kind: kind, + publishedAt: stored.PublishedAt, + }, nil +} + +func (text ConsentText) Purpose() ConsentPurpose { return text.purpose } +func (text ConsentText) Version() ConsentTextVersion { return text.version } +func (text ConsentText) Body() string { return text.body } +func (text ConsentText) Kind() ConsentTextKind { return text.kind } +func (text ConsentText) PublishedAt() time.Time { return text.publishedAt } + +// Hash is the digest of Body. A grant of C1-C3 or C5 records exactly this +// hash; a C4 grant records the hash of RenderForOrganization instead. +func (text ConsentText) Hash() ConsentTextHash { return text.hash } + +// IsZero reports a ConsentText not built by RestoreConsentText. +func (text ConsentText) IsZero() bool { return text.purpose == "" } + +// RenderForOrganization returns the C4 text as the candidate sees it: the +// body with every placeholder replaced by the organization name. The C4 +// grant records HashConsentText of this result. The name must be one line +// of 1 to 200 characters without surrounding spaces. +func (text ConsentText) RenderForOrganization(organizationName string) (string, error) { + const location = "ConsentText.RenderForOrganization" + if !text.purpose.OrganizationScoped() { + return "", fmt.Errorf("%s - only the C4 text names an organization: %w", location, ErrInvalidConsentText) + } + if !validOrganizationName(organizationName) { + return "", fmt.Errorf("%s - organization name must be one line of 1 to %d characters: %w", location, maxOrganizationNameRunes, ErrInvalidConsentText) + } + return strings.ReplaceAll(text.body, ConsentTextOrganizationPlaceholder, organizationName), nil +} + +func validOrganizationName(name string) bool { + if name == "" || !utf8.ValidString(name) || utf8.RuneCountInString(name) > maxOrganizationNameRunes { + return false + } + if strings.TrimSpace(name) != name { + return false + } + return !strings.ContainsFunc(name, unicode.IsControl) +} + +// ConsentSource tells where a grant was given. +type ConsentSource string + +const ( + // ConsentSourceRegistration is the C1 acceptance in the registration. + ConsentSourceRegistration ConsentSource = "registration" + // ConsentSourceConsentSettings is a grant in the consent settings of the + // account, for C1-C3 and C5. + ConsentSourceConsentSettings ConsentSource = "consent_settings" + // ConsentSourceInvitationAcceptance is the C4 grant in the acceptance of + // an invitation. + ConsentSourceInvitationAcceptance ConsentSource = "invitation_acceptance" +) + +// allowedFor reports whether a grant of purpose may come from the source. +func (source ConsentSource) allowedFor(purpose ConsentPurpose) bool { + switch source { + case ConsentSourceRegistration: + return purpose == ConsentPurposePersonalData + case ConsentSourceConsentSettings: + return !purpose.OrganizationScoped() + case ConsentSourceInvitationAcceptance: + return purpose.OrganizationScoped() + default: + return false + } +} + +// ConsentRevocationSource tells who recorded a revocation. +type ConsentRevocationSource string + +const ( + // ConsentRevocationSourceConsentSettings is a revocation by the subject in + // the product. + ConsentRevocationSourceConsentSettings ConsentRevocationSource = "consent_settings" + // ConsentRevocationSourceSupportRequest is a revocation that an operator + // recorded on the subject's request through support. + ConsentRevocationSourceSupportRequest ConsentRevocationSource = "support_request" +) + +func (source ConsentRevocationSource) known() bool { + return source == ConsentRevocationSourceConsentSettings || source == ConsentRevocationSourceSupportRequest +} + +// ContactField is a kind of contact data that C4 can disclose to one +// organization; the values match the contract enum ContactFieldKind. +type ContactField string + +const ( + ContactFieldFullName ContactField = "full_name" + ContactFieldEmail ContactField = "email" + ContactFieldPhone ContactField = "phone" + ContactFieldTelegram ContactField = "telegram" +) + +// ParseContactField accepts a known kind. +func ParseContactField(value string) (ContactField, error) { + field := ContactField(value) + switch field { + case ContactFieldFullName, ContactFieldEmail, ContactFieldPhone, ContactFieldTelegram: + return field, nil + default: + return "", fmt.Errorf("domain.ParseContactField - unknown contact field: %w", ErrInvalidConsent) + } +} + +// ContactFieldSet is a non-empty set of distinct contact fields in canonical +// ascending byte order, the form the ledger stores. One kind never implies +// another. +type ContactFieldSet struct { + fields []ContactField +} + +// NewContactFieldSet accepts one to four distinct known fields in any order. +// A repeated field is refused, as the contract's uniqueItems refuses it, +// rather than merged. +func NewContactFieldSet(fields ...ContactField) (ContactFieldSet, error) { + const location = "domain.NewContactFieldSet" + if len(fields) == 0 || len(fields) > maxContactFields { + return ContactFieldSet{}, fmt.Errorf("%s - set must have 1 to %d fields: %w", location, maxContactFields, ErrInvalidConsent) + } + canonical := make([]ContactField, 0, len(fields)) + for _, field := range fields { + if _, err := ParseContactField(string(field)); err != nil { + return ContactFieldSet{}, fmt.Errorf("%s - validate field: %w", location, err) + } + if slices.Contains(canonical, field) { + return ContactFieldSet{}, fmt.Errorf("%s - fields must be distinct: %w", location, ErrInvalidConsent) + } + canonical = append(canonical, field) + } + slices.Sort(canonical) + return ContactFieldSet{fields: canonical}, nil +} + +// Fields returns a copy of the fields in canonical order. +func (set ContactFieldSet) Fields() []ContactField { return slices.Clone(set.fields) } + +// Contains reports whether the set covers field. +func (set ContactFieldSet) Contains(field ContactField) bool { + return slices.Contains(set.fields, field) +} + +// Equal reports whether both sets cover the same fields. +func (set ContactFieldSet) Equal(other ContactFieldSet) bool { + return slices.Equal(set.fields, other.fields) +} + +// IsZero reports a set not built by NewContactFieldSet. +func (set ContactFieldSet) IsZero() bool { return len(set.fields) == 0 } + +// ConsentState is the state of a ledger record as the read model computes +// it from the ledger. +type ConsentState string + +const ( + // ConsentStateActive is an unrevoked record that is the newest of its + // purpose; every unrevoked C4 record is active, since each covers its + // own invitation. + ConsentStateActive ConsentState = "active" + // ConsentStateSuperseded is an unrevoked record of C1-C3 or C5 with a + // newer unrevoked record of the same purpose, typically for a newer + // text version. It stays valid evidence for its own time. + ConsentStateSuperseded ConsentState = "superseded" + // ConsentStateRevoked is a revoked record. + ConsentStateRevoked ConsentState = "revoked" +) + +// ParseConsentState accepts a known state. +func ParseConsentState(value string) (ConsentState, error) { + state := ConsentState(value) + switch state { + case ConsentStateActive, ConsentStateSuperseded, ConsentStateRevoked: + return state, nil + default: + return "", fmt.Errorf("domain.ParseConsentState - unknown state: %w", ErrInvalidConsent) + } +} + +// ConsentGrantInput describes a grant of C1, C2, C3, or C5. TextVersion and +// TextHash come from the ConsentText that the subject saw. +type ConsentGrantInput struct { + SubjectID uuid.UUID + Purpose ConsentPurpose + TextVersion ConsentTextVersion + TextHash ConsentTextHash + Source ConsentSource + GrantedAt time.Time +} + +// ConsentGrant is a validated grant of C1, C2, C3, or C5, ready for the +// ledger. C4 is never a ConsentGrant: it needs its organization scope, see +// ContactConsentGrant. +type ConsentGrant struct { + id uuid.UUID + subjectID uuid.UUID + purpose ConsentPurpose + textVersion ConsentTextVersion + textHash ConsentTextHash + source ConsentSource + grantedAt time.Time +} + +// NewConsentGrant validates input and assigns a UUIDv7 identifier. +func NewConsentGrant(input ConsentGrantInput) (ConsentGrant, error) { + const location = "domain.NewConsentGrant" + if _, err := ParseConsentPurpose(string(input.Purpose)); err != nil { + return ConsentGrant{}, fmt.Errorf("%s - validate purpose: %w", location, err) + } + if input.Purpose.OrganizationScoped() { + return ConsentGrant{}, fmt.Errorf("%s - C4 is granted only with its organization scope: %w", location, ErrInvalidConsent) + } + if err := validateGrantText(location, input.TextVersion, input.TextHash); err != nil { + return ConsentGrant{}, err + } + switch { + case input.SubjectID == uuid.Nil: + return ConsentGrant{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, ErrInvalidConsent) + case !input.Source.allowedFor(input.Purpose): + return ConsentGrant{}, fmt.Errorf("%s - source does not allow the purpose: %w", location, ErrInvalidConsent) + case input.GrantedAt.IsZero(): + return ConsentGrant{}, fmt.Errorf("%s - grant time must be set: %w", location, ErrInvalidConsent) + } + id, err := uuid.NewV7() + if err != nil { + return ConsentGrant{}, fmt.Errorf("%s - generate record ID: %w", location, err) + } + return ConsentGrant{ + id: id, + subjectID: input.SubjectID, + purpose: input.Purpose, + textVersion: input.TextVersion, + textHash: input.TextHash, + source: input.Source, + grantedAt: input.GrantedAt, + }, nil +} + +func (grant ConsentGrant) ID() uuid.UUID { return grant.id } +func (grant ConsentGrant) SubjectID() uuid.UUID { return grant.subjectID } +func (grant ConsentGrant) Purpose() ConsentPurpose { return grant.purpose } +func (grant ConsentGrant) TextVersion() ConsentTextVersion { return grant.textVersion } +func (grant ConsentGrant) TextHash() ConsentTextHash { return grant.textHash } +func (grant ConsentGrant) Source() ConsentSource { return grant.source } +func (grant ConsentGrant) GrantedAt() time.Time { return grant.grantedAt } + +// IsZero reports a grant not built by NewConsentGrant. +func (grant ConsentGrant) IsZero() bool { return grant.id == uuid.Nil } + +func (grant ConsentGrant) String() string { + return fmt.Sprintf("[consent grant %s %s]", grant.id, grant.purpose) +} + +func (grant ConsentGrant) GoString() string { return grant.String() } + +// Format applies String to every verb; without it %+v would print the +// subject. +func (grant ConsentGrant) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(grant.String())) +} + +// LogValue carries only the record ID and purpose. +func (grant ConsentGrant) LogValue() slog.Value { return consentLogValue(grant.id, grant.purpose) } + +// ContactConsentGrantInput describes the C4 grant of an invitation +// acceptance: the organization and its name as the candidate saw it, the +// selected fields, the invitation and the terms version it accepts, and the +// published C4 text. The grant computes the hash of the shown text itself; +// a caller never supplies hash bytes. +type ContactConsentGrantInput struct { + SubjectID uuid.UUID + OrganizationID uuid.UUID + OrganizationName string + Fields ContactFieldSet + InvitationID uuid.UUID + InvitationTermsVersion int64 + Text ConsentText + GrantedAt time.Time +} + +// ContactConsentGrant is a validated C4 grant with its scope. String, +// GoString, Format, and LogValue show only the record ID and purpose. +type ContactConsentGrant struct { + id uuid.UUID + subjectID uuid.UUID + organizationID uuid.UUID + organizationName string + fields ContactFieldSet + invitationID uuid.UUID + invitationTermsVersion int64 + textVersion ConsentTextVersion + textHash ConsentTextHash + grantedAt time.Time +} + +// NewContactConsentGrant validates input, renders the C4 text for the +// organization name, records the hash of that shown text, and assigns a +// UUIDv7 identifier. The database checks the same hash against the +// published text and the stored name. +func NewContactConsentGrant(input ContactConsentGrantInput) (ContactConsentGrant, error) { + const location = "domain.NewContactConsentGrant" + if input.Text.IsZero() || !input.Text.Purpose().OrganizationScoped() { + return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires the published C4 text: %w", location, ErrInvalidConsentText) + } + shown, err := input.Text.RenderForOrganization(input.OrganizationName) + if err != nil { + return ContactConsentGrant{}, fmt.Errorf("%s - render the shown text: %w", location, err) + } + switch { + case input.SubjectID == uuid.Nil: + return ContactConsentGrant{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, ErrInvalidConsent) + case input.OrganizationID == uuid.Nil: + return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires an organization: %w", location, ErrInvalidConsent) + case input.Fields.IsZero(): + return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires a field set built by NewContactFieldSet: %w", location, ErrInvalidConsent) + case input.InvitationID == uuid.Nil: + return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires an invitation: %w", location, ErrInvalidConsent) + case input.InvitationTermsVersion <= 0: + return ContactConsentGrant{}, fmt.Errorf("%s - invitation terms version must be positive: %w", location, ErrInvalidConsent) + case input.GrantedAt.IsZero(): + return ContactConsentGrant{}, fmt.Errorf("%s - grant time must be set: %w", location, ErrInvalidConsent) + } + id, err := uuid.NewV7() + if err != nil { + return ContactConsentGrant{}, fmt.Errorf("%s - generate record ID: %w", location, err) + } + return ContactConsentGrant{ + id: id, + subjectID: input.SubjectID, + organizationID: input.OrganizationID, + organizationName: input.OrganizationName, + fields: input.Fields, + invitationID: input.InvitationID, + invitationTermsVersion: input.InvitationTermsVersion, + textVersion: input.Text.Version(), + textHash: HashConsentText(shown), + grantedAt: input.GrantedAt, + }, nil +} + +func (grant ContactConsentGrant) ID() uuid.UUID { return grant.id } +func (grant ContactConsentGrant) SubjectID() uuid.UUID { return grant.subjectID } +func (grant ContactConsentGrant) OrganizationID() uuid.UUID { return grant.organizationID } +func (grant ContactConsentGrant) OrganizationName() string { return grant.organizationName } +func (grant ContactConsentGrant) Fields() ContactFieldSet { return grant.fields } +func (grant ContactConsentGrant) InvitationID() uuid.UUID { return grant.invitationID } +func (grant ContactConsentGrant) InvitationTermsVersion() int64 { return grant.invitationTermsVersion } +func (grant ContactConsentGrant) TextVersion() ConsentTextVersion { return grant.textVersion } +func (grant ContactConsentGrant) TextHash() ConsentTextHash { return grant.textHash } +func (grant ContactConsentGrant) GrantedAt() time.Time { return grant.grantedAt } + +// IsZero reports a grant not built by NewContactConsentGrant. +func (grant ContactConsentGrant) IsZero() bool { return grant.id == uuid.Nil } + +func (grant ContactConsentGrant) String() string { + return fmt.Sprintf("[consent grant %s %s]", grant.id, ConsentPurposeContactDisclosure) +} + +func (grant ContactConsentGrant) GoString() string { return grant.String() } + +// Format applies String to every verb; without it %+v would print the +// subject, the organization, and the fields. +func (grant ContactConsentGrant) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(grant.String())) +} + +// LogValue carries only the record ID and purpose. +func (grant ContactConsentGrant) LogValue() slog.Value { + return consentLogValue(grant.id, ConsentPurposeContactDisclosure) +} + +func validateGrantText(location string, version ConsentTextVersion, hash ConsentTextHash) error { + if _, err := ParseConsentTextVersion(string(version)); err != nil { + return fmt.Errorf("%s - validate text version: %w", location, err) + } + if hash.IsZero() { + return fmt.Errorf("%s - text hash must be set: %w", location, ErrInvalidConsentText) + } + return nil +} + +// ConsentRevocationInput describes a revocation of every unrevoked record of +// a purpose. OrganizationID is required for C4, which is revoked per +// organization, and must be uuid.Nil for every other purpose. +type ConsentRevocationInput struct { + SubjectID uuid.UUID + Purpose ConsentPurpose + OrganizationID uuid.UUID + Source ConsentRevocationSource + RevokedAt time.Time +} + +// ConsentRevocation is a validated revocation. +type ConsentRevocation struct { + subjectID uuid.UUID + purpose ConsentPurpose + organizationID uuid.UUID + source ConsentRevocationSource + revokedAt time.Time +} + +// NewConsentRevocation validates input. +func NewConsentRevocation(input ConsentRevocationInput) (ConsentRevocation, error) { + const location = "domain.NewConsentRevocation" + if _, err := ParseConsentPurpose(string(input.Purpose)); err != nil { + return ConsentRevocation{}, fmt.Errorf("%s - validate purpose: %w", location, err) + } + switch { + case input.SubjectID == uuid.Nil: + return ConsentRevocation{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, ErrInvalidConsent) + case input.Purpose.OrganizationScoped() != (input.OrganizationID != uuid.Nil): + return ConsentRevocation{}, fmt.Errorf("%s - only C4 is revoked per organization, and always so: %w", location, ErrInvalidConsent) + case !input.Source.known(): + return ConsentRevocation{}, fmt.Errorf("%s - unknown revocation source: %w", location, ErrInvalidConsent) + case input.RevokedAt.IsZero(): + return ConsentRevocation{}, fmt.Errorf("%s - revocation time must be set: %w", location, ErrInvalidConsent) + } + return ConsentRevocation{ + subjectID: input.SubjectID, + purpose: input.Purpose, + organizationID: input.OrganizationID, + source: input.Source, + revokedAt: input.RevokedAt, + }, nil +} + +func (revocation ConsentRevocation) SubjectID() uuid.UUID { return revocation.subjectID } +func (revocation ConsentRevocation) Purpose() ConsentPurpose { return revocation.purpose } +func (revocation ConsentRevocation) OrganizationID() uuid.UUID { return revocation.organizationID } +func (revocation ConsentRevocation) Source() ConsentRevocationSource { return revocation.source } +func (revocation ConsentRevocation) RevokedAt() time.Time { return revocation.revokedAt } +func (revocation ConsentRevocation) IsZero() bool { return revocation.subjectID == uuid.Nil } + +func (revocation ConsentRevocation) String() string { + return fmt.Sprintf("[consent revocation %s]", revocation.purpose) +} + +func (revocation ConsentRevocation) GoString() string { return revocation.String() } + +// Format applies String to every verb; without it %+v would print the +// subject and the organization. +func (revocation ConsentRevocation) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(revocation.String())) +} + +// LogValue carries only the purpose and the source. +func (revocation ConsentRevocation) LogValue() slog.Value { + return slog.GroupValue( + slog.String("purpose", string(revocation.purpose)), + slog.String("revocation_source", string(revocation.source)), + ) +} + +// ConsentRecord is one row of the consent ledger as read back, with the +// state the read model computed. It is personal data of the subject: +// String, GoString, Format, and LogValue show only the record ID, purpose, +// and state, never the subject, the organization, or the fields. +type ConsentRecord struct { + id uuid.UUID + subjectID uuid.UUID + purpose ConsentPurpose + textVersion ConsentTextVersion + textHash ConsentTextHash + source ConsentSource + state ConsentState + grantedAt time.Time + revokedAt time.Time + revocationSource ConsentRevocationSource + organizationID uuid.UUID + organizationName string + fields ContactFieldSet + invitationID uuid.UUID + invitationTermsVersion int64 +} + +// StoredConsentRecord carries the columns of a stored record. Absent C4 +// scope values are uuid.Nil, nil, and 0; an unrevoked record has a nil +// RevokedAt and an empty RevocationSource. +type StoredConsentRecord struct { + ID uuid.UUID + SubjectID uuid.UUID + Purpose string + TextVersion string + TextHash []byte + Source string + State string + GrantedAt time.Time + RevokedAt *time.Time + RevocationSource string + OrganizationID uuid.UUID + OrganizationName string + FieldSet []string + InvitationID uuid.UUID + InvitationTermsVersion int64 +} + +// RestoreConsentRecord validates a stored record against the rules the +// database enforces, so a row changed outside the application fails with +// ErrInvalidConsent or ErrInvalidConsentText. +func RestoreConsentRecord(stored StoredConsentRecord) (ConsentRecord, error) { + const location = "domain.RestoreConsentRecord" + purpose, err := ParseConsentPurpose(stored.Purpose) + if err != nil { + return ConsentRecord{}, fmt.Errorf("%s - validate purpose: %w", location, err) + } + version, err := ParseConsentTextVersion(stored.TextVersion) + if err != nil { + return ConsentRecord{}, fmt.Errorf("%s - validate text version: %w", location, err) + } + hash, err := ConsentTextHashFromBytes(stored.TextHash) + if err != nil { + return ConsentRecord{}, fmt.Errorf("%s - validate text hash: %w", location, err) + } + state, err := ParseConsentState(stored.State) + if err != nil { + return ConsentRecord{}, fmt.Errorf("%s - validate state: %w", location, err) + } + record := ConsentRecord{ + id: stored.ID, + subjectID: stored.SubjectID, + purpose: purpose, + textVersion: version, + textHash: hash, + source: ConsentSource(stored.Source), + state: state, + grantedAt: stored.GrantedAt, + revocationSource: ConsentRevocationSource(stored.RevocationSource), + organizationID: stored.OrganizationID, + organizationName: stored.OrganizationName, + invitationID: stored.InvitationID, + invitationTermsVersion: stored.InvitationTermsVersion, + } + if stored.RevokedAt != nil { + record.revokedAt = *stored.RevokedAt + } + if purpose.OrganizationScoped() { + fields, err := restoreContactFields(stored.FieldSet) + if err != nil { + return ConsentRecord{}, fmt.Errorf("%s - validate field set: %w", location, err) + } + record.fields = fields + } + if err := record.validate(stored.FieldSet != nil); err != nil { + return ConsentRecord{}, fmt.Errorf("%s - %w", location, err) + } + return record, nil +} + +func restoreContactFields(stored []string) (ContactFieldSet, error) { + fields := make([]ContactField, 0, len(stored)) + for _, value := range stored { + field, err := ParseContactField(value) + if err != nil { + return ContactFieldSet{}, err + } + fields = append(fields, field) + } + return NewContactFieldSet(fields...) +} + +// validate checks the invariants that RestoreConsentRecord cannot express +// while parsing single values. +func (record ConsentRecord) validate(hasFieldSet bool) error { + switch { + case record.id == uuid.Nil || record.subjectID == uuid.Nil: + return fmt.Errorf("record and subject IDs must not be nil: %w", ErrInvalidConsent) + case !record.source.allowedFor(record.purpose): + return fmt.Errorf("source does not allow the purpose: %w", ErrInvalidConsent) + case record.grantedAt.IsZero(): + return fmt.Errorf("grant time must be set: %w", ErrInvalidConsent) + } + if err := record.validateRevocation(); err != nil { + return err + } + return record.validateScope(hasFieldSet) +} + +// validateRevocation mirrors consent_records_revocation_stamp and ties the +// computed state to the stamp. +func (record ConsentRecord) validateRevocation() error { + revoked := !record.revokedAt.IsZero() + switch { + case revoked != (record.revocationSource != ""): + return fmt.Errorf("revocation time and source must be set together: %w", ErrInvalidConsent) + case revoked && (!record.revocationSource.known() || record.revokedAt.Before(record.grantedAt)): + return fmt.Errorf("revocation must have a known source and follow the grant: %w", ErrInvalidConsent) + case revoked != (record.state == ConsentStateRevoked): + return fmt.Errorf("state must match the revocation: %w", ErrInvalidConsent) + } + return nil +} + +// validateScope mirrors consent_records_c4_scope. +func (record ConsentRecord) validateScope(hasFieldSet bool) error { + if !record.purpose.OrganizationScoped() { + if record.organizationID != uuid.Nil || record.organizationName != "" || hasFieldSet || + record.invitationID != uuid.Nil || record.invitationTermsVersion != 0 { + return fmt.Errorf("only a C4 record has an organization scope: %w", ErrInvalidConsent) + } + return nil + } + switch { + case record.state == ConsentStateSuperseded: + return fmt.Errorf("a C4 record is never superseded: %w", ErrInvalidConsent) + case record.organizationID == uuid.Nil || record.invitationID == uuid.Nil || record.invitationTermsVersion <= 0: + return fmt.Errorf("a C4 record must have its organization and invitation: %w", ErrInvalidConsent) + case !validOrganizationName(record.organizationName): + return fmt.Errorf("a C4 record must have the organization name it was shown with: %w", ErrInvalidConsent) + } + return nil +} + +func (record ConsentRecord) ID() uuid.UUID { return record.id } +func (record ConsentRecord) SubjectID() uuid.UUID { return record.subjectID } +func (record ConsentRecord) Purpose() ConsentPurpose { return record.purpose } +func (record ConsentRecord) TextVersion() ConsentTextVersion { return record.textVersion } +func (record ConsentRecord) TextHash() ConsentTextHash { return record.textHash } +func (record ConsentRecord) Source() ConsentSource { return record.source } +func (record ConsentRecord) State() ConsentState { return record.state } +func (record ConsentRecord) GrantedAt() time.Time { return record.grantedAt } + +// RevokedAt returns the revocation time and true for a revoked record. +func (record ConsentRecord) RevokedAt() (time.Time, bool) { + return record.revokedAt, !record.revokedAt.IsZero() +} + +// RevocationSource is empty for an unrevoked record. +func (record ConsentRecord) RevocationSource() ConsentRevocationSource { + return record.revocationSource +} + +// OrganizationID, OrganizationName, Fields, InvitationID, and +// InvitationTermsVersion hold the C4 scope and are zero for every other +// purpose. OrganizationName is the name the shown text carried at the time +// of the consent, not the current name of the organization. +func (record ConsentRecord) OrganizationID() uuid.UUID { return record.organizationID } +func (record ConsentRecord) OrganizationName() string { return record.organizationName } +func (record ConsentRecord) Fields() ContactFieldSet { return record.fields } +func (record ConsentRecord) InvitationID() uuid.UUID { return record.invitationID } +func (record ConsentRecord) InvitationTermsVersion() int64 { return record.invitationTermsVersion } + +// IsZero reports a record not built by RestoreConsentRecord. +func (record ConsentRecord) IsZero() bool { return record.id == uuid.Nil } + +func (record ConsentRecord) String() string { + return fmt.Sprintf("[consent %s %s %s]", record.id, record.purpose, record.state) +} + +func (record ConsentRecord) GoString() string { return record.String() } + +// Format applies String to every verb; without it %+v would print the +// subject and the scope. +func (record ConsentRecord) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(record.String())) +} + +// LogValue carries only the record ID, purpose, and state. +func (record ConsentRecord) LogValue() slog.Value { + return slog.GroupValue( + slog.String("consent_record_id", record.id.String()), + slog.String("purpose", string(record.purpose)), + slog.String("state", string(record.state)), + ) +} + +func consentLogValue(id uuid.UUID, purpose ConsentPurpose) slog.Value { + return slog.GroupValue( + slog.String("consent_record_id", id.String()), + slog.String("purpose", string(purpose)), + ) +} diff --git a/backend/internal/domain/consent_test.go b/backend/internal/domain/consent_test.go new file mode 100644 index 0000000..ec27c60 --- /dev/null +++ b/backend/internal/domain/consent_test.go @@ -0,0 +1,437 @@ +package domain + +import ( + "bytes" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +var consentTestTime = time.Date(2026, 10, 6, 9, 30, 0, 0, time.UTC) + +const consentTestVersion ConsentTextVersion = "c1-2026-10-01" + +func TestParseConsentPurposeAcceptsOnlyC1ToC5(t *testing.T) { + for _, value := range []string{"c1", "c2", "c3", "c4", "c5"} { + purpose, err := ParseConsentPurpose(value) + if err != nil { + t.Fatalf("ParseConsentPurpose(%q) error = %v", value, err) + } + if purpose.OrganizationScoped() != (value == "c4") { + t.Fatalf("%s.OrganizationScoped() = %v, want true only for c4", value, purpose.OrganizationScoped()) + } + } + for _, value := range []string{"", "C1", "c0", "c6", "c1 "} { + if _, err := ParseConsentPurpose(value); !errors.Is(err, ErrInvalidConsent) { + t.Fatalf("ParseConsentPurpose(%q) error = %v, want ErrInvalidConsent", value, err) + } + } +} + +func TestParseConsentTextVersionFollowsTheContractPattern(t *testing.T) { + for _, value := range []string{"c1-2026-10-01", "v1.2_rc", strings.Repeat("a", 64)} { + if _, err := ParseConsentTextVersion(value); err != nil { + t.Fatalf("ParseConsentTextVersion(%q) error = %v", value, err) + } + } + for _, value := range []string{"", " ", "c1 2026", "c1/2026", "версия", strings.Repeat("a", 65)} { + if _, err := ParseConsentTextVersion(value); !errors.Is(err, ErrInvalidConsentText) { + t.Fatalf("ParseConsentTextVersion(%q) error = %v, want ErrInvalidConsentText", value, err) + } + } +} + +func TestConsentTextHashFromBytesRefusesEmptyAndMalformedDigests(t *testing.T) { + valid := HashConsentText("text") + if hash, err := ConsentTextHashFromBytes(valid[:]); err != nil || hash != valid { + t.Fatalf("ConsentTextHashFromBytes(valid) = %x, %v", hash, err) + } + for name, value := range map[string][]byte{ + "nil": nil, + "empty": {}, + "short": valid[:31], + "long": append(valid[:], 0), + "all zero": make([]byte, ConsentTextHashSize), + } { + if _, err := ConsentTextHashFromBytes(value); !errors.Is(err, ErrInvalidConsentText) { + t.Fatalf("ConsentTextHashFromBytes(%s) error = %v, want ErrInvalidConsentText", name, err) + } + } +} + +func storedText(purpose, body string) StoredConsentText { + hash := HashConsentText(body) + return StoredConsentText{ + Purpose: purpose, + Version: purpose + "-2026-10-01", + Body: body, + Hash: hash[:], + Kind: string(ConsentTextKindDemo), + PublishedAt: consentTestTime, + } +} + +func TestRestoreConsentTextChecksTheHashAndThePlaceholder(t *testing.T) { + text, err := RestoreConsentText(storedText("c1", "I consent.")) + if err != nil { + t.Fatalf("RestoreConsentText(c1) error = %v", err) + } + if text.Hash() != HashConsentText("I consent.") || text.Purpose() != ConsentPurposePersonalData { + t.Fatalf("restored text = %s %x, want the stored purpose and hash", text.Purpose(), text.Hash()) + } + + tampered := storedText("c1", "I consent.") + tampered.Body = "I consent to more." + changedKind := storedText("c1", "I consent.") + changedKind.Kind = "draft" + for name, stored := range map[string]StoredConsentText{ + "body changed after hashing": tampered, + "C4 without the placeholder": storedText("c4", "I consent to the transfer."), + "C2 with the placeholder": storedText("c2", "I consent for {organization}."), + "unknown kind": changedKind, + "empty body": storedText("c3", ""), + } { + if _, err := RestoreConsentText(stored); !errors.Is(err, ErrInvalidConsentText) { + t.Fatalf("RestoreConsentText(%s) error = %v, want ErrInvalidConsentText", name, err) + } + } +} + +func TestRenderForOrganizationNamesTheOrganizationOnlyInC4(t *testing.T) { + contact, err := RestoreConsentText(storedText("c4", "I consent to the transfer to {organization}.")) + if err != nil { + t.Fatalf("RestoreConsentText(c4) error = %v", err) + } + shown, err := contact.RenderForOrganization("ООО Пример") + if err != nil { + t.Fatalf("RenderForOrganization() error = %v", err) + } + if shown != "I consent to the transfer to ООО Пример." { + t.Fatalf("RenderForOrganization() = %q", shown) + } + // The ledger stores the hash of the shown text, which differs per + // organization and from the hash of the published template. + other, err := contact.RenderForOrganization("Other LLC") + if err != nil { + t.Fatalf("RenderForOrganization(other) error = %v", err) + } + if HashConsentText(shown) == contact.Hash() || HashConsentText(shown) == HashConsentText(other) { + t.Fatal("the shown C4 text must hash differently per organization and from the template") + } + for _, name := range []string{"", " Leading", "Trailing ", "Two\nlines", strings.Repeat("я", 201)} { + if _, err := contact.RenderForOrganization(name); !errors.Is(err, ErrInvalidConsentText) { + t.Fatalf("RenderForOrganization(%q) error = %v, want ErrInvalidConsentText", name, err) + } + } + personalData, err := RestoreConsentText(storedText("c1", "I consent.")) + if err != nil { + t.Fatalf("RestoreConsentText(c1) error = %v", err) + } + if _, err := personalData.RenderForOrganization("Acme"); !errors.Is(err, ErrInvalidConsentText) { + t.Fatalf("RenderForOrganization(C1) error = %v, want ErrInvalidConsentText", err) + } +} + +func TestNewContactFieldSetIsCanonicalAndRefusesDuplicates(t *testing.T) { + set, err := NewContactFieldSet(ContactFieldTelegram, ContactFieldEmail, ContactFieldFullName) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + reordered, err := NewContactFieldSet(ContactFieldFullName, ContactFieldTelegram, ContactFieldEmail) + if err != nil { + t.Fatalf("NewContactFieldSet(reordered) error = %v", err) + } + if !set.Equal(reordered) || fmt.Sprint(set.Fields()) != "[email full_name telegram]" { + t.Fatalf("Fields() = %v, want the canonical order for any input order", set.Fields()) + } + if set.Contains(ContactFieldPhone) { + t.Fatal("one field must never imply another") + } + fields := set.Fields() + fields[0] = ContactFieldPhone + if set.Contains(ContactFieldPhone) { + t.Fatal("Fields() must return a copy") + } + for name, input := range map[string][]ContactField{ + "empty": nil, + "duplicate": {ContactFieldEmail, ContactFieldEmail}, + "unknown": {ContactFieldEmail, "address"}, + "too many": {ContactFieldEmail, ContactFieldPhone, ContactFieldTelegram, ContactFieldFullName, ContactFieldEmail}, + } { + if _, err := NewContactFieldSet(input...); !errors.Is(err, ErrInvalidConsent) { + t.Fatalf("NewContactFieldSet(%s) error = %v, want ErrInvalidConsent", name, err) + } + } +} + +func validGrantInput() ConsentGrantInput { + return ConsentGrantInput{ + SubjectID: uuid.Must(uuid.NewV7()), + Purpose: ConsentPurposePersonalData, + TextVersion: consentTestVersion, + TextHash: HashConsentText("I consent."), + Source: ConsentSourceRegistration, + GrantedAt: consentTestTime, + } +} + +func TestNewConsentGrantValidatesEveryField(t *testing.T) { + grant, err := NewConsentGrant(validGrantInput()) + if err != nil { + t.Fatalf("NewConsentGrant() error = %v", err) + } + if grant.ID().Version() != 7 || grant.Purpose() != ConsentPurposePersonalData || grant.IsZero() { + t.Fatalf("grant = %s %s, want a UUIDv7 C1 grant", grant.ID(), grant.Purpose()) + } + for name, change := range map[string]func(*ConsentGrantInput){ + "C4 without its scope": func(input *ConsentGrantInput) { + input.Purpose, input.Source = ConsentPurposeContactDisclosure, ConsentSourceInvitationAcceptance + }, + "unknown purpose": func(input *ConsentGrantInput) { input.Purpose = "c9" }, + "empty text version": func(input *ConsentGrantInput) { input.TextVersion = "" }, + "malformed text version": func(input *ConsentGrantInput) { input.TextVersion = "c1 v2" }, + "missing text hash": func(input *ConsentGrantInput) { input.TextHash = ConsentTextHash{} }, + "missing subject": func(input *ConsentGrantInput) { input.SubjectID = uuid.Nil }, + "registration of C2": func(input *ConsentGrantInput) { input.Purpose = ConsentPurposePublication }, + "invitation acceptance of C3": func(input *ConsentGrantInput) { + input.Purpose, input.Source = ConsentPurposeAutoCategorization, ConsentSourceInvitationAcceptance + }, + "unknown source": func(input *ConsentGrantInput) { input.Source = "import" }, + "missing grant time": func(input *ConsentGrantInput) { input.GrantedAt = time.Time{} }, + } { + input := validGrantInput() + change(&input) + _, err := NewConsentGrant(input) + if !errors.Is(err, ErrInvalidConsent) && !errors.Is(err, ErrInvalidConsentText) { + t.Fatalf("NewConsentGrant(%s) error = %v, want a validation error", name, err) + } + } +} + +const consentTestC4Body = "I consent to the transfer to {organization}." + +func contactText(t *testing.T) ConsentText { + t.Helper() + text, err := RestoreConsentText(storedText("c4", consentTestC4Body)) + if err != nil { + t.Fatalf("RestoreConsentText(c4) error = %v", err) + } + return text +} + +func validContactGrantInput(t *testing.T) ContactConsentGrantInput { + t.Helper() + fields, err := NewContactFieldSet(ContactFieldEmail) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + return ContactConsentGrantInput{ + SubjectID: uuid.Must(uuid.NewV7()), + OrganizationID: uuid.Must(uuid.NewV7()), + OrganizationName: "Acme", + Fields: fields, + InvitationID: uuid.Must(uuid.NewV7()), + InvitationTermsVersion: 2, + Text: contactText(t), + GrantedAt: consentTestTime, + } +} + +func TestNewContactConsentGrantRequiresItsScope(t *testing.T) { + grant, err := NewContactConsentGrant(validContactGrantInput(t)) + if err != nil { + t.Fatalf("NewContactConsentGrant() error = %v", err) + } + if grant.IsZero() || !grant.Fields().Contains(ContactFieldEmail) || grant.InvitationTermsVersion() != 2 || + grant.OrganizationName() != "Acme" || grant.TextVersion() != "c4-2026-10-01" { + t.Fatalf("grant = %s, want the given scope", grant.ID()) + } + // The grant hashes the text as shown for the organization; a caller + // never supplies hash bytes. + if grant.TextHash() != HashConsentText("I consent to the transfer to Acme.") { + t.Fatalf("TextHash() = %x, want the hash of the shown text", grant.TextHash()) + } + personalData, err := RestoreConsentText(storedText("c1", "I consent.")) + if err != nil { + t.Fatalf("RestoreConsentText(c1) error = %v", err) + } + for name, change := range map[string]func(*ContactConsentGrantInput){ + "missing organization": func(input *ContactConsentGrantInput) { input.OrganizationID = uuid.Nil }, + "missing organization name": func(input *ContactConsentGrantInput) { input.OrganizationName = "" }, + "multi-line name": func(input *ContactConsentGrantInput) { input.OrganizationName = "Acme\nLLC" }, + "missing field set": func(input *ContactConsentGrantInput) { input.Fields = ContactFieldSet{} }, + "missing invitation": func(input *ContactConsentGrantInput) { input.InvitationID = uuid.Nil }, + "non-positive terms version": func(input *ContactConsentGrantInput) { input.InvitationTermsVersion = 0 }, + "missing subject": func(input *ContactConsentGrantInput) { input.SubjectID = uuid.Nil }, + "missing text": func(input *ContactConsentGrantInput) { input.Text = ConsentText{} }, + "text of another purpose": func(input *ContactConsentGrantInput) { input.Text = personalData }, + "missing grant time": func(input *ContactConsentGrantInput) { input.GrantedAt = time.Time{} }, + } { + input := validContactGrantInput(t) + change(&input) + _, err := NewContactConsentGrant(input) + if !errors.Is(err, ErrInvalidConsent) && !errors.Is(err, ErrInvalidConsentText) { + t.Fatalf("NewContactConsentGrant(%s) error = %v, want a validation error", name, err) + } + } +} + +func TestGrantsAndRevocationsShowNoSubjectOrScope(t *testing.T) { + input := validContactGrantInput(t) + contact, err := NewContactConsentGrant(input) + if err != nil { + t.Fatalf("NewContactConsentGrant() error = %v", err) + } + personalInput := validGrantInput() + personal, err := NewConsentGrant(personalInput) + if err != nil { + t.Fatalf("NewConsentGrant() error = %v", err) + } + revocation, err := NewConsentRevocation(ConsentRevocationInput{ + SubjectID: input.SubjectID, Purpose: ConsentPurposeContactDisclosure, OrganizationID: input.OrganizationID, + Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime, + }) + if err != nil { + t.Fatalf("NewConsentRevocation() error = %v", err) + } + var logs bytes.Buffer + logger := slog.New(slog.NewJSONHandler(&logs, nil)) + logger.Info("consent", "contact", contact, "personal", personal, "revocation", revocation) + output := logs.String() + fmt.Sprintf("%v %+v %#v %+v %+v", contact, contact, personal, revocation, struct{ Grant ContactConsentGrant }{contact}) + for _, private := range []string{ + input.SubjectID.String(), input.OrganizationID.String(), input.InvitationID.String(), + personalInput.SubjectID.String(), "Acme", "email", + } { + if strings.Contains(output, private) { + t.Fatalf("output %q contains %q", output, private) + } + } +} + +func TestNewConsentRevocationScopesOnlyC4ByOrganization(t *testing.T) { + subject, organization := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + valid := []ConsentRevocationInput{ + {SubjectID: subject, Purpose: ConsentPurposePublication, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime}, + {SubjectID: subject, Purpose: ConsentPurposeContactDisclosure, OrganizationID: organization, Source: ConsentRevocationSourceSupportRequest, RevokedAt: consentTestTime}, + } + for _, input := range valid { + if _, err := NewConsentRevocation(input); err != nil { + t.Fatalf("NewConsentRevocation(%s) error = %v", input.Purpose, err) + } + } + for name, input := range map[string]ConsentRevocationInput{ + "C4 without an organization": {SubjectID: subject, Purpose: ConsentPurposeContactDisclosure, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime}, + "C1 with an organization": {SubjectID: subject, Purpose: ConsentPurposePersonalData, OrganizationID: organization, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime}, + "unknown source": {SubjectID: subject, Purpose: ConsentPurposePersonalData, Source: "admin", RevokedAt: consentTestTime}, + "missing subject": {Purpose: ConsentPurposePersonalData, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime}, + "missing time": {SubjectID: subject, Purpose: ConsentPurposePersonalData, Source: ConsentRevocationSourceConsentSettings}, + } { + if _, err := NewConsentRevocation(input); !errors.Is(err, ErrInvalidConsent) { + t.Fatalf("NewConsentRevocation(%s) error = %v, want ErrInvalidConsent", name, err) + } + } +} + +func storedRecord(purpose string) StoredConsentRecord { + hash := HashConsentText("shown text") + record := StoredConsentRecord{ + ID: uuid.Must(uuid.NewV7()), + SubjectID: uuid.Must(uuid.NewV7()), + Purpose: purpose, + TextVersion: purpose + "-2026-10-01", + TextHash: hash[:], + Source: string(ConsentSourceConsentSettings), + State: string(ConsentStateActive), + GrantedAt: consentTestTime, + } + if purpose == "c4" { + record.Source = string(ConsentSourceInvitationAcceptance) + record.OrganizationID = uuid.Must(uuid.NewV7()) + record.OrganizationName = "Acme" + record.FieldSet = []string{"phone", "email"} + record.InvitationID = uuid.Must(uuid.NewV7()) + record.InvitationTermsVersion = 1 + } + return record +} + +func TestRestoreConsentRecordMirrorsTheLedgerConstraints(t *testing.T) { + for _, purpose := range []string{"c1", "c2", "c3", "c4", "c5"} { + if _, err := RestoreConsentRecord(storedRecord(purpose)); err != nil { + t.Fatalf("RestoreConsentRecord(%s) error = %v", purpose, err) + } + } + revokedAt := consentTestTime.Add(time.Hour) + earlier := consentTestTime.Add(-time.Hour) + for name, change := range map[string]func(*StoredConsentRecord){ + "C4 without an organization": func(record *StoredConsentRecord) { record.OrganizationID = uuid.Nil }, + "C4 without its name snapshot": func(record *StoredConsentRecord) { record.OrganizationName = "" }, + "C4 with an empty field set": func(record *StoredConsentRecord) { record.FieldSet = []string{} }, + "C4 superseded": func(record *StoredConsentRecord) { + record.State = string(ConsentStateSuperseded) + }, + "C4 from the settings": func(record *StoredConsentRecord) { record.Source = string(ConsentSourceConsentSettings) }, + "revoked state without a stamp": func(record *StoredConsentRecord) { + record.State = string(ConsentStateRevoked) + }, + "stamp without a source": func(record *StoredConsentRecord) { + record.RevokedAt, record.State = &revokedAt, string(ConsentStateRevoked) + }, + "revocation before the grant": func(record *StoredConsentRecord) { + record.RevokedAt, record.RevocationSource, record.State = &earlier, string(ConsentRevocationSourceConsentSettings), string(ConsentStateRevoked) + }, + "empty hash": func(record *StoredConsentRecord) { record.TextHash = nil }, + "empty version": func(record *StoredConsentRecord) { record.TextVersion = "" }, + "unknown state": func(record *StoredConsentRecord) { record.State = "pending" }, + } { + record := storedRecord("c4") + change(&record) + _, err := RestoreConsentRecord(record) + if !errors.Is(err, ErrInvalidConsent) && !errors.Is(err, ErrInvalidConsentText) { + t.Fatalf("RestoreConsentRecord(%s) error = %v, want a validation error", name, err) + } + } + scoped := storedRecord("c3") + scoped.FieldSet = []string{"email"} + if _, err := RestoreConsentRecord(scoped); !errors.Is(err, ErrInvalidConsent) { + t.Fatalf("RestoreConsentRecord(C3 with fields) error = %v, want ErrInvalidConsent", err) + } + named := storedRecord("c1") + named.OrganizationName = "Acme" + if _, err := RestoreConsentRecord(named); !errors.Is(err, ErrInvalidConsent) { + t.Fatalf("RestoreConsentRecord(C1 with an organization name) error = %v, want ErrInvalidConsent", err) + } +} + +func TestConsentRecordOutputShowsNoSubjectOrScope(t *testing.T) { + stored := storedRecord("c4") + record, err := RestoreConsentRecord(stored) + if err != nil { + t.Fatalf("RestoreConsentRecord() error = %v", err) + } + var logs bytes.Buffer + for _, logger := range []*slog.Logger{ + slog.New(slog.NewTextHandler(&logs, nil)), + slog.New(slog.NewJSONHandler(&logs, nil)), + } { + logger.Info("consent", "record", record) + } + output := strings.Join([]string{ + logs.String(), + fmt.Sprintf("%v %+v %#v %s", record, record, record, record), + fmt.Sprintf("%+v", struct{ Record ConsentRecord }{record}), + }, "\n") + for _, private := range []string{stored.SubjectID.String(), stored.OrganizationID.String(), stored.InvitationID.String(), "phone", "Acme"} { + if strings.Contains(output, private) { + t.Fatalf("output %q contains %q", output, private) + } + } + if !strings.Contains(output, record.ID().String()) || !strings.Contains(output, "c4") { + t.Fatalf("output %q, want the record ID and purpose", output) + } +} diff --git a/backend/internal/port/outbound/consents.go b/backend/internal/port/outbound/consents.go new file mode 100644 index 0000000..77b2075 --- /dev/null +++ b/backend/internal/port/outbound/consents.go @@ -0,0 +1,160 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrConsentTextNotFound reports that no text has the purpose and + // version, or no text of the purpose is published at the time. + ErrConsentTextNotFound = errors.New("consent text not found") + + // ErrConsentTextMismatch reports a grant whose hash is not the hash of + // the published text of its version: for C1-C3 and C5 the text itself, + // for C4 the text with the stored organization name filled in. + ErrConsentTextMismatch = errors.New("consent text hash does not match the published text") + + // ErrConsentTextNotPublished reports a grant for a text version whose + // publication time is after the grant time. + ErrConsentTextNotPublished = errors.New("consent text not published at the grant time") + + // ErrConsentNotFound reports that the subject has no unrevoked record of + // the purpose. + ErrConsentNotFound = errors.New("consent not found") + + // ErrConsentInvitationTaken reports a C4 grant for an invitation whose C4 + // record belongs to another subject. Nothing was stored. + ErrConsentInvitationTaken = errors.New("invitation consent belongs to another subject") + + // ErrConsentRecordImmutable reports an attempt to change a record other + // than by its one revocation stamp, or to delete a record of a confirmed + // account. The database refuses both. + ErrConsentRecordImmutable = errors.New("consent record is immutable") +) + +// ConsentRepositories exposes the consent texts and the consent ledger. +// UnitOfWork binds them to one transaction, so a business operation records +// a consent atomically with its own changes: the registration with C1, the +// invitation acceptance with C4. An adapter may also provide them outside a +// transaction, where every call is its own statement. Every method that +// takes a time rejects the zero time. +type ConsentRepositories interface { + ConsentTexts() ConsentTextRepository + ConsentLedger() ConsentLedger +} + +// ConsentTextRepository reads the immutable published consent texts. It has +// no write method: texts are published by migrations. +type ConsentTextRepository interface { + // Get returns the text with the purpose and version, published or + // scheduled, or ErrConsentTextNotFound. + Get(ctx context.Context, purpose domain.ConsentPurpose, version domain.ConsentTextVersion) (domain.ConsentText, error) + + // Current returns the text of the purpose with the latest publication + // time not after at, or ErrConsentTextNotFound. + Current(ctx context.Context, purpose domain.ConsentPurpose, at time.Time) (domain.ConsentText, error) +} + +// ConsentLedger stores the append-only consent ledger. A grant is a new +// record; history is never rewritten except for the one revocation stamp of +// a record. Every read and every revocation is scoped by the subject, so a +// caller cannot reach another subject's records through it. +// +// A grant binds the record to a stored text version: an unknown version +// fails with ErrConsentTextNotFound, a version published after the grant +// time with ErrConsentTextNotPublished, and, for C1-C3 and C5, a hash other +// than the hash of that text with ErrConsentTextMismatch. An unknown subject +// fails with ErrUserNotFound. These failures come from the database and +// abort a surrounding transaction. +type ConsentLedger interface { + // Grant records a grant of C1, C2, C3, or C5 and returns the record + // with created true. When the subject already has an unrevoked record of + // the purpose and text version, it returns that record with created + // false and stores nothing, without aborting a surrounding transaction. + // A grant of another version is a new record next to the earlier one. + // Superseded is decided by granted_at, then the record ID: the + // unrevoked record granted last is active, whatever its text version, + // so Grant accepts any published version. The grant usecase (TASK-063) + // must check that the version is the current text of the purpose, + // ConsentTexts().Current at the grant time, before it calls Grant. + Grant(ctx context.Context, grant domain.ConsentGrant) (record domain.ConsentRecord, created bool, err error) + + // GrantContact records the C4 grant of an invitation acceptance with its + // organization, the organization name as the shown text named it, the + // field set, the invitation, and the terms version. The database checks + // that the hash is the hash of the published text with that name, so the + // stored name is the snapshot a later rename never changes. It is meant to + // run in the acceptance transaction next to the state change, the grant, + // and the audit event, so all of them commit or roll back together. + // When the invitation already has a C4 record of the same subject, it + // returns that record, revoked or not, with created false and stores + // nothing; the caller compares its scope to decide between a repeat and + // a conflict. When the record belongs to another subject it returns + // ErrConsentInvitationTaken. Neither case aborts the transaction. + GrantContact(ctx context.Context, grant domain.ContactConsentGrant) (record domain.ConsentRecord, created bool, err error) + + // Revoke stamps every unrevoked record of the revocation's purpose, and + // for C4 of its organization only, with the revocation time and source, + // and returns the revoked records. Superseded records of the purpose are + // revoked too. Records that are already revoked keep their first stamp; + // with nothing to revoke the result is empty, so a repeat is harmless. + // A later grant is a new record. A revocation time before the grant + // time of a record, from clock skew between instances, is stamped at + // the grant time. + Revoke(ctx context.Context, revocation domain.ConsentRevocation) ([]domain.ConsentRecord, error) + + // Current returns the newest unrevoked record of C1, C2, C3, or C5, or + // ErrConsentNotFound. C4 fails with domain.ErrInvalidConsent; use + // CurrentContact. + Current(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) + + // CurrentContact returns the unrevoked C4 records of the subject for the + // organization, newest first, one per accepted invitation. The result + // is empty when there is none. + CurrentContact(ctx context.Context, subjectID uuid.UUID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) + + // List returns one page of the subject's records, newest grant first, + // with the state of each record. It is the read model of the subject's + // own consents and history. + List(ctx context.Context, query ConsentListQuery) (ConsentPage, error) +} + +// ConsentListQuery selects one page of a subject's ledger. +type ConsentListQuery struct { + SubjectID uuid.UUID + // State limits the page to one state; empty selects every record. + State domain.ConsentState + // After continues after the position of the last record of the previous + // page; nil reads the first page. + After *ConsentListPosition + // Limit is the page size, from 1 to MaxConsentPageSize. + Limit int32 +} + +// MaxConsentPageSize matches the largest page of the contract. +const MaxConsentPageSize = 100 + +// ConsentListPosition is the ordering key of a record in List. +type ConsentListPosition struct { + GrantedAt time.Time + ID uuid.UUID +} + +// ConsentPositionOf returns the ordering key of record for the next page. +func ConsentPositionOf(record domain.ConsentRecord) ConsentListPosition { + return ConsentListPosition{GrantedAt: record.GrantedAt(), ID: record.ID()} +} + +// ConsentPage is one page of List. +type ConsentPage struct { + Records []domain.ConsentRecord + // HasMore reports that another page follows; read it with After set to + // the position of the last record. + HasMore bool +} diff --git a/backend/internal/port/outbound/identity.go b/backend/internal/port/outbound/identity.go index cf8b4a7..6dde4e3 100644 --- a/backend/internal/port/outbound/identity.go +++ b/backend/internal/port/outbound/identity.go @@ -88,6 +88,13 @@ type UserRepository interface { // RegistrationVersion by one, so callers never choose the registration // version; the returned account carries the new values. Otherwise it // returns ErrUserVersionConflict. + // + // The same statement deletes the C1 records with the source + // registration that the earlier registration of this account stored, + // because the earlier registrant's consent must never stand for the new + // one. The registration usecase (TASK-053) must record the new C1 with + // ConsentLedger().Grant in the same transaction; a version conflict + // deletes nothing. UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error) // MarkEmailVerified sets the verification time when the account is still @@ -99,11 +106,14 @@ type UserRepository interface { // DeleteUnverifiedRegisteredBefore deletes at most limit accounts that are // unverified and were last registered before cutoff, oldest first, with - // their tokens, sessions, and mail deliveries, and returns how many it - // deleted. It never waits for a lock: an account whose row, token, - // session, or delivery is locked by another transaction is skipped and - // stays for the next run. A cleanup job - // repeats it until the result is below limit and runs again later. + // their tokens, sessions, mail deliveries, and consent records, and + // returns how many it deleted. It never waits for a lock: an account + // whose row, token, session, delivery, or consent record is locked by + // another transaction is skipped and stays for the next run. A consent + // recorded for a candidate account after the statement started fails the + // restricting foreign key; the run then returns an error matching + // ErrTransactionConflict, deletes nothing, and may be repeated. A cleanup + // job repeats it until the result is below limit and runs again later. DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error) } diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index 3afc0a1..b8ff14b 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -49,6 +49,7 @@ type Transactor interface { // repositories are added here as their usecases appear. type UnitOfWork interface { IdentityRepositories + ConsentRepositories Policies() PolicyRepository Deliveries() DeliveryRepository MailRequests() MailRequestRepository diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 4d1e7aa..c67f2ad 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -416,7 +416,7 @@ backend/ cmd/app/main.go calls bootstrap.Run and reports errors config/ shared runtime configuration internal/ - domain/ flat package; DomainEvent, identity types, product policy + domain/ flat package; DomainEvent, identity types, consent ledger, product policy usecase/health/ operational readiness usecase port/inbound/ readiness and event handler input boundaries usecase/identity/ password validation before hashing (Credentials) @@ -424,7 +424,7 @@ backend/ usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums usecase/notification/ mail requests and the consumer that stores them as deliveries usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it - port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, policy, password hashing, and mail boundaries + port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, policy, password hashing, and mail boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -437,7 +437,7 @@ backend/ mail/disabled/ mail transport that sends nothing and reports the channel unavailable mail/resend/ mail transport that sends one request to the Resend HTTP API per message ml/api/ generated client from backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity and policy repositories, health check + postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, and policy repositories, health check postgres/sqlc/ generated SQL adapter redis/ cache adapter and Redis check seaweedfs/ S3 adapter and bucket check @@ -447,12 +447,12 @@ backend/ worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown worker/retry/ backoff with jitter and a context-aware wait shared by the workers bootstrap/ configuration, wiring, lifecycle, shutdown - db/ embedded migrations and SQL queries; outbox, identity, policy, event consumer, delivery, mail quota, and scheduled job tables + db/ embedded migrations and SQL queries; outbox, identity, policy, event consumer, delivery, mail quota, scheduled job, and consent ledger tables codegen/ ogen and sqlc configs pkg/testutil/ fake application clock shared by tests ``` -Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`. +Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The consent ledger types live in `consent.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`. Product domain types and usecase modules, the SMTP and FSP adapters, and product worker jobs are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. @@ -556,7 +556,7 @@ Implemented as storage only (TASK-051): migration `backend/db/migrations/00002_c - `users`: UUIDv7 `id`; `email`, the delivery form (trimmed ASCII, letter case as typed, returned as `Account.email`), and `email_normalized`, the unique comparison key (the same address with A-Z lowercased); `password_hash`, an Argon2id v19 PHC string; `scenario` and `onboarding_step` with a CHECK that the step belongs to the scenario; nullable `email_verified_at`; `registration_version`; `last_registered_at` with a partial index over unverified accounts for the planned 7-day cleanup; the optimistic `version`; `created_at` and `updated_at`. The delivery form is kept because RFC 5321 allows a case-sensitive local part: mail goes to the address as typed, while uniqueness ignores letter case. - `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists the allowed purposes, so a password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. A CHECK allows at most one of consumed and invalidated. - `sessions`: a UUIDv7 `id` that never leaves the server, `token_hash` (SHA-256 of the cookie value, unique), `user_id`, `created_at`, `last_seen_at`, the absolute `expires_at`, and `revoked_at`. No IP address or user agent is stored. -- Tokens and sessions reference `users` with `ON DELETE CASCADE`. The consent tables planned in TASK-062 can reference `users.id` the same way. CHECK constraints repeat the domain rules as a backstop: the ASCII address and its key, the PHC format, and timestamps (verification, consumption, invalidation, and revocation) not earlier than `created_at`. +- Tokens and sessions reference `users` with `ON DELETE CASCADE`. Consent records reference it with `ON DELETE RESTRICT` instead; see [Consent ledger](#consent-ledger). CHECK constraints repeat the domain rules as a backstop: the ASCII address and its key, the PHC format, and timestamps (verification, consumption, invalidation, and revocation) not earlier than `created_at`. Decisions: @@ -568,11 +568,11 @@ Decisions: What the ports guarantee: -- `UserRepository.Create` returns `ErrEmailTaken` for a duplicate key. `UpdateRegistration` stores the result of `domain.User.ReRegister` only when the stored `version` matches and the email is unverified; the same statement advances `version` and `registration_version` by one, so no caller chooses the registration version. `MarkEmailVerified` applies only to an unverified account with the given registration version. Both return `ErrUserVersionConflict` otherwise. +- `UserRepository.Create` returns `ErrEmailTaken` for a duplicate key. `UpdateRegistration` stores the result of `domain.User.ReRegister` only when the stored `version` matches and the email is unverified; the same statement advances `version` and `registration_version` by one, so no caller chooses the registration version, and deletes the registration C1 of the earlier registrant (see [Consent ledger](#consent-ledger)). `MarkEmailVerified` applies only to an unverified account with the given registration version. Both return `ErrUserVersionConflict` otherwise. - `EmailTokenRepository.Consume` is one `UPDATE ... RETURNING` that requires an unconsumed, uninvalidated, unexpired token. Concurrent callers queue on the token row lock; under READ COMMITTED each waiter re-checks the row after the holder finishes, so exactly one succeeds and, if the holder rolls back, a waiter can still succeed. A miss is reported as `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (replaced, or issued for an earlier registration version), or `ErrEmailTokenExpired`. `InvalidateActive` marks every earlier token of a user and purpose. - Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase (TASK-054) maps that outcome to `verification_token_invalid`. - `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` writes `last_seen_at` only when the stored value is more than one minute older, so frequent requests do not rewrite the row and the idle timeout can end a session up to a minute early; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`. -- `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, their sessions, their mail requests, and their mail deliveries with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token, session, mail request, or delivery row, is locked by another transaction, such as a re-registration, a resend, a confirmation, the delivery consumer, or a delivery worker; skipped accounts stay for the next run. The mail requests, deliveries, and attempts go with the account by cascade. +- `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, their sessions, their mail requests, their mail deliveries, and their consent records with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token, session, mail request, delivery, or consent row, is locked by another transaction, such as a re-registration, a resend, a confirmation, the delivery consumer, or a delivery worker; skipped accounts stay for the next run. The mail requests, deliveries, and attempts go with the account by cascade; the consent records, which restrict the delete, are deleted explicitly in the same statement. - `postgres.IdentityStore` runs the same repositories outside a transaction. Called with a context from a `Transactor` callback, it returns `ErrNestedTransaction` instead of committing on a separate connection. - Unique and foreign key violations map to `ErrEmailTaken`, `ErrTokenHashConflict`, and `ErrUserNotFound` by SQLSTATE and constraint name, never by error text. - Lock order: an operation that changes both an account and its tokens locks the tokens first. A confirmation consumes the token and then verifies the account, so a re-registration or resend calls `InvalidateActive` before it updates the account or inserts a token; the opposite order can deadlock. The cleanup is the only exception: it locks the account before the tokens and sessions, which is safe because each of those locks uses SKIP LOCKED and never waits. A deadlock (SQLSTATE 40P01) or serialization failure (40001) that still happens is reported by `Transactor.WithinTransaction` and the identity repositories as `outbound.ErrTransactionConflict`; nothing was committed, and the usecase or job may retry the whole operation with backoff while staying idempotent. @@ -590,6 +590,36 @@ Implemented (TASK-052) and tested, but not wired into bootstrap: registration (T - `identity.Credentials.HashNewPassword` validates a new password and only then hashes it; registration will call it on every branch before it looks up the email. - Errors and logs never contain the password or the hash. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken`, and `domain.EmailAddress` redact themselves in `fmt`, `slog`, and JSON output, and keep their value behind a pointer, so printing an enclosing struct, even through an unexported field, shows only an address. +### Consent ledger + +Implemented as storage, ports, and a read contract (TASK-062): migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, the ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Granting C1-C3 and C5 with a current-version check (TASK-063), revocation with its downstream effects and the HTTP handler (TASK-064), C1 in the registration transaction (TASK-053), and C4 in the invitation acceptance (TASK-201) are planned; no usecase writes the ledger yet. + +The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation of one never changes another. + +`consent_texts` holds the published texts: `purpose`, `version` (the contract's `ConsentTextVersion`), the exact `body`, `body_sha256` checked against the body by a CHECK, `kind` (`demo` for synthetic texts without a legal review, `operator` for texts of the actual operator), and `published_at`. The current text of a purpose is the latest publication not after the grant time. Texts are immutable: a trigger refuses UPDATE, DELETE, and TRUNCATE (`consent_texts_immutable`), and a changed text is a new version. The migration publishes demo version `cN-2026-10-01` of every purpose; the operator's texts arrive as new versions in a later migration before real data are accepted (PRD 7.3). Only the C4 text contains the placeholder `{organization}`; `ConsentText.RenderForOrganization` fills it in. + +`consent_records` is the append-only ledger. One row per grant: UUIDv7 `id`, `subject_id`, `purpose`, `text_version`, `text_hash` (SHA-256 of exactly the text the subject saw, 32 bytes), `source` (`registration` for C1 only, `consent_settings` for C1-C3 and C5, `invitation_acceptance` for C4 only), `granted_at`, and the one-time revocation stamp `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A C4 row also has `organization_id`, `organization_name` (the name the shown text carried, a snapshot of 1-200 characters), the canonical `field_set` (one to four distinct `ContactFieldKind` values in ascending byte order), `invitation_id`, and `invitation_terms_version`; every other purpose must leave them NULL (`consent_records_c4_scope`). Request metadata such as IP addresses or user agents is not stored: the PRD asks for the version, hash, time, subject, and revocation event, and the extra data would be personal data without a purpose. + +Decisions: + +- Text binding. A foreign key on (`purpose`, `text_version`) refuses a version that was never published for the purpose, and a BEFORE INSERT trigger refuses a version published after the grant time (`consent_records_text_published`). For C1-C3 and C5 a second foreign key over a generated column requires `text_hash` to equal the hash of the published text. For C4 the same trigger requires `text_hash` to equal the SHA-256 of the published text with `organization_name` filled in (`consent_records_c4_text_hash`). The domain computes that hash itself in `domain.NewContactConsentGrant` from the published `ConsentText` and the name, so no caller supplies hash bytes, and a client can invent neither a version nor a hash. The stored name is the snapshot that proves the shown text; a later rename of the organization does not change it, and the read model returns it as `ConsentOrganization.name`. +- History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (`consent_records_immutable`). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (`active`, `superseded`, `revoked`) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (by `granted_at`, then ID) is `active` and the others are `superseded`, whatever their versions. The ledger therefore accepts any published version, and the grant usecase (TASK-063) must check that the version is the current text before it calls `Grant`. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index on `invitation_id` keeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back. +- Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to TASK-064 and are not implemented. +- Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request of TASK-064 and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration. +- Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for TASK-053: the registration usecase calls `UpdateRegistration` and records the new C1 with `ConsentLedger().Grant` in the same transaction. +- C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are evidence of the publication history of TASK-088, which must keep them with their times. Adding a field scope to C2 rows later is an additive migration and contract change. +- C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The acceptance (TASK-201) calls it in the transaction that moves the invitation to `accepted`, creates the grant, and writes the audit event, so all of them commit or roll back together. A repeated acceptance gets the existing record with `created` false and compares its scope; an invitation whose C4 belongs to another subject returns `ErrConsentInvitationTaken`. +- Cleanup race. The cleanup checks consent rows in its statement snapshot. A consent committed for a candidate account after that snapshot but before the account lock fails the restricting foreign key at the end of the statement (SQLSTATE 23001); the adapter reports it as `ErrTransactionConflict`, nothing is deleted, and the next run sees the consent. +- Scoping. Every read and revocation takes the subject, and the contract operation takes it from the session, so the read model returns only the caller's own records. Errors of the adapter keep the SQLSTATE and constraint name only, and `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant`, and `ConsentRevocation` show no subject, organization, name, or fields in `fmt` and `slog` output. + +Legal check items, not decided by this storage: deleting the C1 of never-confirmed accounts against the three-year retention of consents in PRD 7.3; 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 and may need a field scope on the C2 record; and the operator texts that replace the demo texts. + +What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWork` and as `postgres.ConsentStore` outside a transaction): + +- `ConsentTexts().Get` and `Current` read published texts and verify the stored hash on every read. +- `ConsentLedger().Grant` and `GrantContact` return the new record with `created` true or the existing one with `created` false. An unknown subject returns `ErrUserNotFound`, an unknown version `ErrConsentTextNotFound`, a version published later `ErrConsentTextNotPublished`, and a hash that does not match the published text (for C4 with the stored name) `ErrConsentTextMismatch`; these come from the database and abort a surrounding transaction. A duplicate does not. A grant whose conflicting record was revoked between its two statements returns `ErrTransactionConflict`. +- `Revoke` returns the rows it stamped. `Current` returns the newest unrevoked C1-C3 or C5 record or `ErrConsentNotFound`; `CurrentContact` returns the unrevoked C4 records of one organization. `List` pages the subject's ledger newest first, optionally by state. + ## Frontend The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 6116bbe..f62daf0 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -13,6 +13,8 @@ deploy/docker/docker-compose.yml starts PostgreSQL, Redis, SeaweedFS, Kafka, the Before it opens its listeners, the backend applies the database migrations embedded in its binary; a migration error stops the container. Compose does not pass `DATABASE_MIGRATE_ON_START`, so the deployed backend always migrates at startup, and the PostgreSQL role in `DATABASE_URL` needs DDL rights on the application schema. That flag is a local development option; a separate least-privilege migration role is future work. Right after the migrations, and only when they run, the backend seeds the demo product policy: when the `product` policy family has no version, it publishes version 1 and logs `demo product policy published`; otherwise it logs that the seed was skipped and changes nothing. With `DATABASE_MIGRATE_ON_START=false` the seed is skipped too. A database error during the seed stops the container like a migration error. See [DEVELOPMENT.md](DEVELOPMENT.md#database-migrations) and [ARCHITECTURE.md](ARCHITECTURE.md#product-policy-versions). +Consent texts are published by migrations, not at startup: migration 00009 publishes the demo texts `c1-2026-10-01` to `c5-2026-10-01` with `kind` `demo`. The database refuses to change or delete a published text, so a new text is a new version in a new migration, and the texts of the actual operator must be published that way before real personal data are accepted. An account with consent history cannot be deleted with a plain `DELETE FROM users` (SQLSTATE 23001 on `consent_records_subject_id_fkey`), and the consent records of a confirmed account cannot be deleted at all (SQLSTATE 23000, `consent_records_retained`); only the unverified account cleanup and the re-registration of an unverified account remove consent records. See [ARCHITECTURE.md](ARCHITECTURE.md#consent-ledger). + The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context. The current `postgres:alpine` volume mounts at `/var/lib/postgresql`; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with `pg_upgrade` or backup/restore. Updating the image alone does not convert the data. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 80e3b64..8ca6d9b 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -220,6 +220,36 @@ Indexes start at 1. Set both variables together; invalid settings, an empty suit CI uses a separate matrix of two integration jobs with `GOFLAGS=-race` and `fail-fast: false`. Every shard must pass before aggregate and deployment smoke succeed. Run `GOFLAGS='-race -shuffle=on' make -C backend test-int` locally to check races and order independence. Shards use their own containers; runners do not share a database or a broker, so a Kafka test passes in whichever shard it lands. CI takes `TEST_SHARD_TOTAL` from the matrix size (`strategy.job-total`), so adding a shard index to the matrix is enough when suite duration warrants more runners; an index above the total fails the job. +## Consent ledger tests + +Unit tests (`make -C backend test`) cover the ledger rules without a database: + +- `internal/domain/` (`consent_test.go`): only `c1` to `c5` are purposes and only C4 is organization scoped; a text version follows the contract pattern of 1 to 64 characters; a text hash must be 32 bytes and not all zero; a stored text whose body no longer matches its hash, a C4 text without the `{organization}` placeholder, and another text with it are refused; the rendered C4 text hashes differently per organization and from its template, and an empty, padded, or multi-line organization name is refused. `NewConsentGrant` refuses C4, an empty or malformed version, a missing hash, subject, or time, and a source that the purpose does not allow; `NewContactConsentGrant` requires the C4 text, the organization with a valid name, a field set, the invitation, and a positive terms version, and hashes the text as shown for that name. Grants and revocations print and log no subject, organization, name, or field. A field set is canonical in any input order and refuses empty, repeated, unknown, and more than four fields. `RestoreConsentRecord` refuses what the database refuses, and a record prints and logs only its ID, purpose, and state. +- `internal/adapter/secondary/postgres/` (`consents_test.go`): ledger constraint errors map to their sentinels by SQLSTATE and constraint name without the row detail, the restricting consent key in the cleanup maps to `ErrTransactionConflict`, invalid input fails before any statement, every generated row type converts to one record row, and the stored field set keeps the order the database accepts. +- `internal/adapter/primary/http/` (`router_test.go`): `ListMyConsents` answers 501 after validation for a session and 400 with the query pointer for an unknown state, a limit over 100, and a malformed cursor; under `DenyAllSecurity` it answers 401 with or without a cookie and with a `subject_id` parameter; the DTOs carry no hash, subject, or contact field, the parameters are only the state and the page, and the contract example decodes and validates. +- `frontend/src/shared/api/consent-contract.test.ts`: the generated Zod schemas accept a C4 record with its scope and a revoked unscoped record, refuse an unknown purpose, state, or source, an empty or malformed version, an empty or oversized field set, an unknown contact kind, and a terms version below 1, require every nullable field, and drop a hash or subject; the operation takes only the state and page parameters. + +`TestConsentLedger` in `backend/integration_test/consent_ledger_test.go` uses `bootstrap(t, postgresService)` with the migrated schema, publishes a second C1 text the way a migration would, and truncates the ledger between cases: + +- The migration publishes one demo text per purpose with a matching hash; the current C1 text depends on the time; an unknown version and a version of another purpose are not found. +- Versions and purposes: C1 at registration, C2, and a newer C1 version give three rows; the older C1 row stays byte-for-byte the same and is listed as `superseded`, the current C1 is the newer one, a repeated grant of the older version returns the existing row without a new one, and revoking C2 leaves C1 unchanged. +- Revocation stamps once: a second revocation finds nothing and keeps the first time, the current C3 is gone, and a new grant is a new row next to the revoked one. Revoking C1 also closes its superseded row. +- C4: the generic grant and a scoped grant without organization and fields are refused by the domain; a grant stores the organization, the canonical fields, the invitation, and the terms version, with the hash of the shown text rather than the template; a repeat returns the same row; an invitation consent of another subject fails with `ErrConsentInvitationTaken`; revoking C4 for organization A leaves organization B, and a revoked invitation consent never comes back. +- Repository validation: an unknown subject, an empty or malformed version, an empty hash, an invented version, a version of another purpose, a hash of another text, and a grant before publication are refused and store nothing. Another subject neither sees nor revokes the owner's consent. +- Database constraints through raw SQL: an empty version, an empty or short hash, C4 without a scope or with an empty, repeated, or unknown field, C2 with a scope or from the registration, a revocation without a source, and a hash of another text are refused by name; an update of a granted row, a revocation that also moves the grant, a second revocation, an update or delete of a published text, and a delete of an account with consent history are refused. +- Read model: pages of three return exactly the owner's four records newest first and never the other subject's; the state filter returns the active and the revoked records. +- Business transaction: a C4 grant rolls back with a failing acceptance, a failing statement after the grant rolls back the whole transaction, and a committed acceptance is visible after the commit and to its own transaction before it. +- The unverified account cleanup deletes the stale account with its C1 row and keeps the verified account and its record. +- C4 snapshot: raw rows whose hash belongs to another organization name, to another name than the stored one, or to the template are refused (`consent_records_c4_text_hash`), C4 without a name and C1 with one are refused (`consent_records_c4_scope`); after a rename, two acceptances keep their own names, and each hash still proves the text shown with its snapshot. +- A revocation dated an hour before the grant is stamped at the grant time. +- Deleting a consent row of a confirmed account is refused (`consent_records_retained`); a row of an unconfirmed account can be deleted. +- Re-registration: `UpdateRegistration` and a new C1 grant in one transaction leave only the new C1; a stale re-registration and an attempt on a verified account change and delete nothing. +- Eight concurrent grants of one version on their own connections store one record, and all of them return it with exactly one `created`. +- Twenty rounds of a grant racing a revocation return no error other than `ErrTransactionConflict` and never leave more than one unrevoked record of the version. +- With only the consent row of a stale account locked, the cleanup on a session with a 200 ms lock timeout skips the account without waiting, and deletes it after the lock is gone. + +`TestPostgresMigrations` rolls migration 00009 back with the others and checks that no table or function remains. The integration tests of identity, mail delivery, and mail quotas name `consent_records` in their TRUNCATE of `users`. The suite does not cover the grant and revocation usecases or the HTTP handler, and the cleanup race that ends in SQLSTATE 23001 is covered only by the unit test of its mapping, because its window cannot be reproduced deterministically. + ## Future software validation Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index ed28ff0..0686d6a 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -416,7 +416,7 @@ backend/ cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку config/ общая конфигурация runtime internal/ - domain/ плоский пакет; DomainEvent, типы identity, продуктовая политика + domain/ плоский пакет; DomainEvent, типы identity, журнал согласий, продуктовая политика usecase/health/ operational readiness usecase port/inbound/ inbound границы readiness и обработчиков событий usecase/identity/ проверка пароля до хеширования (Credentials) @@ -424,7 +424,7 @@ backend/ usecase/files/ общий закрытый файловый слой: политики, непрозрачные ключи, лимиты потока, контрольные суммы usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления - port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, политики, хеширования паролей и почты + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, политики, хеширования паролей и почты adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -437,7 +437,7 @@ backend/ mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend ml/api/ generated client из backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity и политики, health check + postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity, журнала согласий и политики, health check postgres/sqlc/ generated SQL adapter redis/ адаптер кеша и проверка Redis seaweedfs/ S3-адаптер и проверка bucket @@ -447,12 +447,12 @@ backend/ worker/jobrunner/ runtime заданий по сроку: захват под lease, выполнение вместе с завершением, повторы, освобождение и остановка worker/retry/ backoff с jitter и ожидание с учетом context, общие для workers bootstrap/ конфигурация, wiring, lifecycle, shutdown - db/ встроенные миграции и SQL-запросы; таблицы outbox, identity, политики, обработчиков событий, доставок, квот почты и заданий по сроку + db/ встроенные миграции и SQL-запросы; таблицы outbox, identity, политики, обработчиков событий, доставок, квот почты, заданий по сроку и журнала согласий codegen/ конфигурация ogen и sqlc pkg/testutil/ fake clock приложения, общий для тестов ``` -Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`. +Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Типы журнала согласий лежат в `consent.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`. `domain/`, продуктовые `usecase/`, адаптеры SMTP и FSP, а также продуктовые задания worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. @@ -556,7 +556,7 @@ contact_grant относится к паре кандидат-компания - `users`: UUIDv7 `id`; `email` - форма для доставки (ASCII без пробелов по краям, регистр как при вводе, возвращается в `Account.email`), и `email_normalized` - уникальный ключ сравнения (тот же адрес, в котором A-Z переведены в нижний регистр); `password_hash` - строка PHC Argon2id v19; `scenario` и `onboarding_step` с CHECK, что шаг относится к сценарию; nullable `email_verified_at`; `registration_version`; `last_registered_at` с частичным индексом по неподтвержденным аккаунтам для запланированной очистки через 7 дней; оптимистичная `version`; `created_at` и `updated_at`. Форма для доставки хранится, потому что RFC 5321 допускает local part с учетом регистра: письмо уходит на адрес в введенном виде, а уникальность не учитывает регистр. - `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. CHECK допускает не больше одного из consumed и invalidated. - `sessions`: UUIDv7 `id`, который не покидает сервер, `token_hash` (SHA-256 значения cookie, уникальный), `user_id`, `created_at`, `last_seen_at`, абсолютный `expires_at` и `revoked_at`. IP-адрес и user agent не хранятся. -- Токены и сессии ссылаются на `users` с `ON DELETE CASCADE`. Таблицы согласий, запланированные в TASK-062, могут ссылаться на `users.id` так же. CHECK-ограничения дублируют доменные правила как последнюю защиту: ASCII-адрес и его ключ, формат PHC и времена (подтверждения, погашения, аннулирования и отзыва) не раньше `created_at`. +- Токены и сессии ссылаются на `users` с `ON DELETE CASCADE`. Записи согласий ссылаются на него с `ON DELETE RESTRICT`; см. [Журнал согласий](#журнал-согласий). CHECK-ограничения дублируют доменные правила как последнюю защиту: ASCII-адрес и его ключ, формат PHC и времена (подтверждения, погашения, аннулирования и отзыва) не раньше `created_at`. Решения: @@ -568,11 +568,11 @@ contact_grant относится к паре кандидат-компания Что гарантируют порты: -- `UserRepository.Create` возвращает `ErrEmailTaken` для повторного ключа. `UpdateRegistration` сохраняет результат `domain.User.ReRegister`, только если сохраненная `version` совпадает и email не подтвержден; тот же запрос увеличивает `version` и `registration_version` на единицу, поэтому версию регистрации не выбирает вызывающий код. `MarkEmailVerified` применяется только к неподтвержденному аккаунту с указанной версией регистрации. В остальных случаях оба возвращают `ErrUserVersionConflict`. +- `UserRepository.Create` возвращает `ErrEmailTaken` для повторного ключа. `UpdateRegistration` сохраняет результат `domain.User.ReRegister`, только если сохраненная `version` совпадает и email не подтвержден; тот же запрос увеличивает `version` и `registration_version` на единицу, поэтому версию регистрации не выбирает вызывающий код, и удаляет регистрационное C1 прежнего регистранта (см. [Журнал согласий](#журнал-согласий)). `MarkEmailVerified` применяется только к неподтвержденному аккаунту с указанной версией регистрации. В остальных случаях оба возвращают `ErrUserVersionConflict`. - `EmailTokenRepository.Consume` - один `UPDATE ... RETURNING`, который требует непогашенный, неаннулированный и неистекший токен. Параллельные вызовы ждут в очереди на блокировку строки токена; при READ COMMITTED каждый ожидающий заново проверяет строку после завершения владельца блокировки, поэтому успешен ровно один, а если владелец откатился, ожидающий еще может погасить токен. Неудача сообщается как `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (заменен или выдан для более ранней версии регистрации) или `ErrEmailTokenExpired`. `InvalidateActive` помечает все прежние токены пользователя с этим назначением. - Consume сравнивает версию регистрации токена с аккаунтом только в том виде, в каком его прочитал запрос, без блокировки, поэтому не видит повторную регистрацию, зафиксированную сразу после него. Привязка токена к текущей регистрации поэтому соблюдается, только если подтверждение вызывает `MarkEmailVerified(token.UserID, token.RegistrationVersion)` в той же транзакции и откатывает ее при `ErrUserVersionConflict`; откат возвращает и токен, который затем считается замененным. Usecase подтверждения (TASK-054) переводит этот исход в `verification_token_invalid`. - `SessionRepository.FindActive` и `Touch` получают таймаут простоя от вызывающего кода и принимают только неотозванную сессию до ее абсолютного срока и в пределах таймаута простоя. `Touch` записывает `last_seen_at`, только если сохраненное значение старше более чем на минуту, поэтому частые запросы не переписывают строку, а таймаут простоя может завершить сессию на минуту раньше; `Touch` не сдвигает `last_seen_at` назад и не возобновляет завершенную сессию. `Revoke` и `RevokeAllForUser` устанавливают `revoked_at`. -- `DeleteUnverifiedRegisteredBefore` удаляет одну пачку неподтвержденных аккаунтов, начиная со старых, и никогда не ждет блокировку. Он блокирует аккаунты-кандидаты, их токены, сессии, запросы писем и доставки писем через `FOR UPDATE SKIP LOCKED` и пропускает каждый аккаунт, у которого строка аккаунта или любая строка токена, сессии, запроса письма или доставки заблокирована другой транзакцией, например повторной регистрацией, повторной отправкой, подтверждением, обработчиком доставки или worker доставки; пропущенные аккаунты остаются до следующего запуска. Запросы писем, доставки и попытки удаляются вместе с аккаунтом каскадно. +- `DeleteUnverifiedRegisteredBefore` удаляет одну пачку неподтвержденных аккаунтов, начиная со старых, и никогда не ждет блокировку. Он блокирует аккаунты-кандидаты, их токены, сессии, запросы писем, доставки писем и записи согласий через `FOR UPDATE SKIP LOCKED` и пропускает каждый аккаунт, у которого строка аккаунта или любая строка токена, сессии, запроса письма, доставки или согласия заблокирована другой транзакцией, например повторной регистрацией, повторной отправкой, подтверждением, обработчиком доставки или worker доставки; пропущенные аккаунты остаются до следующего запуска. Запросы писем, доставки и попытки удаляются вместе с аккаунтом каскадно; записи согласий, которые запрещают удаление аккаунта, удаляются явно в том же запросе. - `postgres.IdentityStore` выполняет те же репозитории вне транзакции. При вызове с контекстом из callback `Transactor` он возвращает `ErrNestedTransaction`, а не фиксирует изменения через отдельное соединение. - Нарушения уникальности и внешних ключей переводятся в `ErrEmailTaken`, `ErrTokenHashConflict` и `ErrUserNotFound` по SQLSTATE и имени ограничения, а не по тексту ошибки. - Порядок блокировок: операция, которая меняет и аккаунт, и его токены, сначала блокирует токены. Подтверждение гасит токен, а затем подтверждает аккаунт, поэтому повторная регистрация или повторная отправка вызывает `InvalidateActive` до обновления аккаунта или вставки токена; обратный порядок может привести к взаимной блокировке. Единственное исключение - очистка: она блокирует аккаунт раньше токенов и сессий, и это безопасно, потому что каждая из этих блокировок берется с SKIP LOCKED и никогда не ждет. Если взаимная блокировка (SQLSTATE 40P01) или ошибка сериализации (40001) все же случится, `Transactor.WithinTransaction` и репозитории identity сообщают ее как `outbound.ErrTransactionConflict`; ничего не зафиксировано, и usecase или job может повторить всю операцию с паузой, оставаясь идемпотентным. @@ -590,6 +590,36 @@ contact_grant относится к паре кандидат-компания - `identity.Credentials.HashNewPassword` проверяет новый пароль и только потом хеширует его; регистрация будет вызывать его в каждой ветке до поиска email. - Ошибки и логи никогда не содержат пароль или хеш. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken` и `domain.EmailAddress` скрывают значение в выводе `fmt`, `slog` и JSON и хранят его за указателем, поэтому при печати внешней структуры, даже через неэкспортируемое поле, виден только адрес. +### Журнал согласий + +Реализованы хранение, порты и контракт чтения (TASK-062): миграция `backend/db/migrations/00009_create_consent_ledger.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/consents.go` и `ListMyConsents` в публичном контракте ([api/README.md](../../api/README.md#согласия)). Выдача C1-C3 и C5 с проверкой актуальной версии (TASK-063), отзыв с последствиями и HTTP-обработчик (TASK-064), C1 в транзакции регистрации (TASK-053) и C4 при принятии приглашения (TASK-201) запланированы; ни один usecase пока не пишет в журнал. + +Согласия C1-C5 из PRD FR01 - независимые цели: выдача или отзыв одной цели никогда не меняет другую. + +`consent_texts` хранит опубликованные тексты: `purpose`, `version` (`ConsentTextVersion` контракта), точный `body`, `body_sha256`, который CHECK сверяет с текстом, `kind` (`demo` - синтетический текст без юридической проверки, `operator` - текст фактического оператора) и `published_at`. Актуальный текст цели - последняя публикация не позже времени выдачи. Тексты неизменяемы: триггер запрещает UPDATE, DELETE и TRUNCATE (`consent_texts_immutable`), а измененный текст - новая версия. Миграция публикует демо-версию `cN-2026-10-01` каждой цели; тексты оператора появятся новыми версиями в следующей миграции до приема реальных данных (PRD 7.3). Плейсхолдер `{organization}` есть только в тексте C4; его заполняет `ConsentText.RenderForOrganization`. + +`consent_records` - журнал только на добавление. Одна строка на выдачу: UUIDv7 `id`, `subject_id`, `purpose`, `text_version`, `text_hash` (SHA-256 ровно того текста, который видел субъект, 32 байта), `source` (`registration` только для C1, `consent_settings` для C1-C3 и C5, `invitation_acceptance` только для C4), `granted_at` и однократная отметка отзыва `revoked_at` с `revocation_source` (`consent_settings` или `support_request`). У строки C4 есть еще `organization_id`, `organization_name` (название, которое было в показанном тексте, снимок длиной 1-200 символов), канонический `field_set` (от одного до четырех разных значений `ContactFieldKind` по возрастанию байтов), `invitation_id` и `invitation_terms_version`; у остальных целей они обязаны быть NULL (`consent_records_c4_scope`). Метаданные запроса, например IP-адрес или user agent, не хранятся: PRD требует версию, хэш, время, субъекта и событие отзыва, а лишние данные были бы персональными данными без цели. + +Решения: + +- Привязка к тексту. Внешний ключ на (`purpose`, `text_version`) отклоняет версию, которая для цели не публиковалась, а триггер BEFORE INSERT отклоняет версию, опубликованную позже времени выдачи (`consent_records_text_published`). Для C1-C3 и C5 второй внешний ключ через генерируемую колонку требует, чтобы `text_hash` совпадал с хэшем опубликованного текста. Для C4 тот же триггер требует, чтобы `text_hash` был SHA-256 опубликованного текста с подставленным `organization_name` (`consent_records_c4_text_hash`). Домен сам считает этот хэш в `domain.NewContactConsentGrant` из опубликованного `ConsentText` и названия, поэтому вызывающий код не передает байты хэша, а клиент не может придумать ни версию, ни хэш. Сохраненное название - снимок, который доказывает показанный текст; последующее переименование организации его не меняет, и модель чтения возвращает его как `ConsentOrganization.name`. +- История. Единственный UPDATE, который пропускает триггер, - отметка отзыва у неотозванной строки без изменения остальных колонок (`consent_records_immutable`). Новая версия текста - новая строка рядом со старой; выдача после отзыва - новая строка. Состояние (`active`, `superseded`, `revoked`) вычисляют запросы, оно не хранится: среди неотозванных строк субъекта и цели, кроме C4, строка, выданная последней (по `granted_at`, затем по ID), - `active`, остальные - `superseded`, независимо от их версий. Поэтому журнал принимает любую опубликованную версию, а usecase выдачи (TASK-063) обязан проверить, что версия - актуальный текст, до вызова `Grant`. Частичный уникальный индекс оставляет одну неотозванную строку на субъекта, цель и версию, поэтому повторная или конкурентная выдача возвращает существующую запись; уникальный индекс по `invitation_id` оставляет одну строку C4 на приглашение, отозванную или нет, поэтому отозванное C4 не возвращается. +- Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. Последствия отзыва (запрос удаления для C1, закрытие публикации и grants для C2 и C4, ручной путь для C3, остановка импорта для C5) относятся к TASK-064 и не реализованы. +- Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Оставит ли удаленный аккаунт журнал, tombstone или ничего, решают запрос удаления по C1 из TASK-064 и процедура удаления аккаунта, которая его исполняет и пока не имеет задачи в MVP; правило хранения расширит условие удаления своей миграцией. +- Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для TASK-053: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `ConsentLedger().Grant` в той же транзакции. +- C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения - доказательства истории публикации из TASK-088, которая обязана хранить их со временем. Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта. +- C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Принятие приглашения (TASK-201) вызывает его в транзакции, которая переводит приглашение в `accepted`, создает grant и пишет событие аудита, поэтому все это фиксируется или откатывается вместе. Повторное принятие получает существующую запись с `created` false и сравнивает ее scope; для приглашения, чье C4 принадлежит другому субъекту, возвращается `ErrConsentInvitationTaken`. +- Гонка очистки. Очистка проверяет строки согласий в снимке своего запроса. Согласие, зафиксированное для аккаунта-кандидата после этого снимка, но до блокировки аккаунта, нарушает ограничивающий внешний ключ в конце запроса (SQLSTATE 23001); адаптер возвращает его как `ErrTransactionConflict`, ничего не удаляется, а следующий запуск видит согласие. +- Ограничение субъектом. Каждое чтение и отзыв принимают субъекта, а операция контракта берет его из сессии, поэтому модель чтения возвращает только собственные записи вызывающего. Ошибки адаптера сохраняют только SQLSTATE и имя ограничения, а `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant` и `ConsentRevocation` не показывают в выводе `fmt` и `slog` субъекта, организацию, название или поля. + +Вопросы для юридической проверки, которые это хранение не решает: удаление C1 никогда не подтвержденных аккаунтов при сроке хранения согласий три года из PRD 7.3; является ли C2 согласием на распространение персональных данных по статье 10.1 152-ФЗ, которое требует отдельного согласия с категориями данных и может потребовать scope полей в записи C2; тексты оператора, которые заменят демо-тексты. + +Что гарантируют порты (`outbound.ConsentRepositories`, доступны в `UnitOfWork` и вне транзакции через `postgres.ConsentStore`): + +- `ConsentTexts().Get` и `Current` читают опубликованные тексты и при каждом чтении проверяют сохраненный хэш. +- `ConsentLedger().Grant` и `GrantContact` возвращают новую запись с `created` true или существующую с `created` false. Неизвестный субъект возвращает `ErrUserNotFound`, неизвестная версия - `ErrConsentTextNotFound`, версия, опубликованная позже, - `ErrConsentTextNotPublished`, хэш, не совпадающий с опубликованным текстом (для C4 - с сохраненным названием), - `ErrConsentTextMismatch`; эти ошибки приходят из базы и прерывают внешнюю транзакцию. Дубликат ее не прерывает. Выдача, чья конфликтующая запись была отозвана между двумя ее запросами, возвращает `ErrTransactionConflict`. +- `Revoke` возвращает строки, на которые поставил отметку. `Current` возвращает новейшую неотозванную запись C1-C3 или C5 либо `ErrConsentNotFound`; `CurrentContact` возвращает неотозванные записи C4 одной организации. `List` выдает журнал субъекта страницами от новых к старым, при необходимости по состоянию. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index bd8d98a..e7d7539 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -15,6 +15,8 @@ До открытия listeners backend применяет встроенные в бинарник миграции базы данных; ошибка миграции останавливает контейнер. Compose не передает `DATABASE_MIGRATE_ON_START`, поэтому развернутый backend всегда мигрирует при старте, и роли PostgreSQL из `DATABASE_URL` нужны права DDL на схему приложения. Этот флаг - опция локальной разработки; отдельная роль миграций с минимальными правами - будущая работа. Сразу после миграций и только когда они выполняются backend заполняет демонстрационную продуктовую политику: если у семейства политики `product` нет ни одной версии, он публикует версию 1 и пишет в лог `demo product policy published`, иначе пишет, что заполнение пропущено, и ничего не меняет. При `DATABASE_MIGRATE_ON_START=false` заполнение тоже пропускается. Ошибка базы данных при заполнении останавливает контейнер так же, как ошибка миграции. См. [DEVELOPMENT.md](DEVELOPMENT.md#миграции-базы-данных) и [ARCHITECTURE.md](ARCHITECTURE.md#версии-продуктовой-политики). +Тексты согласий публикуют миграции, а не старт backend: миграция 00009 публикует демо-тексты `c1-2026-10-01`-`c5-2026-10-01` с `kind` `demo`. База запрещает менять или удалять опубликованный текст, поэтому новый текст - новая версия в новой миграции, и так же до приема реальных персональных данных должны быть опубликованы тексты фактического оператора. Аккаунт с историей согласий нельзя удалить простым `DELETE FROM users` (SQLSTATE 23001 на `consent_records_subject_id_fkey`), а записи согласий подтвержденного аккаунта нельзя удалить вовсе (SQLSTATE 23000, `consent_records_retained`); записи согласий удаляют только очистка неподтвержденных аккаунтов и повторная регистрация неподтвержденного аккаунта. См. [ARCHITECTURE.md](ARCHITECTURE.md#журнал-согласий). + Контекст сборки backend - каталог `backend/`, поэтому Docker применяет `backend/.dockerignore`. Локальные инструменты, кеши, файлы окружения и результаты сборки не отправляются в этот build context. Для текущего `postgres:alpine` volume монтируется в `/var/lib/postgresql`; образ размещает данные в подкаталоге своей major-версии. При переходе тега на новую major-версию существующую базу нужно мигрировать через `pg_upgrade` или backup/restore. Обновление образа само по себе не преобразует данные. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 59a2a4f..82e25fa 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -220,6 +220,36 @@ TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int CI запускает отдельную matrix из двух integration jobs с `GOFLAGS=-race` и `fail-fast: false`. Результат всех шардов обязателен для aggregate и deployment smoke. `GOFLAGS='-race -shuffle=on' make -C backend test-int` позволяет локально проверить гонки и независимость порядка. Шарды используют свои контейнеры; общие БД и брокер между runner не создаются, поэтому тест Kafka проходит в любом шарде, куда он попал. CI берет `TEST_SHARD_TOTAL` из размера matrix (`strategy.job-total`), поэтому, когда длительность suite оправдывает дополнительные runner, достаточно добавить индекс шарда в matrix; индекс больше общего числа шардов завершает job ошибкой. +## Тесты журнала согласий + +Unit-тесты (`make -C backend test`) проверяют правила журнала без базы: + +- `internal/domain/` (`consent_test.go`): целями считаются только `c1`-`c5`, и только C4 привязано к организации; версия текста следует шаблону контракта из 1-64 символов; хэш текста обязан иметь 32 байта и не быть нулевым; отклоняются сохраненный текст, который больше не совпадает со своим хэшем, текст C4 без плейсхолдера `{organization}` и другой текст с ним; показанный текст C4 дает разный хэш для разных организаций и отличается от хэша шаблона, а пустое, окруженное пробелами или многострочное название организации отклоняется. `NewConsentGrant` отклоняет C4, пустую или неверную версию, отсутствие хэша, субъекта или времени и источник, который цель не допускает; `NewContactConsentGrant` требует текст C4, организацию с допустимым названием, набор полей, приглашение и положительную версию условий и хэширует текст в том виде, в каком он показан с этим названием. Выдачи и отзывы не выводят в печать и логи субъекта, организацию, название или поля. Набор полей каноничен при любом порядке входа и отклоняет пустой, повторный, неизвестный набор и больше четырех полей. `RestoreConsentRecord` отклоняет то же, что отклоняет база, а запись в выводе и логах показывает только ID, цель и состояние. +- `internal/adapter/secondary/postgres/` (`consents_test.go`): ошибки ограничений журнала превращаются в sentinel-ошибки по SQLSTATE и имени ограничения без деталей строки, ограничивающий ключ согласий в очистке превращается в `ErrTransactionConflict`, неверный вход отклоняется до запросов, каждый сгенерированный тип строки приводится к одной структуре записи, а сохраняемый набор полей идет в порядке, который принимает база. +- `internal/adapter/primary/http/` (`router_test.go`): `ListMyConsents` с сессией после валидации отвечает 501, а на неизвестное состояние, limit больше 100 и неверный cursor - 400 с указателем на параметр запроса; при `DenyAllSecurity` отвечает 401 с cookie, без нее и с параметром `subject_id`; DTO не содержат хэша, субъекта или контактов, параметры - только состояние и страница, а пример контракта декодируется и проходит валидацию. +- `frontend/src/shared/api/consent-contract.test.ts`: сгенерированные Zod-схемы принимают запись C4 со scope и отозванную запись без scope, отклоняют неизвестную цель, состояние или источник, пустую или неверную версию, пустой или слишком большой набор полей, неизвестный вид контакта и версию условий меньше 1, требуют каждое nullable-поле и отбрасывают хэш или субъекта; операция принимает только состояние и параметры страницы. + +`TestConsentLedger` в `backend/integration_test/consent_ledger_test.go` использует `bootstrap(t, postgresService)` с примененными миграциями, публикует второй текст C1 так, как это сделала бы миграция, и очищает журнал между случаями: + +- Миграция публикует по одному демо-тексту на цель с совпадающим хэшем; актуальный текст C1 зависит от времени; неизвестная версия и версия другой цели не находятся. +- Версии и цели: C1 при регистрации, C2 и новая версия C1 дают три строки; старая строка C1 остается побайтно прежней и показывается как `superseded`, актуальным C1 становится новая версия, повторная выдача старой версии возвращает существующую строку без новой, а отзыв C2 не меняет C1. +- Отзыв ставится один раз: повторный отзыв ничего не находит и сохраняет первое время, актуального C3 больше нет, а новая выдача - новая строка рядом с отозванной. Отзыв C1 закрывает и его строку `superseded`. +- C4: домен отклоняет общую выдачу и scoped-выдачу без организации и полей; выдача сохраняет организацию, канонический набор полей, приглашение и версию условий с хэшем показанного текста, а не шаблона; повтор возвращает ту же строку; согласие по приглашению другого субъекта дает `ErrConsentInvitationTaken`; отзыв C4 для организации A не затрагивает организацию B, а отозванное согласие по приглашению не возвращается. +- Проверки repository: неизвестный субъект, пустая или неверная версия, пустой хэш, придуманная версия, версия другой цели, хэш другого текста и выдача до публикации отклоняются и ничего не сохраняют. Другой субъект не видит и не отзывает согласие владельца. +- Ограничения базы через прямой SQL: пустая версия, пустой или короткий хэш, C4 без scope или с пустым, повторным или неизвестным полем, C2 со scope или из регистрации, отзыв без источника и хэш другого текста отклоняются с именем ограничения; изменение выданной строки, отзыв с одновременным сдвигом выдачи, повторная отметка отзыва, изменение или удаление опубликованного текста и удаление аккаунта с историей согласий отклоняются. +- Модель чтения: страницы по три записи возвращают ровно четыре записи владельца от новых к старым и никогда не возвращают записи другого субъекта; фильтр состояния возвращает активные и отозванные записи. +- Бизнес-транзакция: выдача C4 откатывается вместе с упавшим принятием, ошибка запроса после выдачи откатывает всю транзакцию, а зафиксированное принятие видно после фиксации и в своей транзакции до нее. +- Очистка неподтвержденных аккаунтов удаляет устаревший аккаунт вместе со строкой C1 и сохраняет подтвержденный аккаунт и его запись. +- Снимок C4: строки, чей хэш относится к другому названию организации, к названию, отличному от сохраненного, или к шаблону, отклоняются (`consent_records_c4_text_hash`), C4 без названия и C1 с названием отклоняются (`consent_records_c4_scope`); после переименования два принятия сохраняют свои названия, и хэш каждого по-прежнему доказывает текст, показанный с его снимком. +- Отзыв со временем на час раньше выдачи записывается временем выдачи. +- Удаление строки согласия подтвержденного аккаунта отклоняется (`consent_records_retained`); строку неподтвержденного аккаунта удалить можно. +- Повторная регистрация: `UpdateRegistration` и новая выдача C1 в одной транзакции оставляют только новое C1; устаревшая повторная регистрация и попытка для подтвержденного аккаунта ничего не меняют и не удаляют. +- Восемь одновременных выдач одной версии на своих соединениях сохраняют одну запись, и все возвращают ее, причем `created` ровно у одной. +- Двадцать раундов гонки выдачи и отзыва не дают ошибок, кроме `ErrTransactionConflict`, и никогда не оставляют больше одной неотозванной записи версии. +- Когда заблокирована только строка согласия устаревшего аккаунта, очистка в сессии с lock timeout 200 ms пропускает аккаунт без ожидания и удаляет его после снятия блокировки. + +`TestPostgresMigrations` откатывает миграцию 00009 вместе с остальными и проверяет, что таблиц и функций не осталось. Интеграционные тесты identity, доставки и квот почты называют `consent_records` в своем TRUNCATE таблицы `users`. Набор не покрывает usecase выдачи и отзыва и HTTP-обработчик, а гонку очистки с SQLSTATE 23001 покрывает только unit-тест ее преобразования, потому что ее окно нельзя воспроизвести детерминированно. + ## Будущая программная валидация Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером. diff --git a/frontend/src/shared/api/consent-contract.test.ts b/frontend/src/shared/api/consent-contract.test.ts new file mode 100644 index 0000000..e5819e0 --- /dev/null +++ b/frontend/src/shared/api/consent-contract.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; +import { listMyConsents } from "./endpoints/consent/consent"; +import { ConsentRecord, ConsentRecordList, ListMyConsentsParams } from "./schemas"; + +// These tests pin the generated consent ledger contract that the consent +// screen (TASK-065) consumes. They fail when regeneration lets a record lose +// its purpose, text version, state, or revocation, accepts a C4 scope +// without fields, or adds a field that would carry the text hash, another +// subject, or a contact value into the read model. + +const contactConsent = { + id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80", + purpose: "c4", + state: "active", + text_version: "c4-2026-10-01", + source: "invitation_acceptance", + granted_at: "2026-10-06T10:15:00Z", + revoked_at: null, + revocation_source: null, + organization: { id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01", name: "ООО Пример Платежи" }, + fields: ["email"], + invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f", + invitation_terms_version: 3, +} as const; + +const revokedPublication = { + id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60", + purpose: "c2", + state: "revoked", + text_version: "c2-2026-10-01", + source: "consent_settings", + granted_at: "2026-10-02T09:00:00Z", + revoked_at: "2026-10-04T18:30:00Z", + revocation_source: "consent_settings", + organization: null, + fields: null, + invitation_id: null, + invitation_terms_version: null, +} as const; + +const page = { + items: [contactConsent, revokedPublication], + page: { has_more: false, next_cursor: null }, +} as const; + +describe("generated ConsentRecordList", () => { + it("accepts a C4 record with its scope and an unscoped revoked record", () => { + expect(ConsentRecordList.parse(page)).toEqual(page); + }); + + it.each([ + ["an unknown purpose", { purpose: "c6" }, "purpose"], + ["an unknown state", { state: "pending" }, "state"], + ["an empty text version", { text_version: "" }, "text_version"], + ["a text version with a space", { text_version: "c4 2026" }, "text_version"], + ["an unknown source", { source: "import" }, "source"], + ["an empty field set", { fields: [] }, "fields"], + [ + "more than four fields", + { fields: ["email", "phone", "telegram", "full_name", "email"] }, + "fields", + ], + ["a terms version below 1", { invitation_terms_version: 0 }, "invitation_terms_version"], + ])("rejects a record with %s", (_case, change, field) => { + const result = ConsentRecord.safeParse({ ...contactConsent, ...change }); + + expect(result.success).toBe(false); + // A value can break several rules of its field, such as both the + // length and the pattern; no other field is reported. + expect(new Set(result.error?.issues.map((issue) => issue.path.join("/")))).toEqual( + new Set([field]), + ); + }); + + it.each([ + "purpose", + "state", + "text_version", + "granted_at", + "revoked_at", + "revocation_source", + "organization", + "fields", + ] as const)("requires %s, null included where it is nullable", (field) => { + const record: Partial> = { ...revokedPublication }; + delete record[field]; + + expect(ConsentRecord.safeParse(record).success).toBe(false); + }); + + it("rejects an unknown contact kind", () => { + expect(ConsentRecord.safeParse({ ...contactConsent, fields: ["address"] }).success).toBe(false); + }); + + it("drops a text hash or a subject that a response would add", () => { + const parsed = ConsentRecord.parse({ + ...contactConsent, + text_hash: "3c48591d8d098a4538f5e013dfcf406e", + subject_id: "01928f7a-0000-7000-8000-00000000c0de", + email: "candidate@example.com", + }); + + // Generated Zod strips unknown keys; the server never sends them. + expect(parsed).not.toHaveProperty("text_hash"); + expect(parsed).not.toHaveProperty("subject_id"); + expect(parsed).not.toHaveProperty("email"); + }); +}); + +describe("generated ListMyConsentsParams", () => { + it("accepts the state filter and the page parameters", () => { + expect(ListMyConsentsParams.parse({ state: "active", limit: 50 })).toEqual({ + state: "active", + limit: 50, + }); + expect(ListMyConsentsParams.parse({})).toEqual({ limit: 20 }); + }); + + it("rejects an unknown state", () => { + expect(ListMyConsentsParams.safeParse({ state: "granted" }).success).toBe(false); + }); +}); + +type PrivateKey = + | "text_hash" + | "hash" + | "subject_id" + | "user_id" + | "account_id" + | "email" + | "phone" + | "telegram" + | "full_name"; + +it("exposes the read model only for the caller's own consents, without hashes or contacts", () => { + expectTypeOf>().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf< + ("full_name" | "email" | "phone" | "telegram")[] | null + >(); + // The subject comes from the session: the operation takes no account, + // user, or subject parameter. + expectTypeOf().toEqualTypeOf<"state" | "limit" | "cursor">(); + expectTypeOf(listMyConsents).parameter(0).toEqualTypeOf(); + expectTypeOf(listMyConsents).returns.resolves.toEqualTypeOf(); +}); diff --git a/frontend/src/shared/api/endpoints/consent/consent.msw.ts b/frontend/src/shared/api/endpoints/consent/consent.msw.ts new file mode 100644 index 0000000..6f25e51 --- /dev/null +++ b/frontend/src/shared/api/endpoints/consent/consent.msw.ts @@ -0,0 +1,47 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + faker +} from '@faker-js/faker'; + +import { + fakeFromPattern +} from '../../mock-pattern'; + +import { + HttpResponse, + http +} from 'msw'; +import type { + RequestHandlerOptions +} from 'msw'; + +import type { + ConsentOrganization, + ConsentRecordList +} from '../../schemas'; + + +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 getListMyConsentsMockHandler = (overrideResponse?: ConsentRecordList | ((info: Parameters[1]>[0]) => Promise | ConsentRecordList), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/consents', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getListMyConsentsResponseMock(), + { status: 200 + }) + }, options) +} +export const getConsentMock = () => [ + getListMyConsentsMockHandler() +] diff --git a/frontend/src/shared/api/endpoints/consent/consent.ts b/frontend/src/shared/api/endpoints/consent/consent.ts new file mode 100644 index 0000000..7bf0e19 --- /dev/null +++ b/frontend/src/shared/api/endpoints/consent/consent.ts @@ -0,0 +1,166 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + ConsentRecordList, + ListMyConsentsParams, + Problem +} from '../../schemas'; + +import { apiRequest } from '../../client'; +import type { ErrorType } from '../../client'; + + +type SecondParameter unknown> = Parameters[1]; + + + +const withQueryKey = (query: T, queryKey: K): T & { queryKey: K } => { + const result = { queryKey } as T & { queryKey: K }; + for (const key of Object.keys(query)) { + // The explicit queryKey always wins, matching the previous + // `{ ...query, queryKey }` spread where it was set last. + if (key === 'queryKey') continue; + Object.defineProperty(result, key, { + enumerable: true, + configurable: true, + get: () => (query as Record)[key], + }); + } + return result; +}; + +export const getListMyConsentsUrl = (params?: ListMyConsentsParams,) => { + const normalizedParams = new URLSearchParams(); + + Object.entries(params || {}).forEach(([key, value]) => { + + if (value !== undefined) { + normalizedParams.append(key, value === null ? 'null' : String(value)) + } + }); + + const stringifiedParams = normalizedParams.toString(); + + return stringifiedParams.length > 0 ? `/api/v1/me/consents?${stringifiedParams}` : `/api/v1/me/consents` +} + +/** + * Requires the session cookie of a candidate or an employer account. The subject comes from the session, never from a request parameter, so the response holds only the caller's own consents: no request can name another account, and records of other accounts are never listed. Returns a page of the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with cursor pagination. + * + * The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the source, and the grant time; the server also stores the hash of exactly the text the subject saw. A newer text version of the same purpose is a new record, and the earlier one becomes `superseded` without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one organization, once; a later grant is a new record. Purposes are independent. + * + * 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 (TASK-088). + * + * Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 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. + */ +export const listMyConsents = async (params?: ListMyConsentsParams, options?: Parameters[1]): Promise => { + + return apiRequest(getListMyConsentsUrl(params), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getListMyConsentsQueryKey = (params?: ListMyConsentsParams,) => { + return [ + `/api/v1/me/consents`, ...(params ? [params] : []) + ] as const; + } + + +export const getListMyConsentsQueryOptions = >, TError = ErrorType>(params?: ListMyConsentsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListMyConsentsQueryKey(params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listMyConsents(params, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListMyConsentsQueryResult = NonNullable>> +export type ListMyConsentsQueryError = ErrorType + + +export function useListMyConsents>, TError = ErrorType>( + params: undefined | ListMyConsentsParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListMyConsents>, TError = ErrorType>( + params?: ListMyConsentsParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListMyConsents>, TError = ErrorType>( + params?: ListMyConsentsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary List the consents of the current account with their history. + */ + +export function useListMyConsents>, TError = ErrorType>( + params?: ListMyConsentsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListMyConsentsQueryOptions(params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + diff --git a/frontend/src/shared/api/endpoints/index.msw.ts b/frontend/src/shared/api/endpoints/index.msw.ts index 00bf551..9eaea01 100644 --- a/frontend/src/shared/api/endpoints/index.msw.ts +++ b/frontend/src/shared/api/endpoints/index.msw.ts @@ -1,6 +1,7 @@ export { getAssessmentMock } from './assessment/assessment.msw' export { getCandidateMock } from './candidate/candidate.msw' export { getCatalogMock } from './catalog/catalog.msw' +export { getConsentMock } from './consent/consent.msw' export { getHealthMock } from './health/health.msw' export { getIdentityMock } from './identity/identity.msw' export { getInvitationMock } from './invitation/invitation.msw' diff --git a/frontend/src/shared/api/endpoints/index.ts b/frontend/src/shared/api/endpoints/index.ts index 3a78856..33e2a85 100644 --- a/frontend/src/shared/api/endpoints/index.ts +++ b/frontend/src/shared/api/endpoints/index.ts @@ -1,6 +1,7 @@ export * from './assessment/assessment'; export * from './candidate/candidate'; export * from './catalog/catalog'; +export * from './consent/consent'; export * from './health/health'; export * from './identity/identity'; export * from './invitation/invitation'; diff --git a/frontend/src/shared/api/schemas/consent/consentOrganization.zod.ts b/frontend/src/shared/api/schemas/consent/consentOrganization.zod.ts new file mode 100644 index 0000000..bad142d --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentOrganization.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const consentOrganizationNameMax = 200; + + +export const ConsentOrganization = zod.object({ + "id": zod.uuid().describe('Identifier of the organization.'), + "name": zod.string().min(1).max(consentOrganizationNameMax).describe('Name of the organization in the consent text at the time of the consent. Plain text; clients show it as text, never as HTML.') +}).describe('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 current name.') + +export type ConsentOrganization = zod.input; +export type ConsentOrganizationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/consentPurposeCode.zod.ts b/frontend/src/shared/api/schemas/consent/consentPurposeCode.zod.ts new file mode 100644 index 0000000..485a117 --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentPurposeCode.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 ConsentPurposeCode = 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 (TASK-088), 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.') + +export type ConsentPurposeCode = zod.input; +export type ConsentPurposeCodeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/consentRecord.zod.ts b/frontend/src/shared/api/schemas/consent/consentRecord.zod.ts new file mode 100644 index 0000000..bb6ba42 --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentRecord.zod.ts @@ -0,0 +1,38 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const consentRecordTextVersionOneMax = 64; + + +export const consentRecordTextVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const consentRecordOrganizationOneNameMax = 200; + +export const consentRecordFieldsMax = 4; + + + +export const ConsentRecord = zod.object({ + "id": zod.uuid().describe('Identifier of the record.'), + "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 (TASK-088), 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.'), + "state": zod.enum(['active', 'superseded', 'revoked']).describe('State of a consent record, computed from the ledger.\n\n- active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation.\n- superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4.\n- revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it.'), + "text_version": zod.string().min(1).max(consentRecordTextVersionOneMax).regex(consentRecordTextVersionOneRegExp).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.').describe('Version of the consent text that the subject accepted.'), + "source": zod.enum(['registration', 'consent_settings', 'invitation_acceptance']).describe('Where the subject gave the consent.\n\n- registration: the c1 acceptance of RegisterAccount.\n- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064).\n- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.\n\nA c4 given when sending an application (PRD Q9) is planned as an additional value.'), + "granted_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.'), + "revoked_at": zod.union([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.'),zod.null()]).describe('Moment of the revocation, or null unless `state` is `revoked`.'), + "revocation_source": zod.union([zod.enum(['consent_settings', 'support_request']).describe('Who recorded a revocation.\n\n- consent_settings: the subject revoked the consent in the product.\n- support_request: an operator recorded a revocation that the subject requested through support.'),zod.null()]).describe('Who recorded the revocation, or null unless `state` is `revoked`.'), + "organization": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of the organization.'), + "name": zod.string().min(1).max(consentRecordOrganizationOneNameMax).describe('Name of the organization in the consent text at the time of the consent. Plain text; clients show it as text, never as HTML.') +}).describe('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 current name.'),zod.null()]).describe('Organization that a c4 consent allows to read the fields, with the name the consent text showed, or null for every other purpose.'), + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('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.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(consentRecordFieldsMax).nullable().describe('Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies another.'), + "invitation_id": zod.uuid().nullable().describe('Invitation whose acceptance gave a c4 consent, or null for every other purpose.'), + "invitation_terms_version": zod.union([zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.'),zod.null()]).describe('Terms version that the acceptance accepted, or null for every other purpose.') +}).describe('One record of the consent ledger as its subject reads it: the purpose, the text version the subject accepted, where and when the consent was given, its state, and the revocation. A c4 record also names the organization, the contact fields, and the invitation with its terms version; these fields are null for every other purpose. The server also stores the SHA-256 hash of exactly the text the subject saw, which a client never sends or receives.') + +export type ConsentRecord = zod.input; +export type ConsentRecordOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/consentRecordList.zod.ts b/frontend/src/shared/api/schemas/consent/consentRecordList.zod.ts new file mode 100644 index 0000000..d34a9bc --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentRecordList.zod.ts @@ -0,0 +1,50 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const consentRecordListItemsItemTextVersionOneMax = 64; + + +export const consentRecordListItemsItemTextVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const consentRecordListItemsItemOrganizationOneNameMax = 200; + +export const consentRecordListItemsItemFieldsMax = 4; + + +export const consentRecordListItemsMax = 100; + +export const consentRecordListPageNextCursorMax = 512; + + +export const consentRecordListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const ConsentRecordList = zod.object({ + "items": zod.array(zod.object({ + "id": zod.uuid().describe('Identifier of the record.'), + "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 (TASK-088), 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.'), + "state": zod.enum(['active', 'superseded', 'revoked']).describe('State of a consent record, computed from the ledger.\n\n- active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation.\n- superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4.\n- revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it.'), + "text_version": zod.string().min(1).max(consentRecordListItemsItemTextVersionOneMax).regex(consentRecordListItemsItemTextVersionOneRegExp).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.').describe('Version of the consent text that the subject accepted.'), + "source": zod.enum(['registration', 'consent_settings', 'invitation_acceptance']).describe('Where the subject gave the consent.\n\n- registration: the c1 acceptance of RegisterAccount.\n- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064).\n- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.\n\nA c4 given when sending an application (PRD Q9) is planned as an additional value.'), + "granted_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.'), + "revoked_at": zod.union([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.'),zod.null()]).describe('Moment of the revocation, or null unless `state` is `revoked`.'), + "revocation_source": zod.union([zod.enum(['consent_settings', 'support_request']).describe('Who recorded a revocation.\n\n- consent_settings: the subject revoked the consent in the product.\n- support_request: an operator recorded a revocation that the subject requested through support.'),zod.null()]).describe('Who recorded the revocation, or null unless `state` is `revoked`.'), + "organization": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of the organization.'), + "name": zod.string().min(1).max(consentRecordListItemsItemOrganizationOneNameMax).describe('Name of the organization in the consent text at the time of the consent. Plain text; clients show it as text, never as HTML.') +}).describe('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 current name.'),zod.null()]).describe('Organization that a c4 consent allows to read the fields, with the name the consent text showed, or null for every other purpose.'), + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('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.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(consentRecordListItemsItemFieldsMax).nullable().describe('Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies another.'), + "invitation_id": zod.uuid().nullable().describe('Invitation whose acceptance gave a c4 consent, or null for every other purpose.'), + "invitation_terms_version": zod.union([zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.'),zod.null()]).describe('Terms version that the acceptance accepted, or null for every other purpose.') +}).describe('One record of the consent ledger as its subject reads it: the purpose, the text version the subject accepted, where and when the consent was given, its state, and the revocation. A c4 record also names the organization, the contact fields, and the invitation with its terms version; these fields are null for every other purpose. The server also stores the SHA-256 hash of exactly the text the subject saw, which a client never sends or receives.')).max(consentRecordListItemsMax).describe('Records of the page.'), + "page": zod.object({ + "has_more": zod.boolean().describe('Whether another page follows this one.'), + "next_cursor": zod.string().min(1).max(consentRecordListPageNextCursorMax).regex(consentRecordListPageNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.') +}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.') +}).describe('One page of the consent ledger of the current account, newest grant first.') + +export type ConsentRecordList = zod.input; +export type ConsentRecordListOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/consentRevocationSource.zod.ts b/frontend/src/shared/api/schemas/consent/consentRevocationSource.zod.ts new file mode 100644 index 0000000..b0d0b87 --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentRevocationSource.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 ConsentRevocationSource = zod.enum(['consent_settings', 'support_request']).describe('Who recorded a revocation.\n\n- consent_settings: the subject revoked the consent in the product.\n- support_request: an operator recorded a revocation that the subject requested through support.') + +export type ConsentRevocationSource = zod.input; +export type ConsentRevocationSourceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/consentSource.zod.ts b/frontend/src/shared/api/schemas/consent/consentSource.zod.ts new file mode 100644 index 0000000..eeed5a8 --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentSource.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 ConsentSource = zod.enum(['registration', 'consent_settings', 'invitation_acceptance']).describe('Where the subject gave the consent.\n\n- registration: the c1 acceptance of RegisterAccount.\n- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064).\n- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.\n\nA c4 given when sending an application (PRD Q9) is planned as an additional value.') + +export type ConsentSource = zod.input; +export type ConsentSourceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/consentState.zod.ts b/frontend/src/shared/api/schemas/consent/consentState.zod.ts new file mode 100644 index 0000000..b3be8de --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/consentState.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 ConsentState = zod.enum(['active', 'superseded', 'revoked']).describe('State of a consent record, computed from the ledger.\n\n- active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation.\n- superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4.\n- revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it.') + +export type ConsentState = zod.input; +export type ConsentStateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/index.ts b/frontend/src/shared/api/schemas/consent/index.ts new file mode 100644 index 0000000..4cf480d --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/index.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ + +export * from './consentOrganization.zod'; +export * from './consentPurposeCode.zod'; +export * from './consentRecord.zod'; +export * from './consentRecordList.zod'; +export * from './consentRevocationSource.zod'; +export * from './consentSource.zod'; +export * from './consentState.zod'; +export * from './listMyConsentsParams.zod'; diff --git a/frontend/src/shared/api/schemas/consent/listMyConsentsParams.zod.ts b/frontend/src/shared/api/schemas/consent/listMyConsentsParams.zod.ts new file mode 100644 index 0000000..32b613a --- /dev/null +++ b/frontend/src/shared/api/schemas/consent/listMyConsentsParams.zod.ts @@ -0,0 +1,24 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const listMyConsentsParamsLimitDefault = 20; +export const listMyConsentsParamsLimitMax = 100; + +export const listMyConsentsParamsCursorMax = 512; + + +export const listMyConsentsParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const ListMyConsentsParams = zod.object({ + "state": zod.enum(['active', 'superseded', 'revoked']).exactOptional().describe('State of a consent record, computed from the ledger.\n\n- active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation.\n- superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4.\n- revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it.'), + "limit": zod.int().min(1).max(listMyConsentsParamsLimitMax).default(listMyConsentsParamsLimitDefault), + "cursor": zod.string().min(1).max(listMyConsentsParamsCursorMax).regex(listMyConsentsParamsCursorRegExp).exactOptional() +}) + +export type ListMyConsentsParams = zod.input; +export type ListMyConsentsParamsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactFieldKind.zod.ts b/frontend/src/shared/api/schemas/contactFieldKind.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/invitation/contactFieldKind.zod.ts rename to frontend/src/shared/api/schemas/contactFieldKind.zod.ts diff --git a/frontend/src/shared/api/schemas/index.ts b/frontend/src/shared/api/schemas/index.ts index c0f63e4..f139b5c 100644 --- a/frontend/src/shared/api/schemas/index.ts +++ b/frontend/src/shared/api/schemas/index.ts @@ -6,9 +6,11 @@ */ export * from './consentTextVersion.zod'; +export * from './contactFieldKind.zod'; export * from './currencyCode.zod'; export * from './emailAddress.zod'; export * from './gradeCode.zod'; +export * from './invitationTermsVersion.zod'; export * from './needLocationName.zod'; export * from './needTaskText.zod'; export * from './needVersion.zod'; @@ -29,6 +31,7 @@ export * from './workFormat.zod'; export * from './assessment'; export * from './candidate'; export * from './catalog'; +export * from './consent'; export * from './health'; export * from './identity'; export * from './invitation'; diff --git a/frontend/src/shared/api/schemas/invitation/index.ts b/frontend/src/shared/api/schemas/invitation/index.ts index 5ac0706..05e91e8 100644 --- a/frontend/src/shared/api/schemas/invitation/index.ts +++ b/frontend/src/shared/api/schemas/invitation/index.ts @@ -18,7 +18,6 @@ export * from './contactConsentAcceptance.zod'; export * from './contactConsentOffer.zod'; export * from './contactConsentText.zod'; export * from './contactDisclosure.zod'; -export * from './contactFieldKind.zod'; export * from './contactFullName.zod'; export * from './contactGrant.zod'; export * from './contactGrantState.zod'; @@ -56,7 +55,6 @@ export * from './invitationSalaryRaise.zod'; export * from './invitationState.zod'; export * from './invitationTeamDescription.zod'; export * from './invitationTerms.zod'; -export * from './invitationTermsVersion.zod'; export * from './invitationVersion.zod'; export * from './listMyInvitationsParams.zod'; export * from './listOrganizationInvitationsParams.zod'; diff --git a/frontend/src/shared/api/schemas/invitation/invitationTermsVersion.zod.ts b/frontend/src/shared/api/schemas/invitationTermsVersion.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/invitation/invitationTermsVersion.zod.ts rename to frontend/src/shared/api/schemas/invitationTermsVersion.zod.ts