feat(consent): grant consents through a version-checked usecase

This commit is contained in:
shira committed 2026-10-06 15:12:08 +03:00
1 parent de49f93b0b
commit ea0982a762
8 files changed
+1731 -11

No files matched your search

+20 -3
View File
@@ -421,6 +421,7 @@ backend/
port/inbound/ readiness and event handler input boundaries
usecase/identity/ password validation before hashing (Credentials)
usecase/policy/ publication of policy versions and the demo policy seed
usecase/consent/ granting of consents C1-C3 and C5 and the scoped C4 with the current-text check
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
@@ -592,7 +593,7 @@ Implemented (TASK-052) and tested, but not wired into bootstrap: registration (T
### 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.
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 is implemented as the usecase `consent.Service` (TASK-063, see [Consent usecase](#consent-usecase)). 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 product flow calls the usecase yet.
The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation of one never changes another.
@@ -603,10 +604,10 @@ The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation
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.
- 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 `consent.Service` (TASK-063) checks 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.
- 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 `consent.Service.GrantAtRegistration`, strictly after `UpdateRegistration`, in the same transaction (see [Consent usecase](#consent-usecase)).
- 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.
@@ -620,6 +621,22 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo
- `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.
### Consent usecase
Implemented (TASK-063): `consent.Service` in `backend/internal/usecase/consent/`. It is not wired into bootstrap yet, because no handler or registration flow calls it; the first caller builds it with `consent.NewService(transactor, clock)`, the `Transactor` and the application clock that the other usecases already receive. A nil transactor or clock panics at construction, so a wiring mistake shows at startup and not at the first grant.
- Entry points fix the source. `GrantAtRegistration(ctx, repositories, subjectID, version)` records C1 with the source `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` records C1, C2, C3, or C5 with the source `consent_settings`. Neither takes a source or a time, so a handler cannot read either from the client. `repositories` is an `outbound.ConsentRepositories`: pass the `UnitOfWork` of a business operation and the grant commits or rolls back with it. The registration (TASK-053) creates the account and records C1 in one transaction on the subject ID alone, so no session is needed. `GrantInSettingsInNewTransaction` opens its own transaction for a grant that is not part of another operation, and retries an `ErrTransactionConflict` up to three attempts in total with a short jittered wait (10 ms plus up to 10 ms) between them, which is safe because a repeat is idempotent; the wait ends at once when the context is canceled.
- Re-registration order. For an unverified account that registers again, call `GrantAtRegistration` strictly after `UserRepository.UpdateRegistration` in the same transaction. `UpdateRegistration` deletes the registration C1 of the earlier registrant, and a grant that ran before it would find that record, return it with `Created` false, and leave the account without any C1 once it is deleted. The integration test shows both orders.
- Version check before the email branch. `CheckTextVersion(ctx, repositories, purpose, version)` returns the current text when `version` is current and fails like a grant otherwise, without writing anything. The registration (TASK-053) must call it with C1 and the submitted version before it branches on a new or an existing email; otherwise a stale version would be refused only for new addresses, and the difference would reveal which accounts exist.
- Current text only. A grant reads `ConsentTexts().Current` at the application time and refuses any other version with `*StaleConsentTextError`, which matches `ErrStaleConsentText` and carries the purpose, the requested version, and the current one, so a handler can map it to one problem code and show the new text. An older version, a version that is scheduled but not yet published, and a version that never existed are all stale. The ledger accepts any published version, so this check is what keeps a grant of an outdated text out. The check and the insert are not locked against a publication between them: texts are published by migrations, and a grant that named the current text when it was checked is valid.
- Server time. The input has no time field. The grant uses one reading of the injected clock for the check and for the record time; a client cannot choose the time. The database still refuses a version published after that time.
- Idempotency. A repeat of the same subject, purpose, and current version returns the existing unrevoked record with `Created` false, keeps its first time, stores nothing, and does not abort a surrounding transaction. A grant after a revocation is a new record. A repeat that names an older version after a newer text was published is stale, not a repeat: the subject has to see the new text, and the ledger keeps its one record.
- C4 only through its scope. `GrantInSettings` refuses C4 with `ErrScopedConsentRequired` before it reads anything. `GrantContact(ctx, repositories, input)` is the explicitly scoped operation for the invitation acceptance (TASK-201): the input carries the organization and the name shown, the field set, the invitation, the invitation terms version, and the C4 text version. It checks that the C4 text is current, lets `domain.NewContactConsentGrant` hash the text as shown, and calls `ConsentLedger().GrantContact` in the caller's transaction. A repeat of the same subject and invitation returns the existing record with `Created` false; the caller compares its scope. The text check comes first, so a repeat after a newer C4 text was published is stale; the acceptance that wants to answer such a repeat with the earlier result must find its existing record before it calls.
- C3 may be withheld. The purposes are independent: no grant requires, implies, or changes another, and no code path requires an active C3 for the profile, the manual assessment path, or another function. A subject without C3 has no C3 record, and `Current` returns `ErrConsentNotFound` for it, which is not an error state of the account. Whoever reads C3 (the manual assessment request of TASK-315, the revocation of TASK-064) treats a missing record as "not given" and keeps the manual path open.
- No revocation here. `Revoke` stays on the ledger port, and TASK-064 calls it with the downstream effects and the outbox events in one transaction.
- Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers (TASK-064, TASK-053, TASK-201).
- Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or TASK-064, and neither exists yet.
## 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.
+12 -1
View File
@@ -226,6 +226,7 @@ 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/usecase/consent/` (`service_test.go`, with an in-memory text repository, ledger, transactor, and a controllable clock): a grant of C1, C2, C3, and C5 records the current text version and hash, the source of its entry point (`GrantAtRegistration` fixes C1 and `registration`, `GrantInSettings` fixes `consent_settings`), and the time of the injected clock, never another time; a grant with an older, unknown, or scheduled version fails with `ErrStaleConsentText`, names the current version, and never reaches the ledger; granting version one, publishing version two, and repeating version one is stale and leaves one record; `CheckTextVersion` returns the current text, fails stale for an older, unknown, and scheduled version, refuses an unknown purpose and a malformed version, and never touches the ledger; C4 on the generic path fails with `ErrScopedConsentRequired` before any repository is read; a malformed or empty version, an unknown purpose, and a nil subject are refused; a repeat returns the existing record with `Created` false and its first time, and the ledger keeps one record; failures of the repositories (no published text, unknown subject) keep their sentinel and a missing text is not reported as stale; a subject who withheld C3 has the other purposes with their own records and no C3 record; `GrantContact` records the scope, the source `invitation_acceptance`, and the hash of the text as shown, returns the existing record for a repeat, reports an invitation of another subject as taken, and refuses a stale C4 version, a padded name, and missing fields, organization, invitation, subject, or terms version; `GrantInSettingsInNewTransaction` retries a transaction conflict after a wait, stops after three attempts, does not retry another error or a canceled context, and rolls back a stale grant; `NewService` panics on a nil transactor or clock.
- `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.
@@ -248,7 +249,17 @@ Unit tests (`make -C backend test`) cover the ledger rules without a database:
- 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.
`TestConsentGrants` in `backend/integration_test/consent_usecase_test.go` runs the usecase on the bootstrap database with a fixed application clock, a second C1 text, and a C5 text scheduled after the clock:
- Registration: `UserRepository.Create` and `GrantAtRegistration` of C1 run in one `Transactor` transaction with no session (the sessions table stays empty) and commit one account and one C1 at the application time with the current text version. C2 and C5 follow as separate operations, each with its own active record; C3 is withheld and has no record while the others stand; a C3 granted later and revoked leaves C1, C2, and C5 active.
- Atomicity: a transaction that fails after the account and C1 were written leaves neither, and a grant for a subject without an account fails with `ErrUserNotFound` and stores nothing.
- Idempotency and versions: a repeat in its own transaction and in a business transaction returns the first record and its time and stores no row, and a repeat does not abort the transaction. An outdated C1 version, a scheduled C5 version, and an unknown C3 version fail with a stale error that names the current version and store nothing; the current C1 version goes through and the outdated one stays refused. A grant after a revocation is a new row. Eight concurrent repeats create exactly one row.
- Republication: after C3 version one is granted and version two is published, a repeat of version one is stale, names version two, and leaves one row and the first record as the current C3.
- Re-registration: `UpdateRegistration` followed by `GrantAtRegistration` in one transaction returns `created` true with a new record and leaves exactly one C1. The opposite order is shown as a hazard: the grant finds the earlier registrant's C1 and returns it with `created` false, the update then deletes it, and the account ends with no C1.
- C4: the generic path refuses it and stores nothing; `GrantContact` in a transaction stores the organization, the name, the fields, the invitation, and the source `invitation_acceptance`; a repeat returns the same record, an outdated C4 version is stale, and the C4 does not create a C2.
- Restart: after the pool is closed, a new pool, store, and usecase list the same four records in order with their states, the revocation stamp and source, and the original grant times, and a repeat grant through the new instance stores nothing.
`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 revocation usecase, the HTTP handler, or the call of the consent usecase from registration and the invitation acceptance, 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
+20 -3
View File
@@ -421,6 +421,7 @@ backend/
port/inbound/ inbound границы readiness и обработчиков событий
usecase/identity/ проверка пароля до хеширования (Credentials)
usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики
usecase/consent/ выдача согласий C1-C3 и C5 и C4 со scope с проверкой актуального текста
usecase/files/ общий закрытый файловый слой: политики, непрозрачные ключи, лимиты потока, контрольные суммы
usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки
usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления
@@ -592,7 +593,7 @@ contact_grant относится к паре кандидат-компания
### Журнал согласий
Реализованы хранение, порты и контракт чтения (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 пока не пишет в журнал.
Реализованы хранение, порты и контракт чтения (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 с проверкой актуальной версии реализована как usecase `consent.Service` (TASK-063, см. [Usecase согласий](#usecase-согласий)). Отзыв с последствиями и HTTP-обработчик (TASK-064), C1 в транзакции регистрации (TASK-053) и C4 при принятии приглашения (TASK-201) запланированы; ни один продуктовый поток пока не вызывает usecase.
Согласия C1-C5 из PRD FR01 - независимые цели: выдача или отзыв одной цели никогда не меняет другую.
@@ -603,10 +604,10 @@ contact_grant относится к паре кандидат-компания
Решения:
- Привязка к тексту. Внешний ключ на (`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 не возвращается.
- История. Единственный UPDATE, который пропускает триггер, - отметка отзыва у неотозванной строки без изменения остальных колонок (`consent_records_immutable`). Новая версия текста - новая строка рядом со старой; выдача после отзыва - новая строка. Состояние (`active`, `superseded`, `revoked`) вычисляют запросы, оно не хранится: среди неотозванных строк субъекта и цели, кроме C4, строка, выданная последней (по `granted_at`, затем по ID), - `active`, остальные - `superseded`, независимо от их версий. Поэтому журнал принимает любую опубликованную версию, а usecase выдачи `consent.Service` (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` в той же транзакции.
- Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для TASK-053: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `consent.Service.GrantAtRegistration` строго после `UpdateRegistration` в той же транзакции (см. [Usecase согласий](#usecase-согласий)).
- 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`, ничего не удаляется, а следующий запуск видит согласие.
@@ -620,6 +621,22 @@ contact_grant относится к паре кандидат-компания
- `ConsentLedger().Grant` и `GrantContact` возвращают новую запись с `created` true или существующую с `created` false. Неизвестный субъект возвращает `ErrUserNotFound`, неизвестная версия - `ErrConsentTextNotFound`, версия, опубликованная позже, - `ErrConsentTextNotPublished`, хэш, не совпадающий с опубликованным текстом (для C4 - с сохраненным названием), - `ErrConsentTextMismatch`; эти ошибки приходят из базы и прерывают внешнюю транзакцию. Дубликат ее не прерывает. Выдача, чья конфликтующая запись была отозвана между двумя ее запросами, возвращает `ErrTransactionConflict`.
- `Revoke` возвращает строки, на которые поставил отметку. `Current` возвращает новейшую неотозванную запись C1-C3 или C5 либо `ErrConsentNotFound`; `CurrentContact` возвращает неотозванные записи C4 одной организации. `List` выдает журнал субъекта страницами от новых к старым, при необходимости по состоянию.
### Usecase согласий
Реализовано (TASK-063): `consent.Service` в `backend/internal/usecase/consent/`. В bootstrap он пока не подключен, потому что его не вызывает ни обработчик, ни регистрация; первый вызывающий код создаст его через `consent.NewService(transactor, clock)` с `Transactor` и часами приложения, которые получают остальные usecase. Нулевой transactor или часы вызывают панику при создании, поэтому ошибка сборки видна при старте, а не при первой выдаче.
- Точки входа фиксируют источник. `GrantAtRegistration(ctx, repositories, subjectID, version)` записывает C1 с источником `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` записывает C1, C2, C3 или C5 с источником `consent_settings`. Ни одна не принимает источник или время, поэтому обработчик не может взять их от клиента. `repositories` - это `outbound.ConsentRepositories`: если передать `UnitOfWork` бизнес-операции, выдача фиксируется или откатывается вместе с ней. Регистрация (TASK-053) создает аккаунт и записывает C1 в одной транзакции только по ID субъекта, поэтому сессия не нужна. `GrantInSettingsInNewTransaction` открывает собственную транзакцию для выдачи вне другой операции и повторяет `ErrTransactionConflict` до трех попыток всего с короткой случайной паузой (10 мс плюс до 10 мс) между ними; это безопасно, потому что повтор идемпотентен, а пауза прерывается сразу при отмене контекста.
- Порядок при повторной регистрации. Для неподтвержденного аккаунта, который регистрируется снова, вызывайте `GrantAtRegistration` строго после `UserRepository.UpdateRegistration` в той же транзакции. `UpdateRegistration` удаляет регистрационное C1 прежнего регистранта, а выдача, выполненная до него, нашла бы эту запись, вернула ее с `Created` false и после удаления оставила бы аккаунт без C1. Интеграционный тест показывает оба порядка.
- Проверка версии до ветвления по email. `CheckTextVersion(ctx, repositories, purpose, version)` возвращает актуальный текст, если `version` актуальна, а иначе завершается как выдача, ничего не записывая. Регистрация (TASK-053) обязана вызвать ее с C1 и присланной версией до ветвления на новый или существующий email; иначе устаревшая версия отклонялась бы только для новых адресов, и разница выдала бы, какие аккаунты существуют.
- Только актуальный текст. Выдача читает `ConsentTexts().Current` на время приложения и отклоняет любую другую версию ошибкой `*StaleConsentTextError`, которая совпадает с `ErrStaleConsentText` и содержит цель, запрошенную и актуальную версии, поэтому обработчик может сопоставить ее одному коду problem и показать новый текст. Устаревшая версия, версия, которая запланирована, но еще не опубликована, и версия, которой никогда не было, считаются устаревшими. Журнал принимает любую опубликованную версию, поэтому именно эта проверка не пускает выдачу устаревшего текста. Проверка и вставка не блокируются от публикации между ними: тексты публикуют миграции, а выдача, назвавшая актуальный текст на момент проверки, допустима.
- Серверное время. Во входе нет поля времени. Выдача берет одно чтение внедренных часов для проверки и для времени записи; клиент не выбирает время. База по-прежнему отклоняет версию, опубликованную после этого времени.
- Идемпотентность. Повтор того же субъекта, цели и актуальной версии возвращает существующую неотозванную запись с `Created` false, сохраняет ее первое время, ничего не записывает и не прерывает внешнюю транзакцию. Выдача после отзыва - новая запись. Повтор с более старой версией после публикации нового текста - не повтор, а устаревшая версия: субъект должен увидеть новый текст, а в журнале остается одна запись.
- C4 только через scope. `GrantInSettings` отклоняет C4 ошибкой `ErrScopedConsentRequired`, ничего не прочитав. `GrantContact(ctx, repositories, input)` - явно ограниченная операция для принятия приглашения (TASK-201): вход содержит организацию и показанное название, набор полей, приглашение, версию условий приглашения и версию текста C4. Она проверяет, что текст C4 актуален, поручает `domain.NewContactConsentGrant` посчитать хэш показанного текста и вызывает `ConsentLedger().GrantContact` в транзакции вызывающего кода. Повтор того же субъекта и приглашения возвращает существующую запись с `Created` false; scope сравнивает вызывающий код. Проверка текста идет первой, поэтому повтор после публикации нового текста C4 считается устаревшим; принятие, которое хочет ответить на такой повтор прежним результатом, должно найти свою запись до вызова.
- C3 можно не давать. Цели независимы: ни одна выдача не требует, не подразумевает и не меняет другую, и ни один путь кода не требует активного C3 для профиля, ручного пути оценки или другой функции. У субъекта без C3 нет записи C3, и `Current` возвращает для него `ErrConsentNotFound`; это не ошибочное состояние аккаунта. Код, который читает C3 (запрос ручной оценки TASK-315, отзыв TASK-064), считает отсутствие записи состоянием "не дано" и оставляет ручной путь доступным.
- Отзыва здесь нет. `Revoke` остается на порте журнала, а TASK-064 вызывает его вместе с последующими эффектами и событиями outbox в одной транзакции.
- Ошибки сохраняют идентичность: устаревшая версия, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (у цели нет опубликованного текста), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent` и `domain.ErrInvalidConsentText`. Действия требует `outbound.ErrTransactionConflict`: журнал возвращает его, не прерывая транзакцию, когда запись повтора была отозвана между вставкой и выборкой. Вызывающий код внутри `UnitOfWork` обязан вернуть эту ошибку, откатить транзакцию и повторить всю операцию; `GrantInSettingsInNewTransaction` делает это сам. Сопоставление остальных ошибок с кодами problem - дело обработчиков (TASK-064, TASK-053, TASK-201).
- Демо-тексты требуют проверки перед выпуском. Тексты, которые публикует миграция, имеют вид `demo`: синтетические, без юридической проверки. Usecase не отличает их от текстов оператора, поэтому установка, принимающая реальные данные, записала бы согласие на демо-текст. До приема реальных данных (PRD 7.3) проверка перед выпуском должна убедиться, что актуальный текст каждой цели имеет вид `operator`; владелец - проверка перед выпуском или TASK-064, и ни той, ни другой пока нет.
## Frontend
Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.
+12 -1
View File
@@ -226,6 +226,7 @@ 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/usecase/consent/` (`service_test.go`, с in-memory репозиторием текстов, журналом, transactor и управляемыми часами): выдача C1, C2, C3 и C5 записывает актуальную версию и хэш текста, источник своей точки входа (`GrantAtRegistration` фиксирует C1 и `registration`, `GrantInSettings` фиксирует `consent_settings`) и время внедренных часов, но не любое другое время; выдача со старой, неизвестной или запланированной версией завершается `ErrStaleConsentText`, называет актуальную версию и не доходит до журнала; выдача версии один, публикация версии два и повтор версии один дают устаревшую версию и одну запись; `CheckTextVersion` возвращает актуальный текст, завершается устаревшей версией для старой, неизвестной и запланированной версии, отклоняет неизвестную цель и неверную версию и никогда не обращается к журналу; C4 на общем пути завершается `ErrScopedConsentRequired` до чтения любого репозитория; неверная или пустая версия, неизвестная цель и нулевой субъект отклоняются; повтор возвращает существующую запись с `Created` false и ее первым временем, а в журнале остается одна запись; ошибки репозиториев (нет опубликованного текста, неизвестный субъект) сохраняют свой sentinel, а отсутствие текста не выдается за устаревшую версию; у субъекта, не давшего C3, остальные цели имеют собственные записи, а записи C3 нет; `GrantContact` записывает scope, источник `invitation_acceptance` и хэш показанного текста, возвращает существующую запись при повторе, сообщает, что приглашение занято другим субъектом, и отклоняет устаревшую версию C4, название с пробелами по краям и отсутствие полей, организации, приглашения, субъекта или версии условий; `GrantInSettingsInNewTransaction` повторяет конфликт транзакции после паузы, останавливается после трех попыток, не повторяет другую ошибку и отмененный контекст и откатывает устаревшую выдачу; `NewService` паникует при нулевом transactor или часах.
- `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-поле и отбрасывают хэш или субъекта; операция принимает только состояние и параметры страницы.
@@ -248,7 +249,17 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
- Двадцать раундов гонки выдачи и отзыва не дают ошибок, кроме `ErrTransactionConflict`, и никогда не оставляют больше одной неотозванной записи версии.
- Когда заблокирована только строка согласия устаревшего аккаунта, очистка в сессии с lock timeout 200 ms пропускает аккаунт без ожидания и удаляет его после снятия блокировки.
`TestPostgresMigrations` откатывает миграцию 00009 вместе с остальными и проверяет, что таблиц и функций не осталось. Интеграционные тесты identity, доставки и квот почты называют `consent_records` в своем TRUNCATE таблицы `users`. Набор не покрывает usecase выдачи и отзыва и HTTP-обработчик, а гонку очистки с SQLSTATE 23001 покрывает только unit-тест ее преобразования, потому что ее окно нельзя воспроизвести детерминированно.
`TestConsentGrants` в `backend/integration_test/consent_usecase_test.go` запускает usecase на базе bootstrap с фиксированными часами приложения, вторым текстом C1 и текстом C5, запланированным после часов:
- Регистрация: `UserRepository.Create` и `GrantAtRegistration` для C1 выполняются в одной транзакции `Transactor` без сессии (таблица сессий остается пустой) и фиксируют один аккаунт и одно C1 со временем приложения и актуальной версией текста. C2 и C5 следуют отдельными операциями, у каждой своя активная запись; C3 не дано, записи C3 нет, пока остальные действуют; C3, выданное позже и отозванное, оставляет C1, C2 и C5 активными.
- Атомарность: транзакция, упавшая после записи аккаунта и C1, не оставляет ни того, ни другого, а выдача для субъекта без аккаунта завершается `ErrUserNotFound` и ничего не записывает.
- Идемпотентность и версии: повтор в собственной транзакции и в бизнес-транзакции возвращает первую запись и ее время и не добавляет строк, а бизнес-транзакция не прерывается. Устаревшая версия C1, запланированная версия C5 и неизвестная версия C3 завершаются ошибкой устаревшей версии с названием актуальной и ничего не записывают; актуальная версия C1 проходит, а устаревшая остается отклоненной. Выдача после отзыва - новая строка. Восемь одновременных повторов создают ровно одну строку.
- Повторная публикация: после выдачи версии один C3 и публикации версии два повтор версии один считается устаревшим, называет версию два и оставляет одну строку и первую запись как текущее C3.
- Повторная регистрация: `UpdateRegistration` и затем `GrantAtRegistration` в одной транзакции возвращают `created` true с новой записью и оставляют ровно одно C1. Обратный порядок показан как риск: выдача находит C1 прежнего регистранта и возвращает его с `created` false, затем обновление удаляет его, и аккаунт остается без C1.
- C4: общий путь отклоняет его и ничего не записывает; `GrantContact` в транзакции сохраняет организацию, название, поля, приглашение и источник `invitation_acceptance`; повтор возвращает ту же запись, устаревшая версия C4 отклоняется, а C4 не создает C2.
- Перезапуск: после закрытия pool новый pool, хранилище и usecase перечисляют те же четыре записи по порядку с их состояниями, отметкой и источником отзыва и исходными временами выдачи, а повторная выдача через новый экземпляр ничего не записывает.
`TestPostgresMigrations` откатывает миграцию 00009 вместе с остальными и проверяет, что таблиц и функций не осталось. Интеграционные тесты identity, доставки и квот почты называют `consent_records` в своем TRUNCATE таблицы `users`. Набор не покрывает usecase отзыва, HTTP-обработчик и вызов usecase согласий из регистрации и принятия приглашения, а гонку очистки с SQLSTATE 23001 покрывает только unit-тест ее преобразования, потому что ее окно нельзя воспроизвести детерминированно.
## Будущая программная валидация