From 12a7213d4a1583c29e2907176409894f81d5f902 Mon Sep 17 00:00:00 2001 From: shira Date: Fri, 9 Oct 2026 19:06:50 +0300 Subject: [PATCH] feat(invitations): check contact grants on every read, cap pending invitations, and expire them at the deadline --- api/README.en.md | 3 +- api/README.md | 3 +- api/core/openapi.bundle.yml | 2 +- .../routes/organization_invitation_send.yml | 2 +- backend/README.en.md | 8 +- backend/README.md | 8 +- ...0042_index_contact_grants_by_candidate.sql | 12 + .../migrations/00043_expire_invitations.sql | 152 +++++ backend/db/queries/contact_grants.sql | 66 +++ backend/db/queries/invitation_cooldowns.sql | 13 + backend/db/queries/invitation_expiry.sql | 30 + backend/db/queries/invitation_pending.sql | 11 + .../contact_read_http_test.go | 518 ++++++++++++++++ .../holding_migration_test.go | 3 + .../invitation_answer_http_test.go | 32 +- .../invitation_expiry_test.go | 551 ++++++++++++++++++ .../integration_test/invitation_http_test.go | 10 + .../primary/http/api/oas_handlers_gen.go | 4 +- .../primary/http/api/oas_server_gen.go | 4 +- .../primary/http/api/oas_unimplemented_gen.go | 4 +- .../adapter/primary/http/v1/contacts.go | 91 +++ .../adapter/primary/http/v1/invitation.go | 13 +- .../primary/http/v1/invitation_test.go | 3 +- .../secondary/postgres/consent_revocation.go | 39 ++ .../postgres/contact_grant_closure.go | 56 ++ .../secondary/postgres/invitation_accept.go | 45 ++ .../secondary/postgres/invitation_expiry.go | 115 ++++ .../adapter/secondary/postgres/invitations.go | 13 +- .../secondary/postgres/privacy_view.go | 23 +- .../postgres/sqlc/contact_grants.sql.go | 123 ++++ .../postgres/sqlc/invitation_cooldowns.sql.go | 39 ++ .../postgres/sqlc/invitation_expiry.sql.go | 73 +++ .../postgres/sqlc/invitation_pending.sql.go | 37 ++ .../secondary/postgres/sqlc/querier.go | 37 ++ backend/internal/bootstrap/jobs.go | 11 +- backend/internal/bootstrap/jobs_test.go | 11 +- backend/internal/domain/contact_disclosure.go | 112 ++++ .../domain/contact_disclosure_test.go | 172 ++++++ backend/internal/domain/contact_grant.go | 3 +- backend/internal/domain/invitation.go | 31 +- backend/internal/domain/invitation_expiry.go | 74 +++ .../internal/domain/invitation_expiry_test.go | 86 +++ backend/internal/port/outbound/consents.go | 24 +- .../internal/port/outbound/contact_grants.go | 17 +- backend/internal/port/outbound/invitations.go | 23 + backend/internal/usecase/invitation/accept.go | 14 +- .../usecase/invitation/accept_test.go | 7 +- .../usecase/invitation/answer_test.go | 10 +- .../usecase/invitation/contact_access.go | 48 ++ .../usecase/invitation/contact_access_test.go | 199 +++++++ .../internal/usecase/invitation/contacts.go | 153 +++++ .../usecase/invitation/contacts_test.go | 205 +++++++ .../internal/usecase/invitation/decline.go | 42 +- backend/internal/usecase/invitation/draft.go | 10 +- backend/internal/usecase/invitation/expire.go | 166 ++++++ .../usecase/invitation/expire_test.go | 272 +++++++++ .../usecase/invitation/pending_limit.go | 50 ++ .../usecase/invitation/pending_limit_test.go | 231 ++++++++ backend/internal/usecase/invitation/send.go | 56 +- .../internal/usecase/invitation/service.go | 24 +- .../usecase/invitation/service_test.go | 28 +- backend/internal/usecase/invitation/view.go | 40 +- docs/en/ARCHITECTURE.md | 68 ++- docs/en/COMPANY_QUOTAS.md | 2 +- docs/ru/ARCHITECTURE.md | 68 ++- docs/ru/COMPANY_QUOTAS.md | 2 +- .../api/endpoints/invitation/invitation.ts | 2 +- 67 files changed, 4255 insertions(+), 149 deletions(-) create mode 100644 backend/db/migrations/00042_index_contact_grants_by_candidate.sql create mode 100644 backend/db/migrations/00043_expire_invitations.sql create mode 100644 backend/db/queries/invitation_cooldowns.sql create mode 100644 backend/db/queries/invitation_expiry.sql create mode 100644 backend/db/queries/invitation_pending.sql create mode 100644 backend/integration_test/contact_read_http_test.go create mode 100644 backend/integration_test/invitation_expiry_test.go create mode 100644 backend/internal/adapter/primary/http/v1/contacts.go create mode 100644 backend/internal/adapter/secondary/postgres/contact_grant_closure.go create mode 100644 backend/internal/adapter/secondary/postgres/invitation_expiry.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/invitation_cooldowns.sql.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/invitation_expiry.sql.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/invitation_pending.sql.go create mode 100644 backend/internal/domain/contact_disclosure.go create mode 100644 backend/internal/domain/contact_disclosure_test.go create mode 100644 backend/internal/domain/invitation_expiry.go create mode 100644 backend/internal/domain/invitation_expiry_test.go create mode 100644 backend/internal/usecase/invitation/contact_access.go create mode 100644 backend/internal/usecase/invitation/contact_access_test.go create mode 100644 backend/internal/usecase/invitation/contacts.go create mode 100644 backend/internal/usecase/invitation/contacts_test.go create mode 100644 backend/internal/usecase/invitation/expire.go create mode 100644 backend/internal/usecase/invitation/expire_test.go create mode 100644 backend/internal/usecase/invitation/pending_limit.go create mode 100644 backend/internal/usecase/invitation/pending_limit_test.go diff --git a/api/README.en.md b/api/README.en.md index 33b07d6..c251a2d 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -459,7 +459,7 @@ Planned contract changes (new enum values; like the catalog codes, generated cli ### Invitations and contact grants -The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The organization side of the draft is implemented: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` follow the rules below, except that `salary_fit` is always `not_available` and the salary limit and the withheld counter are not enforced yet ([backend](../backend/README.en.md#invitation-drafts)). `SendOrganizationInvitation` and `ListMyInvitations` are implemented as well: the send checks the owner, the key, the version, the state, and the current visibility of the candidate and charges the weekly organization quota, while the pending limit of a need and the 30-day pause are not checked yet; a success means the invitation is already in `ListMyInvitations`, and the notification and the email follow through the outbox ([architecture](../docs/en/ARCHITECTURE.md#sending-invitations)). `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` are implemented as described below, with two limits until the related operations exist: no read or command applies the due expiry, so a view at the deadline or later changes nothing and a late decline answers 409 `state_conflict` while the state stays `delivered` or `viewed`; a declined invitation has `contact_consent` and `contact_grant` null. `AcceptMyInvitation` is implemented as the rules below describe, but the contact read and the revocation of a grant are not implemented yet ([architecture](../docs/en/ARCHITECTURE.md#candidate-acceptance)). The business logic of the other operations is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. +The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The organization side of the draft is implemented: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` follow the rules below, except that `salary_fit` is always `not_available` and the salary limit and the withheld counter are not enforced yet ([backend](../backend/README.en.md#invitation-drafts)). `SendOrganizationInvitation` and `ListMyInvitations` are implemented as well: the send checks the owner, the key, the version, the state, the current visibility of the candidate, the pending limit of a need, and the 30-day pause after a decline, and only then charges the weekly organization quota; the pause after a no deal is not checked yet, because no operation produces that state; a success means the invitation is already in `ListMyInvitations`, and the notification and the email follow through the outbox ([architecture](../docs/en/ARCHITECTURE.md#sending-invitations)). `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` are implemented as described below, with one limit: the cancellation is not implemented yet. A read and a view at or after the deadline first move a waiting invitation to `expired` with the reason `invitation_timeout` (the read records no view), and a late decline answers 409 `state_conflict`; a declined invitation has `contact_consent` and `contact_grant` null. `AcceptMyInvitation` is implemented as the rules below describe, but the contact read and the revocation of a grant are not implemented yet ([architecture](../docs/en/ARCHITECTURE.md#candidate-acceptance)). The business logic of the other operations is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -526,6 +526,7 @@ Consent C4 and the contact grant: - The candidate's `contact_grant` has `status` (`active` or `revoked`), `readable`, and `blocked_by`. A grant created while the profile was not published or was hidden from the organization stays `active` with `readable: false` and `blocked_by: visibility`, so the candidate sees why the organization cannot read it (PRD FR12); it becomes readable once the candidate publishes the profile or unhides it. Any visibility change after the grant exists revokes it (`visibility_closed`), and a later publication never reopens it. - Contact values travel only in `ContactDisclosure` from `GetOrganizationInvitationContacts`, separate from the terms and the invitation. Each read checks the membership, C4, the grant and its fields, and the current visibility, without a cache. Without a readable grant the operation answers 404 `not_found`, the same as an unknown invitation. The organization's `contact_access` is `not_granted` (no grant), `available` (with the field kinds), or `closed`, which covers a revoked grant and a grant blocked from the start without saying which. This is the least revealing rule: a revocation, a hiding, and a missing publication look the same, and since every visibility change after the grant revokes it, the organization never observes a later toggle; only a grant blocked from the start can turn `available`, by the candidate's own choice. Fields that the grant does not cover are null. - Revocation: `CancelMyInvitation` revokes the grant of this invitation (`participation_cancelled`); revoking C4 for the organization closes all its grants (`consent_revoked`); revoking C2 or hiding the profile closes them (`visibility_closed`). A withdrawal, a no deal, and a negotiation timeout never revoke a grant; only a new explicit C4 creates a new one. A standalone grant revocation operation belongs to the consent contract. +- Implementation: the contact read, the C4 and C2 revocations, the closing of the publication, and hiding are implemented, owner only, and close the grants as the bullet above states (architecture: [Contact reads and revocation](../docs/en/ARCHITECTURE.md#contact-reads-and-revocation)). The organization's `contact_access` is derived on every read of an invitation (`GetOrganizationInvitation`, the list, and the create, update, and send responses) with the checks of the contact read, so it shows `available` only where a read would succeed, and it never names a reason. `CancelMyInvitation` is not implemented yet. - Value formats: 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) must store contacts in the same formats, so a disclosure never converts or drops a stored value. Decline and privacy: diff --git a/api/README.md b/api/README.md index f5e88dd..81979e5 100644 --- a/api/README.md +++ b/api/README.md @@ -459,7 +459,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Приглашения и контактные разрешения -Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Сторона организации в черновике реализована: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` следуют правилам ниже, но `salary_fit` всегда равен `not_available`, а лимит вилки и счетчик `withheld` пока не применяются ([backend](../backend/README.md#черновики-приглашений)). Реализованы также `SendOrganizationInvitation` и `ListMyInvitations`: отправка проверяет владельца, ключ, версию, состояние и текущую видимость кандидата и списывает недельную квоту организации, а предел ожидающих на потребность и 30-дневная пауза пока не проверяются; успех означает, что приглашение уже есть в `ListMyInvitations`, а уведомление и письмо идут следом через outbox ([архитектура](../docs/ru/ARCHITECTURE.md#отправка-приглашений)). `GetMyInvitation`, `ViewMyInvitation` и `DeclineMyInvitation` реализованы, как описано ниже, с двумя ограничениями до появления связанных операций: ни чтение, ни команда не применяют наступившее истечение, поэтому просмотр в момент срока и позже ничего не меняет, а опоздавший отказ отвечает 409 `state_conflict`, пока состояние остается `delivered` или `viewed`; у отказанного приглашения `contact_consent` и `contact_grant` равны null. `AcceptMyInvitation` реализован, как описывают правила ниже, но чтение контактов и отзыв разрешения еще не реализованы ([архитектура](../docs/ru/ARCHITECTURE.md#принятие-кандидатом)). Бизнес-логика остальных операций еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. +Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Сторона организации в черновике реализована: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` следуют правилам ниже, но `salary_fit` всегда равен `not_available`, а лимит вилки и счетчик `withheld` пока не применяются ([backend](../backend/README.md#черновики-приглашений)). Реализованы также `SendOrganizationInvitation` и `ListMyInvitations`: отправка проверяет владельца, ключ, версию, состояние, текущую видимость кандидата, предел ожидающих приглашений на потребность и 30-дневную паузу после отказа, и только затем списывает недельную квоту организации; пауза после "сделки нет" пока не проверяется, потому что такого состояния никакая операция не создает; успех означает, что приглашение уже есть в `ListMyInvitations`, а уведомление и письмо идут следом через outbox ([архитектура](../docs/ru/ARCHITECTURE.md#отправка-приглашений)). `GetMyInvitation`, `ViewMyInvitation` и `DeclineMyInvitation` реализованы, как описано ниже, с одним ограничением: отмена участия еще не реализована. Чтение и просмотр в срок или позже сначала переводят ожидающее приглашение в `expired` с причиной `invitation_timeout` (чтение не записывает просмотр), а опоздавший отказ отвечает 409 `state_conflict`; у отказанного приглашения `contact_consent` и `contact_grant` равны null. `AcceptMyInvitation` реализован, как описывают правила ниже, но чтение контактов и отзыв разрешения еще не реализованы ([архитектура](../docs/ru/ARCHITECTURE.md#принятие-кандидатом)). Бизнес-логика остальных операций еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -526,6 +526,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - У `contact_grant` кандидата есть `status` (`active` или `revoked`), `readable` и `blocked_by`. Grant, созданный, когда профиль не был опубликован или был скрыт от организации, остается `active` с `readable: false` и `blocked_by: visibility`, чтобы кандидат видел, почему организация не может его прочитать (FR12 в PRD); он станет читаемым, когда кандидат опубликует профиль или снимет скрытие. Любое изменение видимости после появления grant отзывает его (`visibility_closed`), и повторная публикация его не открывает. - Значения контактов передаются только в `ContactDisclosure` из `GetOrganizationInvitationContacts`, отдельно от условий и приглашения. Каждое чтение проверяет членство, C4, grant и его поля и текущую видимость без кеша. Без читаемого grant операция отвечает 404 `not_found`, как для неизвестного приглашения. `contact_access` организации - `not_granted` (grant нет), `available` (с видами полей) или `closed`, что покрывает и отозванный grant, и grant, заблокированный с самого начала, не говоря, какой из них. Это наименее раскрывающее правило: отзыв, скрытие и отсутствие публикации выглядят одинаково, а поскольку любое изменение видимости после появления grant его отзывает, организация не наблюдает последующих переключений; стать `available` может только grant, заблокированный с начала, и лишь по собственному выбору кандидата. Поля вне grant равны null. - Отзыв: `CancelMyInvitation` отзывает grant этого приглашения (`participation_cancelled`); отзыв C4 для организации закрывает все ее grants (`consent_revoked`); отзыв C2 или скрытие профиля закрывает их (`visibility_closed`). Отзыв приглашения, `no_deal` и таймаут финала grant не отзывают; новый grant создает только новое явное C4. Отдельная операция отзыва grant относится к контракту согласий. +- Реализация: чтение контактов, отзывы C4 и C2, закрытие публикации и скрытие реализованы, только для владельца, и закрывают разрешения так, как описано в пункте выше (архитектура: [Чтение контактов и отзыв](../docs/ru/ARCHITECTURE.md#чтение-контактов-и-отзыв)). `contact_access` организации выводится при каждом чтении приглашения (`GetOrganizationInvitation`, список и ответы создания, изменения и отправки) теми же проверками, что и чтение контактов, поэтому он показывает `available` только там, где чтение бы прошло, и никогда не называет причину. `CancelMyInvitation` пока не реализован. - Форматы значений: ФИО одной строкой до 200 символов, телефон в формате E.164 и имя пользователя Telegram с ведущим @. Контракт профиля (FR02) должен хранить контакты в тех же форматах, чтобы раскрытие не преобразовывало и не отбрасывало сохраненное значение. Отказ и приватность: diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 19401ec..72e380a 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -2013,7 +2013,7 @@ paths: Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. - The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are not checked yet. + The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced; the pause after a no deal is planned, because no operation produces the state `no_deal` yet. Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. diff --git a/api/core/routes/organization_invitation_send.yml b/api/core/routes/organization_invitation_send.yml index 513857f..ffea645 100644 --- a/api/core/routes/organization_invitation_send.yml +++ b/api/core/routes/organization_invitation_send.yml @@ -6,7 +6,7 @@ post: Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. - The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are not checked yet. + The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced; the pause after a no deal is planned, because no operation produces the state `no_deal` yet. Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. diff --git a/backend/README.en.md b/backend/README.en.md index fa544a0..1207174 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -26,7 +26,7 @@ HTTP-flow tests with PostgreSQL and Redis are part of `make -C backend test-int` Only the current C1 text is public for registration. A verified user can read current C1/C2/C3/C5 texts before granting them in settings and can page through their own consent history. C1 can be granted by either account scenario; C2, C3, and C5 are candidate-only. Mutations require explicit acceptance, the exact Origin, and session-bound CSRF. -Revoking C2 makes the publication effectively closed and hides its fields through the ledger-backed read in the same transaction; the stored publication stays linked to the revoked record, so a later C2 grant cannot reopen it. Revoking C3 does not block account, profile, or manual-assessment requests through support. Revoking C5 immediately closes the gate for future imports and writes an outbox intent; there is no external FSP adapter yet. C4 revocation is limited to one organization and uses the stored contact scope. A C1 request revokes consent and creates a durable deletion-request record with an outbox intent; repeats return the same active record, and the account is not deleted synchronously. +Revoking C2 makes the publication effectively closed and hides its fields through the ledger-backed read in the same transaction; the stored publication stays linked to the revoked record, so a later C2 grant cannot reopen it. Revoking C3 does not block account, profile, or manual-assessment requests through support. Revoking C5 immediately closes the gate for future imports and writes an outbox intent; there is no external FSP adapter yet. C4 revocation is limited to one organization and uses the stored contact scope; in the same transaction it closes the grants that name the revoked records, and C2 revocation closes every contact grant of the candidate. A C1 request revokes consent and creates a durable deletion-request record with an outbox intent; repeats return the same active record, and the account is not deleted synchronously. `make -C backend test-int` runs the full HTTP flow with PostgreSQL and Redis. `TestConsentSettingsOverHTTP` covers texts, history, grants, revocation effects, and the C1 deletion request. @@ -68,10 +68,14 @@ The integration tests `TestOrganizationInvitationDraftsOverHTTP` (the router, se Sending is implemented: `POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send` (`usecase/invitation/send.go`) and the candidate's list `GET /api/v1/me/invitations` (`usecase/invitation/candidate_inbox.go`). One transaction takes the organization lock, the owner membership, the key, and the invitation row, checks the version and the state, resolves the stored candidate through the card visibility barrier again (409 when hidden, C2 revoked, or suppressed), charges the organization quota through `companyquota.Service.ReserveInvitation` (429 with `Retry-After`), moves the draft to `delivered` with `response_deadline_at = delivered_at + response_period_days`, appends the `delivered` audit event, and writes the outbox events `invitation.delivered` and `notification.mail_requested` (`usecase/notification/invitation.go`). A success therefore means the invitation is already in the candidate's list; the notification and the email follow through the consumers, and neither they nor their retries change the deadline. A repeat with the same key replays the stored outcome, and a send of a delivered invitation answers 200 with its current state without a second charge. Migration `00038_send_invitations.sql` adds the `delivered` event kind, `invitation_send_results` (the 200, 404, or 409 kept under the key), and the foreign key from `company_invitation_quota_usage` to `invitations`; its rollback refuses while a delivery event or a stored outcome exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#sending-invitations). `TestOrganizationInvitationSendOverHTTP` and `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage` cover it against a real PostgreSQL. -The candidate's read, view, decline, and acceptance are implemented: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view`, and `POST .../decline` (`usecase/invitation/view.go` and `decline.go`). The read records nothing; the view moves `delivered` to `viewed` before the deadline, keeps the deadline, and otherwise answers with the invitation as it is; the decline moves `delivered`, `viewed`, or the planned `counter` to `declined` before the deadline with a reason and an optional comment and creates no consent or grant. Both commands lock only the invitation row, never the organization, and append the audit events `viewed` and `declined`. A late decline answers 409, since the expiry is not implemented yet, and a declined invitation has `contact_consent` and `contact_grant` null. Migration `00039_answer_invitations.sql` adds the event kinds, the state rules of the view and the answer, `invitation_declines` (the reason and the comment, which the organization never reads), and `invitation_decline_results` (the outcome under the key); its rollback refuses while a view, a decline, or an outcome exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#candidate-view-and-decline). `TestCandidateInvitationViewAndDeclineOverHTTP` and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` cover it against a real PostgreSQL. +The limit of invitations that wait for an answer per need, the 30-day pause after a decline, and the expiry at the deadline are implemented. The send checks the limit (`max_pending_per_need`) and the pause (`repeat_after_decline_days`) of the effective policy before it charges the quota, and answers 409 `state_conflict`; in the same transaction it schedules the job `invitation.response_deadline` at the response deadline. The handler `usecase/invitation/expire.go` moves a waiting invitation to `expired` with the reason `invitation_timeout`, and the candidate commands apply the due expiry first at or after the deadline. Migration `00043_expire_invitations.sql` adds the event kind `expired` without an actor, the trigger `invitations_guard_expiry`, the partial indexes, and the jobs of invitations that were delivered before it. Details are in the [architecture](../docs/en/ARCHITECTURE.md#pending-limit-cooldown-and-expiry). `TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres`, `TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres`, `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres`, and `TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries` cover it against a real PostgreSQL. + +The candidate's read, view, decline, and acceptance are implemented: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view`, and `POST .../decline` (`usecase/invitation/view.go` and `decline.go`). The read records no view and applies only the due expiry; the view moves `delivered` to `viewed` before the deadline, keeps the deadline, applies the due expiry at or after it, and otherwise answers with the invitation as it is; the decline moves `delivered`, `viewed`, or the planned `counter` to `declined` before the deadline with a reason and an optional comment and creates no consent or grant. The view and the acceptance lock only the invitation row; the decline also takes the organization lock to order the pause of the pair. The commands append the audit events `viewed` and `declined`. A late decline answers 409 after the due expiry, and a declined invitation has `contact_consent` and `contact_grant` null. Migration `00039_answer_invitations.sql` adds the event kinds, the state rules of the view and the answer, `invitation_declines` (the reason and the comment, which the organization never reads), and `invitation_decline_results` (the outcome under the key); its rollback refuses while a view, a decline, or an outcome exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#candidate-view-and-decline). `TestCandidateInvitationViewAndDeclineOverHTTP` and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` cover it against a real PostgreSQL. The candidate's acceptance is implemented: `POST /api/v1/me/invitations/{invitation_id}/accept` (`usecase/invitation/accept.go`). One transaction locks the invitation row, moves a delivered or viewed invitation before its deadline to `accepted` at the invitation version and the terms version that the candidate read, records the consent C4 through `consent.Service.GrantContact` (the published text and the selected fields), stores the contact grant of exactly the selected fields in `contact_grants`, and appends the audit event `accepted`. A stale version answers 412 and is not stored; the consent rules answer 400 with a pointer under `/consent_c4`; a repeat answers the stored acceptance, and another field set answers 409 `state_conflict`. Acceptance never publishes the profile or lifts a hiding: the grant is readable only while the organization may read the profile. Migration `00040_accept_invitations.sql` adds the event kind, the grant table with composite keys that tie it to the invitation, the candidate, and the C4 record, the outcome table, and a refusal of rollback while an acceptance exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#candidate-acceptance). `TestCandidateInvitationAcceptOverHTTP` and `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` cover it against a real PostgreSQL. +The contact read is implemented: `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts` (`usecase/invitation/contacts.go`, handler `adapter/primary/http/v1/contacts.go`). It is owner only. Each request rechecks, under locks, the membership, the C4 record, the grant and its fields, and the visibility of the publication, and every closed case answers 404 `not_found`. A successful read writes one `contact_read` row to `candidate_card_access_events` and consumes no card-view quota. Revoking C4 closes the grants that name its records, revoking C2 or closing the publication closes every grant of the candidate, and hiding an organization closes its grants; unhiding or publishing again never reopens them. Migration `00042_index_contact_grants_by_candidate.sql` adds the index of those closings. Details are in [architecture](../docs/en/ARCHITECTURE.md#contact-reads-and-revocation). `TestOrganizationContactReadsAndRevocationOverHTTP` covers it against a real PostgreSQL. + ## Support cases Verified accounts can create and list their own cases at `/api/v1/me/support-cases` and read a case by its ID. Ownership is independent of access to a disputed action. Object references contain only a type and ID; the server checks their scope and does not copy private object content. Employers can submit general support requests. Candidates can also request manual assessment without a prior attempt or C3 consent. Such a request waits for an expert and does not assign a grade or grant consent. diff --git a/backend/README.md b/backend/README.md index 9f8f9c0..7cf056d 100644 --- a/backend/README.md +++ b/backend/README.md @@ -26,7 +26,7 @@ Публично доступен только текущий текст C1 для регистрации. Подтвержденный пользователь может прочитать текущие тексты C1/C2/C3/C5 перед выдачей в настройках и постранично получить только собственный журнал согласий. C1 можно выдать аккаунту любого сценария; C2, C3 и C5 доступны кандидату. Изменения требуют явного подтверждения, exact Origin и session-bound CSRF. -Отзыв C2 закрывает публикацию в модели чтения и скрывает поля в той же транзакции; сохраненная публикация остается связанной с отозванной записью, поэтому повторная выдача C2 не открывает ее снова. Отзыв C3 не блокирует аккаунт, профиль или запрос ручной оценки через поддержку. Отзыв C5 немедленно закрывает gate будущего импорта и пишет intent в outbox; внешнего адаптера ФСП пока нет. Отзыв C4 ограничен одной организацией и использует сохраненную область контактов. Запрос C1 отзывает согласие и создает долговечную запись запроса удаления с outbox intent; повтор возвращает ту же активную запись, а сама учетная запись не удаляется синхронно. +Отзыв C2 закрывает публикацию в модели чтения и скрывает поля в той же транзакции; сохраненная публикация остается связанной с отозванной записью, поэтому повторная выдача C2 не открывает ее снова. Отзыв C3 не блокирует аккаунт, профиль или запрос ручной оценки через поддержку. Отзыв C5 немедленно закрывает gate будущего импорта и пишет intent в outbox; внешнего адаптера ФСП пока нет. Отзыв C4 ограничен одной организацией и использует сохраненную область контактов; в той же транзакции он закрывает разрешения, которые ссылаются на отозванные записи, а отзыв C2 закрывает все разрешения контактов кандидата. Запрос C1 отзывает согласие и создает долговечную запись запроса удаления с outbox intent; повтор возвращает ту же активную запись, а сама учетная запись не удаляется синхронно. Проверку полного HTTP-пути с PostgreSQL и Redis запускает `make -C backend test-int`; тест `TestConsentSettingsOverHTTP` покрывает тексты, журнал, grants, revocation effects и C1 deletion request. @@ -68,10 +68,14 @@ Реализована отправка: `POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send` (`usecase/invitation/send.go`) и список кандидата `GET /api/v1/me/invitations` (`usecase/invitation/candidate_inbox.go`). Одна транзакция берет блокировку организации, членство владельца, ключ и строку приглашения, проверяет версию и состояние, снова разрешает сохраненного кандидата через барьер видимости карточки (409 при скрытии, отзыве C2 или подавлении), списывает квоту организации через `companyquota.Service.ReserveInvitation` (429 с `Retry-After`), переводит черновик в `delivered` с `response_deadline_at = delivered_at + response_period_days`, добавляет событие аудита `delivered` и пишет события outbox `invitation.delivered` и `notification.mail_requested` (`usecase/notification/invitation.go`). Поэтому успех означает, что приглашение уже в списке кандидата; уведомление и письмо идут следом через обработчики, и ни они, ни их повторы срок не меняют. Повтор с тем же ключом возвращает сохраненный исход, а отправка доставленного приглашения отвечает 200 с текущим состоянием без второго списания. Миграция `00038_send_invitations.sql` добавляет вид события `delivered`, `invitation_send_results` (200, 404 или 409 под ключом) и внешний ключ из `company_invitation_quota_usage` на `invitations`; ее откат отказывает, пока есть событие доставки или сохраненный исход. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#отправка-приглашений). `TestOrganizationInvitationSendOverHTTP` и `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage` проверяют это на настоящем PostgreSQL. -Реализованы чтение, просмотр, отказ и принятие кандидата: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view` и `POST .../decline` (`usecase/invitation/view.go` и `decline.go`). Чтение ничего не записывает; просмотр переводит `delivered` в `viewed` до срока, сохраняет срок, а иначе отвечает приглашением как есть; отказ переводит `delivered`, `viewed` или запланированное `counter` в `declined` до срока с причиной и необязательным комментарием и не создает ни согласия, ни разрешения. Обе команды блокируют только строку приглашения, но не организацию, и добавляют события аудита `viewed` и `declined`. Опоздавший отказ отвечает 409, потому что истечение еще не реализовано, а у отказанного приглашения `contact_consent` и `contact_grant` равны null. Миграция `00039_answer_invitations.sql` добавляет виды событий, правила состояния для просмотра и ответа, `invitation_declines` (причина и комментарий, которые организация никогда не читает) и `invitation_decline_results` (исход под ключом); ее откат отказывает, пока есть просмотр, отказ или исход. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#просмотр-и-отказ-кандидата). `TestCandidateInvitationViewAndDeclineOverHTTP` и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` проверяют это на настоящем PostgreSQL. +Предел ожидающих приглашений на потребность, 30-дневная пауза после отказа и истечение по сроку реализованы. Отправка проверяет предел (`max_pending_per_need`) и паузу (`repeat_after_decline_days`) из эффективной политики до списания квоты и отвечает 409 `state_conflict`; в той же транзакции она ставит задание `invitation.response_deadline` на срок ответа. Обработчик `usecase/invitation/expire.go` переводит ожидающее приглашение в `expired` с причиной `invitation_timeout`, а команды кандидата в срок или позже применяют истечение первыми. Миграция `00043_expire_invitations.sql` добавляет вид события `expired` без актора, триггер `invitations_guard_expiry`, частичные индексы и задания для уже доставленных приглашений. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#предел-ожидающих-пауза-и-истечение). `TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres`, `TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres`, `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres` и `TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries` проверяют это на настоящем PostgreSQL. + +Реализованы чтение, просмотр, отказ и принятие кандидата: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view` и `POST .../decline` (`usecase/invitation/view.go` и `decline.go`). Чтение ничего не записывает, кроме истечения срока; просмотр переводит `delivered` в `viewed` до срока, сохраняет срок, в срок или позже сначала применяет истечение, а иначе отвечает приглашением как есть; отказ переводит `delivered`, `viewed` или запланированное `counter` в `declined` до срока с причиной и необязательным комментарием и не создает ни согласия, ни разрешения. Просмотр и принятие блокируют только строку приглашения, а отказ дополнительно берет блокировку организации, чтобы упорядочить паузу пары; команды добавляют события аудита `viewed` и `declined`. Опоздавший отказ отвечает 409 после применения истечения, а у отказанного приглашения `contact_consent` и `contact_grant` равны null. Миграция `00039_answer_invitations.sql` добавляет виды событий, правила состояния для просмотра и ответа, `invitation_declines` (причина и комментарий, которые организация никогда не читает) и `invitation_decline_results` (исход под ключом); ее откат отказывает, пока есть просмотр, отказ или исход. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#просмотр-и-отказ-кандидата). `TestCandidateInvitationViewAndDeclineOverHTTP` и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` проверяют это на настоящем PostgreSQL. Принятие кандидатом реализовано: `POST /api/v1/me/invitations/{invitation_id}/accept` (`usecase/invitation/accept.go`). Одна транзакция блокирует строку приглашения, переводит доставленное или просмотренное приглашение до срока в `accepted` при версии приглашения и версии условий, которые прочитал кандидат, записывает согласие C4 через `consent.Service.GrantContact` (опубликованный текст и выбранные поля), сохраняет разрешение ровно на выбранные поля в `contact_grants` и добавляет событие аудита `accepted`. Устаревшая версия отвечает 412 и не сохраняется; правила согласия отвечают 400 с указателем под `/consent_c4`; повтор отвечает сохраненным принятием, другой набор полей отвечает 409 `state_conflict`. Принятие никогда не публикует профиль и не снимает скрытие: разрешение читается только пока организация может читать профиль. Миграция `00040_accept_invitations.sql` добавляет вид события, таблицу разрешений с составными ключами на приглашение, кандидата и запись C4, таблицу исходов и отказ отката, пока принятие существует. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#принятие-кандидатом). `TestCandidateInvitationAcceptOverHTTP` и `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` проверяют это на настоящем PostgreSQL. +Чтение контактов реализовано: `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts` (`usecase/invitation/contacts.go`, обработчик `adapter/primary/http/v1/contacts.go`). Операция доступна только владельцу. Каждый запрос заново проверяет под блокировками членство, запись C4, разрешение с его видами и видимость публикации, а любой закрытый случай отвечает 404 `not_found`. Успешное чтение пишет одну строку `contact_read` в `candidate_card_access_events` и не расходует квоту просмотров карточек. Отзыв C4 закрывает разрешения, которые ссылаются на его записи, отзыв C2 или закрытие публикации закрывают все разрешения кандидата, а скрытие организации закрывает ее разрешения; снятие скрытия и повторная публикация их никогда не открывают. Миграция `00042_index_contact_grants_by_candidate.sql` добавляет индекс для этих закрытий. Подробности в [архитектуре](../docs/ru/ARCHITECTURE.md#чтение-контактов-и-отзыв). `TestOrganizationContactReadsAndRevocationOverHTTP` покрывает это на настоящем PostgreSQL. + ## Обращения в поддержку Подтвержденные аккаунты создают и просматривают список собственных обращений через `/api/v1/me/support-cases`, а отдельное дело читают по его ID. Владение обращением не зависит от доступа к спорному действию. Ссылка на объект содержит только тип и ID; сервер проверяет область доступа и не копирует приватное содержимое объекта. Работодатели отправляют общие запросы поддержки. Кандидаты также могут запросить ручную оценку без предыдущей попытки и согласия C3. Такой запрос ожидает эксперта, не назначает грейд и не выдает согласие. diff --git a/backend/db/migrations/00042_index_contact_grants_by_candidate.sql b/backend/db/migrations/00042_index_contact_grants_by_candidate.sql new file mode 100644 index 0000000..de2ad47 --- /dev/null +++ b/backend/db/migrations/00042_index_contact_grants_by_candidate.sql @@ -0,0 +1,12 @@ +-- +goose Up +-- A visibility change of the whole profile closes every active grant of one +-- candidate: the revocation of C2 and the closing of the publication. The +-- existing active index leads with the organization, so it cannot serve that +-- lookup. The index holds no data and only speeds up the closing statement. +CREATE INDEX contact_grants_candidate_active_idx +ON contact_grants (candidate_id) +WHERE revoked_at IS NULL; + +-- +goose Down +-- The index holds no data, so a rollback drops only the lookup it provides. +DROP INDEX contact_grants_candidate_active_idx; diff --git a/backend/db/migrations/00043_expire_invitations.sql b/backend/db/migrations/00043_expire_invitations.sql new file mode 100644 index 0000000..164c832 --- /dev/null +++ b/backend/db/migrations/00043_expire_invitations.sql @@ -0,0 +1,152 @@ +-- +goose Up +-- The pending limit per need, the pause after a decline, and the expiry at the +-- response deadline. A delivered or viewed invitation whose deadline has passed +-- moves to `expired` with the reason `invitation_timeout`. Nothing else changes +-- with it: no consent, no contact grant, and no organization quota is returned. +-- The expiry is written by a scheduled job, which the send schedules for every +-- delivery at its deadline, and by the candidate commands that find the +-- deadline passed. The system performs the expiry, so its audit event names no +-- actor. +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ( + 'draft_created', 'draft_updated', 'delivered', 'viewed', 'declined', + 'accepted', 'expired' + ) +); + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_expiry_changes_no_field CHECK ( + kind <> 'expired' OR cardinality(changed_fields) = 0 +); + +-- Only the expiry is a server change, so only its event may lack an actor. +ALTER TABLE invitation_events +ALTER COLUMN actor_id DROP NOT NULL; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_system_actor CHECK ( + (kind = 'expired') = (actor_id IS NULL) +); + +-- Only a delivered or viewed invitation expires, and the expiry is not +-- recorded before the deadline it passed. The application compares the clock +-- with the deadline; this trigger keeps a row changed outside the application +-- from skipping either rule. An expiry without its reason is left to the +-- check constraint invitations_expiry_reason, which runs after this trigger. +-- +goose StatementBegin +CREATE FUNCTION invitations_guard_expiry() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.state = 'expired' AND NEW.expiry_reason IS NOT NULL + AND OLD.state IS DISTINCT FROM NEW.state THEN + IF OLD.state NOT IN ('delivered', 'viewed') THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_expiry_from_pending', + TABLE = 'invitations', + MESSAGE = 'only a delivered or viewed invitation expires'; + END IF; + IF NEW.updated_at < OLD.response_deadline_at THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_expiry_after_deadline', + TABLE = 'invitations', + MESSAGE = 'an invitation expires at or after its response deadline'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER invitations_guard_expiry +BEFORE UPDATE ON invitations +FOR EACH ROW EXECUTE FUNCTION invitations_guard_expiry(); + +-- The invitations that wait for an answer under one need of an organization: +-- the pending limit counts them. +CREATE INDEX invitations_pending_need_idx +ON invitations (organization_id, need_id) +WHERE need_id IS NOT NULL AND state IN ('delivered', 'viewed', 'counter'); + +-- The latest decline of one candidate by one organization, which starts the +-- pause before the next invitation of that pair. +CREATE INDEX invitations_declined_pair_idx +ON invitations (organization_id, candidate_id, responded_at DESC) +WHERE state = 'declined'; + +-- Invitations delivered before this migration have no deadline job yet. The +-- job's key is the invitation identifier, so the schedule is idempotent, and +-- its due time is the deadline that the invitation already stores. +INSERT INTO scheduled_jobs ( + kind, + dedup_key, + payload, + due_at, + available_at, + status, + attempts +) +SELECT + 'invitation.response_deadline', + invitations.id::text, + jsonb_build_object('invitation_id', invitations.id::text), + invitations.response_deadline_at AS due_at, + invitations.response_deadline_at AS available_at, + 'pending', + 0 +FROM invitations +WHERE + invitations.state IN ('delivered', 'viewed') + AND invitations.response_deadline_at IS NOT NULL +ON CONFLICT (kind, dedup_key) DO NOTHING; + +-- +goose Down +-- A rollback must not hide an expiry that already happened, and it must not +-- leave the deadline jobs without a handler. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM invitation_events WHERE kind = 'expired') + OR EXISTS (SELECT 1 FROM invitations WHERE state = 'expired') THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitation_expiries_retained', + TABLE = 'invitation_events', + MESSAGE = 'expired invitations must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DELETE FROM scheduled_jobs WHERE kind = 'invitation.response_deadline'; + +DROP INDEX invitations_declined_pair_idx; +DROP INDEX invitations_pending_need_idx; + +DROP TRIGGER invitations_guard_expiry ON invitations; +DROP FUNCTION invitations_guard_expiry(); + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_system_actor; + +ALTER TABLE invitation_events +ALTER COLUMN actor_id SET NOT NULL; + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_expiry_changes_no_field; + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ( + 'draft_created', 'draft_updated', 'delivered', 'viewed', 'declined', + 'accepted' + ) +); diff --git a/backend/db/queries/contact_grants.sql b/backend/db/queries/contact_grants.sql index 2482439..70f77f1 100644 --- a/backend/db/queries/contact_grants.sql +++ b/backend/db/queries/contact_grants.sql @@ -43,3 +43,69 @@ FROM contact_grants WHERE organization_id = sqlc.arg(organization_id) AND source_invitation_id = sqlc.arg(invitation_id); + +-- Share-locks the consent C4 record of a grant for the duration of a contact +-- read. The read locks the record before the grant, the order that a C4 +-- revocation follows when it stamps the record and then closes its grants. No +-- row means the record is revoked or belongs to another scope, which closes +-- the read. +-- name: LockCurrentContactConsentRecord :one +SELECT consent_records.id +FROM consent_records +WHERE + consent_records.id = sqlc.arg(consent_record_id) + AND consent_records.subject_id = sqlc.arg(candidate_id) + AND consent_records.organization_id = sqlc.arg(organization_id) + AND consent_records.purpose = 'c4' + AND consent_records.revoked_at IS NULL +FOR SHARE; + +-- Share-locks one grant for the duration of a contact read and returns its +-- stored state. The caller decides whether the state still allows the read. +-- name: LockContactGrant :one +SELECT + id, + organization_id, + candidate_id, + source_invitation_id, + consent_record_id, + terms_version, + fields, + consent_text_version, + granted_at, + revoked_at, + revocation_reason +FROM contact_grants +WHERE id = sqlc.arg(id) +FOR SHARE; + +-- Closes the active grants of one candidate with one reason. A nil organization +-- closes every organization of the candidate, and a non-nil list of consent +-- records closes only the grants that those records gave. The grant rows are +-- locked in identifier order, so two closures that overlap take their locks in +-- the same order. The revocation time never precedes the grant time, which the +-- grant checks. A grant that is already closed keeps its first stamp. +-- name: CloseActiveContactGrants :execrows +WITH targets AS ( + SELECT contact_grants.id + FROM contact_grants + WHERE + contact_grants.candidate_id = sqlc.arg(candidate_id) + AND ( + sqlc.narg(organization_id)::uuid IS NULL + OR contact_grants.organization_id = sqlc.narg(organization_id)::uuid + ) + AND ( + sqlc.narg(consent_record_ids)::uuid [] IS NULL + OR contact_grants.consent_record_id = ANY(sqlc.narg(consent_record_ids)::uuid []) + ) + AND contact_grants.revoked_at IS NULL + ORDER BY contact_grants.id + FOR NO KEY UPDATE +) +UPDATE contact_grants +SET + revoked_at = greatest(contact_grants.granted_at, sqlc.arg(revoked_at)::timestamptz), + revocation_reason = sqlc.arg(revocation_reason) +FROM targets +WHERE contact_grants.id = targets.id; diff --git a/backend/db/queries/invitation_cooldowns.sql b/backend/db/queries/invitation_cooldowns.sql new file mode 100644 index 0000000..6522c85 --- /dev/null +++ b/backend/db/queries/invitation_cooldowns.sql @@ -0,0 +1,13 @@ +-- The time of the latest decline of one candidate by one organization, across +-- every need and every member of the organization. The pause that follows it is +-- applied by the send, from the policy in force. A candidate without a decline +-- finds no row. +-- name: LatestInvitationDecline :one +SELECT responded_at AS declined_at +FROM invitations +WHERE + organization_id = sqlc.arg(organization_id) + AND candidate_id = sqlc.arg(candidate_id) + AND state = 'declined' +ORDER BY responded_at DESC +LIMIT 1; diff --git a/backend/db/queries/invitation_expiry.sql b/backend/db/queries/invitation_expiry.sql new file mode 100644 index 0000000..98784fc --- /dev/null +++ b/backend/db/queries/invitation_expiry.sql @@ -0,0 +1,30 @@ +-- Takes the row lock of one invitation by its identifier alone. Only the +-- response deadline job reads an invitation without an organization or a +-- candidate of the request; it reads the organization from this row and then +-- reads the locked invitation with its scope. +-- name: LockInvitationByID :one +SELECT organization_id +FROM invitations +WHERE id = sqlc.arg(invitation_id) +FOR UPDATE; + +-- The compare-and-swap of the expiry: it applies only to a delivered or viewed +-- invitation at the version the caller read, whose deadline has passed at the +-- expiry time. It keeps the deadline, the terms, and every answer field, and it +-- sets the timeout reason. No row is returned when it lost a race or the +-- deadline has not passed. +-- name: ExpireInvitation :one +UPDATE invitations +SET + state = 'expired', + expiry_reason = 'invitation_timeout', + version = sqlc.arg(next_version), + updated_at = sqlc.arg(expired_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state IN ('delivered', 'viewed') + AND version = sqlc.arg(expected_version) + AND response_deadline_at <= sqlc.arg(expired_at) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; diff --git a/backend/db/queries/invitation_pending.sql b/backend/db/queries/invitation_pending.sql new file mode 100644 index 0000000..470670f --- /dev/null +++ b/backend/db/queries/invitation_pending.sql @@ -0,0 +1,11 @@ +-- Counts the invitations of one organization need that wait for an answer: +-- delivered, viewed, or the planned counter offer. The send counts them under +-- the organization lock, which every send takes first, so no other send can +-- add a waiting invitation between the count and its own delivery. +-- name: CountPendingNeedInvitations :one +SELECT count(*)::bigint AS pending +FROM invitations +WHERE + organization_id = sqlc.arg(organization_id) + AND need_id = sqlc.arg(need_id) + AND state IN ('delivered', 'viewed', 'counter'); diff --git a/backend/integration_test/contact_read_http_test.go b/backend/integration_test/contact_read_http_test.go new file mode 100644 index 0000000..6805649 --- /dev/null +++ b/backend/integration_test/contact_read_http_test.go @@ -0,0 +1,518 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/policy" +) + +const contactReadTimeout = 10 * time.Minute + +// contactDisclosureHTTP is the contact disclosure as the owner reads it. A +// null value is a nil pointer, so a value that leaks shows up as non-nil. +type contactDisclosureHTTP struct { + InvitationID uuid.UUID `json:"invitation_id"` + GrantID uuid.UUID `json:"grant_id"` + Fields []string `json:"fields"` + GrantedAt time.Time `json:"granted_at"` + FullName *string `json:"full_name"` + Email *string `json:"email"` + Phone *string `json:"phone"` + Telegram *string `json:"telegram"` +} + +// TestOrganizationContactReadsAndRevocationOverHTTP covers the contact read +// through an accepted invitation and the independent closing of its grant: the +// consent C4, the consent C2 and the publication, and the hiding of the +// organization. Each subtest uses its own candidates, so the cases do not share +// the state of a grant. +func TestOrganizationContactReadsAndRevocationOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), contactReadTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolated := *env + isolated.Config.DatabaseURL = databaseURL + setupPool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + harness := newInvitationHTTPHarness(ctx, t, &isolated) + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)) + origin := env.Config.AppPublicURL + now := harness.clock.Now() + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + account := func(email string, scenario domain.Scenario) domain.User { + return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now) + } + ownerA := account("contact-owner-a@example.test", domain.ScenarioEmployer) + ownerB := account("contact-owner-b@example.test", domain.ScenarioEmployer) + ownerD := account("contact-owner-d@example.test", domain.ScenarioEmployer) + recruiterA := account("contact-recruiter-a@example.test", domain.ScenarioEmployer) + sessionOwnerA := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()) + sessionOwnerB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()) + sessionOwnerD := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerD.Email.Address()) + orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwnerA, "contact-company-a") + orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwnerB, "contact-company-b") + orgD := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwnerD, "contact-company-d") + insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA, recruiterA.ID, "recruiter", "active", now) + sessionRecruiterA := loginOrganizationHTTP(t, harness.sessionHTTPHarness, recruiterA.Email.Address()) + + identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture, now: now} + var keySequence int + nextKey := func() string { + keySequence++ + return fmt.Sprintf("contact-read-key-%d", keySequence) + } + request := func(method, path, body string, session organizationHTTPSession, key string) *httptest.ResponseRecorder { + t.Helper() + return organizationHTTPRequest(t, harness.sessionHTTPHarness, method, path, body, origin, session, key) + } + // Each candidate signs in once: the login limit of one client is shared by + // the whole subtest, and every request of a candidate reuses its session. + sessions := map[uuid.UUID]organizationHTTPSession{} + login := func(candidate domain.User) organizationHTTPSession { + t.Helper() + if session, ok := sessions[candidate.ID]; ok { + return session + } + session := loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) + sessions[candidate.ID] = session + return session + } + // newCandidate creates a candidate who holds an email and a phone number, + // grants C2, and publishes the card, through the routes the candidate uses. + newCandidate := func(email string) domain.User { + t.Helper() + candidate := account(email, domain.ScenarioCandidate) + profiles.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision("Contact Candidate"), Email: confirmedDecision(email), Phone: confirmedDecision("+70000000000"), + }, 0) + session := login(candidate) + if response := request(http.MethodPut, "/api/v1/me/consents/c2", + fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), session, ""); response.Code != http.StatusOK { + t.Fatalf("C2 grant = %d %s, want 200", response.Code, response.Body.String()) + } + if response := request(http.MethodPut, "/api/v1/me/privacy/publication", + `{"expected_version":0,"state":"published","fields":["stack"]}`, session, ""); response.Code != http.StatusOK { + t.Fatalf("publication = %d %s, want 200", response.Code, response.Body.String()) + } + return candidate + } + // deliver creates a draft for the candidate and sends it from the organization. + deliver := func(organizationID uuid.UUID, owner organizationHTTPSession, candidate domain.User) invitationHTTPBody { + t.Helper() + handle, err := harness.key.ForOrganization(organizationID, candidate.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + draft := decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", organizationID), + invitationCreateJSON(t, handle, nil), owner, nextKey()), http.StatusCreated) + return decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/send", organizationID, draft.ID), + fmt.Sprintf(`{"expected_version":%d}`, draft.Version), owner, nextKey()), http.StatusOK) + } + acceptResponse := func(candidate domain.User, invitation invitationHTTPBody, key string, fields ...string) *httptest.ResponseRecorder { + t.Helper() + encoded, err := json.Marshal(map[string]any{ + "expected_version": invitation.Version, "terms_version": invitation.TermsVersion, + "consent_c4": map[string]any{"text_version": acceptTextVersion, "accepted": true, "fields": fields}, + }) + if err != nil { + t.Fatalf("marshal acceptance: %v", err) + } + return request(http.MethodPost, "/api/v1/me/invitations/"+invitation.ID.String()+"/accept", string(encoded), login(candidate), key) + } + acceptFields := func(candidate domain.User, invitation invitationHTTPBody, fields ...string) candidateInvitationHTTPBody { + t.Helper() + return decodeCandidateInvitationHTTP(t, acceptResponse(candidate, invitation, nextKey(), fields...), http.StatusOK) + } + readContacts := func(organizationID, invitationID uuid.UUID, session organizationHTTPSession) *httptest.ResponseRecorder { + t.Helper() + return request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/contacts", organizationID, invitationID), "", session, "") + } + requireDisclosure := func(response *httptest.ResponseRecorder, invitationID, grantID uuid.UUID) contactDisclosureHTTP { + t.Helper() + if response.Code != http.StatusOK { + t.Fatalf("contact read = %d %s, want 200", response.Code, response.Body.String()) + } + if cache := response.Header().Get("Cache-Control"); cache != "no-store" { + t.Fatalf("contact read Cache-Control = %q, want no-store", cache) + } + var disclosure contactDisclosureHTTP + if err := json.Unmarshal(response.Body.Bytes(), &disclosure); err != nil { + t.Fatalf("decode contact read %s: %v", response.Body.String(), err) + } + if disclosure.InvitationID != invitationID || disclosure.GrantID != grantID { + t.Fatalf("contact read names invitation %s and grant %s, want %s and %s", disclosure.InvitationID, disclosure.GrantID, invitationID, grantID) + } + return disclosure + } + requireNotFound := func(label string, response *httptest.ResponseRecorder) { + t.Helper() + if response.Code != http.StatusNotFound { + t.Fatalf("%s = %d %s, want 404", label, response.Code, response.Body.String()) + } + requireSessionProblem(t, response, http.StatusNotFound, "not_found") + } + grantRow := func(invitationID uuid.UUID) (revoked bool, reason string) { + t.Helper() + var reasonValue *string + if err := harness.pool.QueryRow(ctx, `SELECT revoked_at IS NOT NULL, revocation_reason FROM contact_grants WHERE source_invitation_id = $1`, + invitationID).Scan(&revoked, &reasonValue); err != nil { + t.Fatalf("read grant of %s: %v", invitationID, err) + } + if reasonValue != nil { + reason = *reasonValue + } + return revoked, reason + } + requireGrantStatus := func(candidate domain.User, invitationID uuid.UUID, status string, readable bool, reason string) { + t.Helper() + read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, "/api/v1/me/invitations/"+invitationID.String(), "", login(candidate), ""), http.StatusOK) + grant := decodeContactGrantHTTP(t, read) + if grant.Status != status || grant.Readable != readable { + t.Fatalf("grant as the candidate reads it = %+v, want status %q readable %v", grant, status, readable) + } + if reason == "" { + if grant.RevocationReason != nil { + t.Fatalf("grant reason = %q, want none", *grant.RevocationReason) + } + return + } + if grant.RevocationReason == nil || *grant.RevocationReason != reason { + t.Fatalf("grant reason = %v, want %q", grant.RevocationReason, reason) + } + } + // requireNoContactValues fails when a response carries a value of the + // candidates that the test creates. Only the kinds may appear. + requireNoContactValues := func(label, text string) { + t.Helper() + for _, marker := range []string{"@example.test", "+70000000000", "Contact Candidate"} { + if strings.Contains(text, marker) { + t.Fatalf("%s carries the contact value %q: %s", label, marker, text) + } + } + } + // requireOrganizationAccess reads one invitation as its owner and checks the + // contact access of the response: its status and the kinds it lists. + requireOrganizationAccess := func(label string, organizationID, invitationID uuid.UUID, session organizationHTTPSession, status string, fields ...string) invitationHTTPBody { + t.Helper() + response := request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID), "", session, "") + invitation := decodeInvitationHTTP(t, response, http.StatusOK) + if invitation.ContactAccess.Status != status || !slices.Equal(invitation.ContactAccess.Fields, fields) { + t.Fatalf("%s contact access = %+v, want %q with fields %v", label, invitation.ContactAccess, status, fields) + } + requireNoContactValues(label, response.Body.String()) + return invitation + } + // requireListedAccess checks the contact access of one invitation in the + // owner's list, which shows the same states as the single read. + requireListedAccess := func(organizationID, invitationID uuid.UUID, session organizationHTTPSession, status string, fields ...string) { + t.Helper() + response := request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations?limit=100", organizationID), "", session, "") + if response.Code != http.StatusOK { + t.Fatalf("organization list = %d %s, want 200", response.Code, response.Body.String()) + } + requireNoContactValues("organization list", response.Body.String()) + var page struct { + Items []struct { + ID uuid.UUID `json:"id"` + ContactAccess struct { + Status string `json:"status"` + Fields []string `json:"fields"` + } `json:"contact_access"` + } `json:"items"` + } + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode organization list: %v", err) + } + for _, item := range page.Items { + if item.ID != invitationID { + continue + } + if item.ContactAccess.Status != status || !slices.Equal(item.ContactAccess.Fields, fields) { + t.Fatalf("listed contact access = %+v, want %q with fields %v", item.ContactAccess, status, fields) + } + return + } + t.Fatalf("organization list does not show invitation %s", invitationID) + } + candidates := []domain.User{} + for index := range 6 { + candidates = append(candidates, newCandidate(fmt.Sprintf("contact-candidate-%d@example.test", index))) + } + + t.Run("an email-only grant reads the email to the owner and nothing else", func(t *testing.T) { + candidate := candidates[0] + invitation := deliver(orgA, sessionOwnerA, candidate) + requireOrganizationAccess("organization view before the acceptance", orgA, invitation.ID, sessionOwnerA, "not_granted") + accepted := acceptFields(candidate, invitation, "email") + grantID := decodeContactGrantHTTP(t, accepted).ID + requireOrganizationAccess("organization view after the acceptance", orgA, invitation.ID, sessionOwnerA, "available", "email") + requireListedAccess(orgA, invitation.ID, sessionOwnerA, "available", "email") + + first := readContacts(orgA, invitation.ID, sessionOwnerA) + disclosure := requireDisclosure(first, invitation.ID, grantID) + if len(disclosure.Fields) != 1 || disclosure.Fields[0] != "email" || disclosure.Email == nil || *disclosure.Email != candidate.Email.Address() { + t.Fatalf("disclosure = %+v, want the confirmed email only", disclosure) + } + if disclosure.Phone != nil || disclosure.FullName != nil || disclosure.Telegram != nil { + t.Fatalf("disclosure = %+v, want null for every kind the grant does not cover", disclosure) + } + if again := readContacts(orgA, invitation.ID, sessionOwnerA); again.Code != http.StatusOK || again.Body.String() != first.Body.String() { + t.Fatalf("repeated contact read = %d %s, want the same body", again.Code, again.Body.String()) + } + + // Organization B and a non-owner member of A are refused, and so is a + // candidate or an anonymous request. + requireNotFound("owner of another organization on the path of A", readContacts(orgA, invitation.ID, sessionOwnerB)) + requireNotFound("owner of B on its own path with the invitation of A", readContacts(orgB, invitation.ID, sessionOwnerB)) + requireSessionProblem(t, readContacts(orgA, invitation.ID, sessionRecruiterA), http.StatusForbidden, "forbidden") + requireSessionProblem(t, readContacts(orgA, invitation.ID, login(candidate)), http.StatusForbidden, "forbidden") + requireSessionProblem(t, readContacts(orgA, invitation.ID, organizationHTTPSession{}), http.StatusUnauthorized, "unauthenticated") + + // Each successful read is audited with its kinds only, and the read does + // not consume the card-view quota. + var audited, emailOnly int + var actor string + if err := harness.pool.QueryRow(ctx, ` + SELECT count(*), + count(*) FILTER (WHERE field_codes = ARRAY['email']::text []), + COALESCE(max(actor_id::text), '') + FROM candidate_card_access_events + WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidate.ID, orgA). + Scan(&audited, &emailOnly, &actor); err != nil { + t.Fatalf("read the access audit: %v", err) + } + if audited != 2 || emailOnly != 2 || actor != ownerA.ID.String() { + t.Fatalf("access audit = %d rows, %d of them the email only, by %q; want the two successful reads by the owner", audited, emailOnly, actor) + } + var viewQuota int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1`, orgA).Scan(&viewQuota); err != nil { + t.Fatalf("count card view quota: %v", err) + } + if viewQuota != 0 { + t.Fatalf("contact reads consumed %d card-view quota rows, want none", viewQuota) + } + requireGrantStatus(candidate, invitation.ID, "active", true, "") + if logs := harness.logs.String(); strings.Contains(logs, candidate.Email.Address()) || strings.Contains(logs, candidate.ID.String()) { + t.Fatal("the server log contains the candidate's email or identifier") + } + }) + + t.Run("revoking C4 closes the grant for the URL, the API, and a repeated request, and leaves other organizations", func(t *testing.T) { + candidate := candidates[1] + inA := deliver(orgA, sessionOwnerA, candidate) + grantA := decodeContactGrantHTTP(t, acceptFields(candidate, inA, "email")).ID + inB := deliver(orgB, sessionOwnerB, candidate) + grantB := decodeContactGrantHTTP(t, acceptFields(candidate, inB, "email")).ID + requireDisclosure(readContacts(orgA, inA.ID, sessionOwnerA), inA.ID, grantA) + requireDisclosure(readContacts(orgB, inB.ID, sessionOwnerB), inB.ID, grantB) + + revoke := request(http.MethodDelete, "/api/v1/me/consents/c4/organizations/"+orgA.String(), "", login(candidate), "") + if revoke.Code != http.StatusNoContent { + t.Fatalf("C4 revoke for A = %d %s, want 204", revoke.Code, revoke.Body.String()) + } + requireNotFound("contact read after the revocation", readContacts(orgA, inA.ID, sessionOwnerA)) + requireNotFound("repeated contact read after the revocation", readContacts(orgA, inA.ID, sessionOwnerA)) + requireDisclosure(readContacts(orgB, inB.ID, sessionOwnerB), inB.ID, grantB) + if revoked, reason := grantRow(inA.ID); !revoked || reason != "consent_revoked" { + t.Fatalf("grant of A after the C4 revocation: revoked %v reason %q, want consent_revoked", revoked, reason) + } + if revoked, _ := grantRow(inB.ID); revoked { + t.Fatal("the C4 revocation for A closed the grant of B") + } + requireGrantStatus(candidate, inA.ID, "revoked", false, "consent_revoked") + requireGrantStatus(candidate, inB.ID, "active", true, "") + requireOrganizationAccess("organization view of A after the C4 revocation", orgA, inA.ID, sessionOwnerA, "closed") + requireOrganizationAccess("organization view of B after the C4 revocation", orgB, inB.ID, sessionOwnerB, "available", "email") + + // The publication stays as it was: the C4 revocation closes only the grant, + // and only a new explicit C4 creates a new grant for A. + requireNotFound("contact read of the revoked grant", readContacts(orgA, inA.ID, sessionOwnerA)) + inAgain := deliver(orgA, sessionOwnerA, candidate) + grantAgain := decodeContactGrantHTTP(t, acceptFields(candidate, inAgain, "email")).ID + if grantAgain == grantA { + t.Fatal("a new C4 reused the revoked grant") + } + requireDisclosure(readContacts(orgA, inAgain.ID, sessionOwnerA), inAgain.ID, grantAgain) + requireNotFound("the revoked grant after a new C4", readContacts(orgA, inA.ID, sessionOwnerA)) + requireOrganizationAccess("organization view of the revoked invitation after a new C4", orgA, inA.ID, sessionOwnerA, "closed") + requireOrganizationAccess("organization view of the new grant", orgA, inAgain.ID, sessionOwnerA, "available", "email") + }) + + t.Run("hiding the organization closes its grants, and unhiding never reopens them", func(t *testing.T) { + candidate := candidates[2] + inA := deliver(orgA, sessionOwnerA, candidate) + grantA := decodeContactGrantHTTP(t, acceptFields(candidate, inA, "email")).ID + inB := deliver(orgB, sessionOwnerB, candidate) + grantB := decodeContactGrantHTTP(t, acceptFields(candidate, inB, "phone")).ID + // The candidate may hide only an organization that already appears in + // the candidate's access history, so the owner reads the grant first. + requireDisclosure(readContacts(orgA, inA.ID, sessionOwnerA), inA.ID, grantA) + + hide := request(http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), "") + if hide.Code != http.StatusOK { + t.Fatalf("hide A = %d %s, want 200", hide.Code, hide.Body.String()) + } + requireNotFound("contact read while A is hidden", readContacts(orgA, inA.ID, sessionOwnerA)) + requireDisclosure(readContacts(orgB, inB.ID, sessionOwnerB), inB.ID, grantB) + unhide := request(http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), "") + if unhide.Code != http.StatusNoContent { + t.Fatalf("unhide A = %d %s, want 204", unhide.Code, unhide.Body.String()) + } + requireNotFound("contact read after unhiding A", readContacts(orgA, inA.ID, sessionOwnerA)) + requireOrganizationAccess("organization view of A after hiding and unhiding", orgA, inA.ID, sessionOwnerA, "closed") + if revoked, reason := grantRow(inA.ID); !revoked || reason != "visibility_closed" { + t.Fatalf("grant of A after hiding: revoked %v reason %q, want visibility_closed", revoked, reason) + } + requireGrantStatus(candidate, inA.ID, "revoked", false, "visibility_closed") + requireOrganizationAccess("organization view of A while hidden", orgA, inA.ID, sessionOwnerA, "closed") + if revoked, _ := grantRow(inB.ID); revoked { + t.Fatal("hiding A closed the grant of B") + } + + // A grant created while the organization is hidden stays stored and blocked, + // and it becomes readable when the candidate unhides the organization. + inAHidden := deliver(orgA, sessionOwnerA, candidate) + hideAgain := request(http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), "") + if hideAgain.Code != http.StatusOK { + t.Fatalf("hide A again = %d %s, want 200", hideAgain.Code, hideAgain.Body.String()) + } + blocked := decodeCandidateInvitationHTTP(t, acceptResponse(candidate, inAHidden, nextKey(), "email"), http.StatusOK) + grantHidden := decodeContactGrantHTTP(t, blocked) + if grantHidden.Readable || grantHidden.BlockedBy == nil || *grantHidden.BlockedBy != "visibility" { + t.Fatalf("grant accepted while hidden = %+v, want blocked by visibility", grantHidden) + } + requireNotFound("contact read of the blocked grant", readContacts(orgA, inAHidden.ID, sessionOwnerA)) + requireOrganizationAccess("organization view of the blocked grant", orgA, inAHidden.ID, sessionOwnerA, "closed") + if response := request(http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), ""); response.Code != http.StatusNoContent { + t.Fatalf("unhide A after the blocked acceptance = %d %s, want 204", response.Code, response.Body.String()) + } + requireDisclosure(readContacts(orgA, inAHidden.ID, sessionOwnerA), inAHidden.ID, grantHidden.ID) + requireOrganizationAccess("organization view of the blocked grant after unhiding", orgA, inAHidden.ID, sessionOwnerA, "available", "email") + }) + + t.Run("withdrawing C2 closes the grants, and publishing again does not reopen them", func(t *testing.T) { + candidate := candidates[3] + invitation := deliver(orgD, sessionOwnerD, candidate) + grant := decodeContactGrantHTTP(t, acceptFields(candidate, invitation, "email")).ID + requireDisclosure(readContacts(orgD, invitation.ID, sessionOwnerD), invitation.ID, grant) + + revokeC2 := request(http.MethodDelete, "/api/v1/me/consents/c2", "", login(candidate), "") + if revokeC2.Code != http.StatusNoContent { + t.Fatalf("C2 revoke = %d %s, want 204", revokeC2.Code, revokeC2.Body.String()) + } + requireNotFound("contact read after C2 revoke", readContacts(orgD, invitation.ID, sessionOwnerD)) + requireOrganizationAccess("organization view after the C2 withdrawal", orgD, invitation.ID, sessionOwnerD, "closed") + if revoked, reason := grantRow(invitation.ID); !revoked || reason != "visibility_closed" { + t.Fatalf("grant after C2 revoke: revoked %v reason %q, want visibility_closed", revoked, reason) + } + if response := request(http.MethodPut, "/api/v1/me/consents/c2", + fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), login(candidate), ""); response.Code != http.StatusOK { + t.Fatalf("C2 regrant = %d %s, want 200", response.Code, response.Body.String()) + } + var version int64 + if err := harness.pool.QueryRow(ctx, `SELECT version FROM candidate_publications WHERE user_id = $1`, candidate.ID).Scan(&version); err != nil { + t.Fatalf("read publication version: %v", err) + } + if response := request(http.MethodPut, "/api/v1/me/privacy/publication", + fmt.Sprintf(`{"expected_version":%d,"state":"published","fields":["stack"]}`, version), login(candidate), ""); response.Code != http.StatusOK { + t.Fatalf("republication = %d %s, want 200", response.Code, response.Body.String()) + } + requireNotFound("contact read after republishing", readContacts(orgD, invitation.ID, sessionOwnerD)) + requireGrantStatus(candidate, invitation.ID, "revoked", false, "visibility_closed") + requireOrganizationAccess("organization view after republishing", orgD, invitation.ID, sessionOwnerD, "closed") + }) + + t.Run("closing the publication closes the grants", func(t *testing.T) { + candidate := candidates[4] + invitation := deliver(orgD, sessionOwnerD, candidate) + grant := decodeContactGrantHTTP(t, acceptFields(candidate, invitation, "email")).ID + requireDisclosure(readContacts(orgD, invitation.ID, sessionOwnerD), invitation.ID, grant) + + var version int64 + if err := harness.pool.QueryRow(ctx, `SELECT version FROM candidate_publications WHERE user_id = $1`, candidate.ID).Scan(&version); err != nil { + t.Fatalf("read publication version: %v", err) + } + closing := request(http.MethodPut, "/api/v1/me/privacy/publication", + fmt.Sprintf(`{"expected_version":%d,"state":"closed","fields":[]}`, version), login(candidate), "") + if closing.Code != http.StatusOK { + t.Fatalf("closing the publication = %d %s, want 200", closing.Code, closing.Body.String()) + } + requireNotFound("contact read after closing the publication", readContacts(orgD, invitation.ID, sessionOwnerD)) + requireOrganizationAccess("organization view after closing the publication", orgD, invitation.ID, sessionOwnerD, "closed") + if revoked, reason := grantRow(invitation.ID); !revoked || reason != "visibility_closed" { + t.Fatalf("grant after closing: revoked %v reason %q, want visibility_closed", revoked, reason) + } + }) + + t.Run("the grant index for candidate-wide closing exists", func(t *testing.T) { + var indexes int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM pg_indexes WHERE indexname = 'contact_grants_candidate_active_idx'`).Scan(&indexes); err != nil { + t.Fatalf("read the index catalog: %v", err) + } + if indexes != 1 { + t.Fatalf("contact_grants_candidate_active_idx count = %d, want 1", indexes) + } + }) + + t.Run("a declined invitation shows not_granted", func(t *testing.T) { + candidate := candidates[5] + invitation := deliver(orgA, sessionOwnerA, candidate) + answer := request(http.MethodPost, "/api/v1/me/invitations/"+invitation.ID.String()+"/decline", + fmt.Sprintf(`{"expected_version":%d,"reason":"other"}`, invitation.Version), login(candidate), nextKey()) + if answer.Code != http.StatusOK { + t.Fatalf("decline = %d %s, want 200", answer.Code, answer.Body.String()) + } + declined := requireOrganizationAccess("organization view of a declined invitation", orgA, invitation.ID, sessionOwnerA, "not_granted") + if declined.State != "declined" { + t.Fatalf("declined invitation state = %q, want declined", declined.State) + } + }) + + // This subtest moves the clock to the response deadline, which ends the + // sessions that were created earlier, so it signs in again after the move. + // It must stay the last subtest. + t.Run("an expired invitation shows not_granted", func(t *testing.T) { + candidate := newCandidate("contact-candidate-expired@example.test") + invitation := deliver(orgA, sessionOwnerA, candidate) + var deadline time.Time + if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, invitation.ID).Scan(&deadline); err != nil { + t.Fatalf("read the response deadline: %v", err) + } + harness.clock.Set(deadline) + ownerSession := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()) + candidateSession := loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) + // A read at the deadline expires the invitation before it answers. + read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, "/api/v1/me/invitations/"+invitation.ID.String(), "", candidateSession, ""), http.StatusOK) + if read.State != "expired" { + t.Fatalf("candidate read at the deadline = %+v, want expired", read) + } + expired := requireOrganizationAccess("organization view of an expired invitation", orgA, invitation.ID, ownerSession, "not_granted") + if expired.State != "expired" { + t.Fatalf("expired invitation state = %q, want expired", expired.State) + } + }) +} diff --git a/backend/integration_test/holding_migration_test.go b/backend/integration_test/holding_migration_test.go index dcd25ad..dafe981 100644 --- a/backend/integration_test/holding_migration_test.go +++ b/backend/integration_test/holding_migration_test.go @@ -59,6 +59,9 @@ func TestHoldingsMigrationBackfillsFoundersAndGuardsRollback(t *testing.T) { if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() with the holdings migration error = %v", err) } + // Later migrations sit above holdings: the rollback subtests undo holdings + // with DownOne, so the schema is taken back to the holdings version first. + rollBackAboveMigration(ctx, t, migrator, holdingsMigrationVersion) t.Run("backfill gives each founder one holding dated by its first organization", func(t *testing.T) { firstHolding := legacyHolding(ctx, t, pool, first) diff --git a/backend/integration_test/invitation_answer_http_test.go b/backend/integration_test/invitation_answer_http_test.go index 7c404da..eb443c9 100644 --- a/backend/integration_test/invitation_answer_http_test.go +++ b/backend/integration_test/invitation_answer_http_test.go @@ -418,8 +418,10 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) { if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts != (invitationAnswerCounts{viewedEvents: 1, declinedEvents: 1, declines: 1}) { t.Fatalf("decline from viewed stored %+v", counts) } - // The comment rules of the contract and an unstorable value. - fresh := deliver(orgA, sessionA, target, nil) + // The comment rules of the contract and an unstorable value. The pause + // after the declines above holds their candidates for thirty days, so + // the new invitation goes to a cohort candidate that never declined. + fresh := deliver(orgA, sessionA, cohort[len(cohort)-1], nil) tooLong := strings.Repeat("я", 501) for name, body := range map[string]string{ "white space": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":" "}`, @@ -441,7 +443,10 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) { }) t.Run("another candidate and an employer learn nothing of the invitation", func(t *testing.T) { - sent := deliver(orgA, sessionA, target, nil) + // The sent invitation goes to a cohort candidate that never declined, so + // the pause after the declines above does not apply to it. Only the draft + // below is addressed to the candidate who declined. + sent := deliver(orgA, sessionA, cohort[len(cohort)-2], nil) draft := draftFor(orgA, sessionA, target, nil) for name, invitationID := range map[string]uuid.UUID{"another candidate's": sent.ID, "unknown": uuid.New()} { for _, response := range []*httptest.ResponseRecorder{ @@ -496,10 +501,12 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) { }) t.Run("a stale version is not stored and a late decline is refused whatever the version", func(t *testing.T) { - sent := deliver(orgA, sessionA, other, func(body, terms map[string]any) { body["response_period_days"] = 3 }) + // Hider has no other invitation of this organization, so the pause after + // the declines above does not apply to it. + sent := deliver(orgA, sessionA, hider, func(body, terms map[string]any) { body["response_period_days"] = 3 }) key := nextKey() - requireSessionProblem(t, decline(sessionOther, sent.ID, declineBody(sent.Version+1, "tasks", nil), key), http.StatusPreconditionFailed, "version_conflict") - if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID); counts.declines != 0 { + requireSessionProblem(t, decline(sessionHider, sent.ID, declineBody(sent.Version+1, "tasks", nil), key), http.StatusPreconditionFailed, "version_conflict") + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, hider.ID); counts.declines != 0 { t.Fatalf("a stale decline stored %+v", counts) } var stored int @@ -516,17 +523,20 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) { t.Fatalf("read the deadline: %v", err) } harness.clock.Set(exactDeadline.UTC()) - lateSession := login(other) + lateSession := login(hider) + // The late view applies the due expiry, so it answers with the expired + // invitation and records no view. late := decodeCandidateInvitationHTTP(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", lateSession, ""), http.StatusOK) - if late.State != "delivered" || late.Version != sent.Version || late.ViewedAt != nil { - t.Fatalf("late view = %+v, want the invitation unchanged", late) + if late.State != "expired" || late.ExpiryReason == nil || *late.ExpiryReason != "invitation_timeout" || + late.Version != sent.Version+1 || late.ViewedAt != nil { + t.Fatalf("late view = %+v, want the invitation expired by the timeout without a view", late) } lateKey := nextKey() for range 2 { - requireSessionProblem(t, decline(lateSession, sent.ID, declineBody(sent.Version+3, "tasks", nil), lateKey), http.StatusConflict, "state_conflict") + requireSessionProblem(t, decline(lateSession, sent.ID, declineBody(late.Version+2, "tasks", nil), lateKey), http.StatusConflict, "state_conflict") } requireSessionProblem(t, decline(lateSession, sent.ID, declineBody(sent.Version, "tasks", nil), key), http.StatusConflict, "state_conflict") - if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID); counts != (invitationAnswerCounts{}) { + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, hider.ID); counts != (invitationAnswerCounts{}) { t.Fatalf("late commands stored %+v", counts) } if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM invitation_decline_results WHERE invitation_id = $1 AND outcome = 'state_conflict'`, sent.ID).Scan(&stored); err != nil || stored != 2 { diff --git a/backend/integration_test/invitation_expiry_test.go b/backend/integration_test/invitation_expiry_test.go new file mode 100644 index 0000000..a74d066 --- /dev/null +++ b/backend/integration_test/invitation_expiry_test.go @@ -0,0 +1,551 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "log/slog" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/consent" + identityusecase "lincodex/backend/internal/usecase/identity" + invitationusecase "lincodex/backend/internal/usecase/invitation" + "lincodex/backend/internal/usecase/policy" + "lincodex/backend/internal/worker/jobrunner" + "lincodex/backend/internal/worker/retry" +) + +const ( + // invitationExpiryMigrationVersion adds the pending limit, the pause, and + // the expiry at the response deadline. + invitationExpiryMigrationVersion = 43 + // invitationExpiryJobKind is the kind of the response deadline job. + invitationExpiryJobKind = "invitation.response_deadline" +) + +// noopDeliveryNotifier stands in for the notification outbox: these tests +// check the invitation rules, not the events of a delivery. +type noopDeliveryNotifier struct{} + +func (noopDeliveryNotifier) InvitationDelivered(context.Context, outbound.UnitOfWork, domain.Invitation) error { + return nil +} + +// invitationLimitsFixture drives the invitation usecases against one isolated +// database with the real repositories, quota, consent ledger, and scheduled +// job store. Candidates resolve through a table of handles, because the card +// visibility rules are tested elsewhere. +type invitationLimitsFixture struct { + ctx context.Context + databaseURL string + pool *pgxpool.Pool + transactor *postgresadapter.Transactor + identity identityFixture + organizations organizationFixture + clock *testClock + service *invitationusecase.Service + key domain.CandidateViewPseudonymKey + handles map[string]uuid.UUID + organization domain.Organization + owner domain.User + secondOwner domain.User +} + +func newInvitationLimitsFixture(ctx context.Context, t *testing.T, env *testEnvironment, databaseURL string) invitationLimitsFixture { + t.Helper() + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + // The policy takes effect when it is stored, after the first read of the + // clock, as in the HTTP harness. + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)} + transactor := postgresadapter.NewTransactor(pool) + identities := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()} + organizations := organizationFixture{ctx: ctx, pool: pool, identity: identities, transactor: transactor, now: clock.Now()} + owner := organizations.employer(t, "limits-owner@example.test") + confirmEmail(ctx, t, pool, owner, clock.Now().Add(-time.Minute)) + organization := organizations.create(t, owner, organizations.completeProfile(t, "Limits company"), clock.Now()) + secondOwner := identities.createUser(t, "limits-second-owner@example.test", domain.ScenarioEmployer, clock.Now().Add(-time.Hour)) + confirmEmail(ctx, t, pool, secondOwner, clock.Now().Add(-time.Minute)) + insertOwnerMembership(ctx, t, transactor, organization.ID(), secondOwner.ID, clock.Now()) + + keyring, err := identityusecase.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + key, err := keyring.CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + fixture := invitationLimitsFixture{ + ctx: ctx, databaseURL: databaseURL, pool: pool, transactor: transactor, identity: identities, organizations: organizations, clock: clock, + key: key, handles: map[string]uuid.UUID{}, organization: organization, owner: owner, secondOwner: secondOwner, + } + quota := companyquota.NewService(clock.Now) + service, err := invitationusecase.NewService(invitationusecase.Dependencies{ + Transactor: transactor, Keyring: keyring, PseudonymKey: key, + Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) { + candidateID, ok := fixture.handles[handle] + if !ok || organizationID != organization.ID() { + return uuid.Nil, candidateview.ErrCandidateCardNotFound + } + return candidateID, nil + }, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveInvitation(ctx, unit, organization, invitationID) + }, + Notifier: noopDeliveryNotifier{}, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now, + }) + if err != nil { + t.Fatalf("invitation.NewService() error = %v", err) + } + fixture.service = service + return fixture +} + +// insertOwnerMembership adds an active owner, which the MVP allows beside the +// first one: every owner may send and answer for the organization. +func insertOwnerMembership(ctx context.Context, t *testing.T, transactor *postgresadapter.Transactor, organizationID, userID uuid.UUID, at time.Time) { + t.Helper() + membership, err := domain.NewOwnerMembership(organizationID, userID, at) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + if err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Memberships().Insert(ctx, membership) + }); err != nil { + t.Fatalf("insert owner membership: %v", err) + } +} + +// confirmEmail marks the account's email confirmed at the given time. The +// invitation commands require a confirmed email of both the employer and the +// candidate. +func confirmEmail(ctx context.Context, t *testing.T, pool *pgxpool.Pool, user domain.User, at time.Time) { + t.Helper() + if _, err := pool.Exec(ctx, ` + UPDATE users SET email_verified_at = $2, version = version + 1 WHERE id = $1`, user.ID, at); err != nil { + t.Fatalf("confirm the email of %s: %v", user.ID, err) + } +} + +// candidate makes a candidate account that can sign in and gives it a card +// handle for the organization. +func (fixture *invitationLimitsFixture) candidate(t *testing.T, email string) domain.User { + t.Helper() + user := fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.clock.Now().Add(-time.Hour)) + confirmEmail(fixture.ctx, t, fixture.pool, user, fixture.clock.Now().Add(-time.Minute)) + handle, err := fixture.key.ForOrganization(fixture.organization.ID(), user.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + fixture.handles[handle] = user.ID + return user +} + +func (fixture *invitationLimitsFixture) handleOf(t *testing.T, candidateID uuid.UUID) string { + t.Helper() + handle, err := fixture.key.ForOrganization(fixture.organization.ID(), candidateID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return handle +} + +// need stores a need of the organization with its first requirements version. +func (fixture *invitationLimitsFixture) need(t *testing.T, title string) domain.InvitationNeedRef { + t.Helper() + need := newIntegrationNeed(t, fixture.organization.ID(), title, fixture.clock.Now()) + fixture.organizations.createNeed(t, need) + return domain.InvitationNeedRef{NeedID: need.ID(), RequirementsVersion: need.RequirementsVersion()} +} + +// draft creates a draft for the candidate, under the need when one is given. +func (fixture *invitationLimitsFixture) draft( + t *testing.T, + actor domain.User, + candidateID uuid.UUID, + need *domain.InvitationNeedRef, + period *int32, +) domain.OrganizationInvitationView { + t.Helper() + key := "create-" + uuid.NewString() + view, err := fixture.service.Create(fixture.ctx, invitationusecase.CreateCommand{ + ActorID: actor.ID, OrganizationID: fixture.organization.ID(), IdempotencyKey: key, + CanonicalBody: []byte(fmt.Sprintf(`{"key":%q}`, key)), CandidateHandle: fixture.handleOf(t, candidateID), + Need: need, ResponsePeriodDays: period, Terms: invitationStorageTerms(), + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + return view +} + +func (fixture *invitationLimitsFixture) sendCommand(actor domain.User, view domain.OrganizationInvitationView) invitationusecase.SendCommand { + return invitationusecase.SendCommand{ + ActorID: actor.ID, OrganizationID: fixture.organization.ID(), InvitationID: view.ID, + IdempotencyKey: "send-" + uuid.NewString(), ExpectedVersion: view.Version, + } +} + +// send delivers a draft and fails the test when the send is refused. +func (fixture *invitationLimitsFixture) send(t *testing.T, actor domain.User, view domain.OrganizationInvitationView) domain.OrganizationInvitationView { + t.Helper() + sent, err := fixture.service.Send(fixture.ctx, fixture.sendCommand(actor, view)) + if err != nil { + t.Fatalf("Send() error = %v", err) + } + return sent +} + +// count reads one number of the database, scoped to the organization. +func (fixture *invitationLimitsFixture) count(t *testing.T, query string, args ...any) int64 { + t.Helper() + var value int64 + if err := fixture.pool.QueryRow(fixture.ctx, query, args...).Scan(&value); err != nil { + t.Fatalf("count %q: %v", query, err) + } + return value +} + +// enlargeQuota makes the organization E1, whose weekly invitation quota is +// larger than the E0 quota of the demo policy, so that the pending limit is +// the rule under test. +func (fixture *invitationLimitsFixture) enlargeQuota(t *testing.T) { + t.Helper() + if _, err := fixture.pool.Exec(fixture.ctx, ` + UPDATE organizations + SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2 + WHERE id = $1`, fixture.organization.ID(), fixture.clock.Now()); err != nil { + t.Fatalf("raise the organization to E1: %v", err) + } +} + +func TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) + fixture.enlargeQuota(t) + candidate := fixture.candidate(t, "limits-candidate-pending@example.test") + need := fixture.need(t, "Pending need") + needRef := need + + for index := range 19 { + draft := fixture.draft(t, fixture.owner, candidate.ID, &needRef, nil) + fixture.send(t, fixture.owner, draft) + if index == 18 && fixture.count(t, `SELECT count(*) FROM invitations WHERE need_id = $1 AND state = 'delivered'`, need.NeedID) != 19 { + t.Fatal("nineteen invitations are not waiting") + } + } + first := fixture.draft(t, fixture.owner, candidate.ID, &needRef, nil) + second := fixture.draft(t, fixture.secondOwner, candidate.ID, &needRef, nil) + + var group sync.WaitGroup + results := make([]error, 2) + for index, sender := range []struct { + actor domain.User + view domain.OrganizationInvitationView + }{{fixture.owner, first}, {fixture.secondOwner, second}} { + group.Go(func() { + _, results[index] = fixture.service.Send(ctx, fixture.sendCommand(sender.actor, sender.view)) + }) + } + group.Wait() + + admitted, refused := 0, 0 + for _, err := range results { + switch { + case err == nil: + admitted++ + case errors.Is(err, invitationusecase.ErrSendBlocked): + refused++ + default: + t.Fatalf("concurrent Send() error = %v, want success or ErrSendBlocked", err) + } + } + if admitted != 1 || refused != 1 { + t.Fatalf("admitted %d and refused %d of two sends with nineteen waiting; want one each", admitted, refused) + } + waiting := fixture.count(t, ` + SELECT count(*) FROM invitations + WHERE need_id = $1 AND state IN ('delivered', 'viewed', 'counter')`, need.NeedID) + if waiting != 20 { + t.Fatalf("waiting invitations under the need = %d, want exactly the limit of 20", waiting) + } + if charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, fixture.organization.ID()); charges != 20 { + t.Fatalf("quota charges = %d, want one per admitted send", charges) + } + // The refused draft is still a draft and carries no charge. + refusedDraftState := fixture.count(t, ` + SELECT count(*) FROM invitations + WHERE need_id = $1 AND state = 'draft'`, need.NeedID) + if refusedDraftState != 1 { + t.Fatalf("drafts under the need = %d, want the refused draft only", refusedDraftState) + } +} + +func TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) + candidate := fixture.candidate(t, "limits-candidate-pause@example.test") + firstNeed := fixture.need(t, "Declined need") + secondNeed := fixture.need(t, "Another need") + + // The candidate receives and declines an invitation under the first need. + first := fixture.draft(t, fixture.owner, candidate.ID, &firstNeed, nil) + sent := fixture.send(t, fixture.owner, first) + declinedAt := sent.DeliveredAt.Add(time.Hour) + fixture.clock.Set(declinedAt) + if _, err := fixture.service.DeclineMine(ctx, invitationusecase.DeclineCommand{ + ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "decline-pause", ExpectedVersion: sent.Version, + Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther}, + }); err != nil { + t.Fatalf("DeclineMine() error = %v", err) + } + + // Another owner of the same organization sends under another need. + next := fixture.draft(t, fixture.secondOwner, candidate.ID, &secondNeed, nil) + fixture.clock.Set(declinedAt.Add(29 * 24 * time.Hour)) + if _, err := fixture.service.Send(ctx, fixture.sendCommand(fixture.secondOwner, next)); !errors.Is(err, invitationusecase.ErrSendBlocked) { + t.Fatalf("Send(day 29 after the decline) error = %v, want ErrSendBlocked", err) + } + if state := fixture.count(t, `SELECT count(*) FROM invitations WHERE id = $1 AND state = 'draft'`, next.ID); state != 1 { + t.Fatal("a send refused by the pause changed the draft") + } + + // The same draft goes out on day 30, with a new key. + fixture.clock.Set(declinedAt.Add(30 * 24 * time.Hour)) + if view, err := fixture.service.Send(ctx, fixture.sendCommand(fixture.secondOwner, next)); err != nil || view.State != domain.InvitationDelivered { + t.Fatalf("Send(day 30 after the decline) = %v, %v; want delivered", view.State, err) + } +} + +func TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) + threeDays := int32(3) + + // Each round delivers a fresh invitation with a three-day deadline and lets + // an acceptance at the deadline race the expiry job. + for round := range 3 { + candidate := fixture.candidate(t, fmt.Sprintf("limits-candidate-race-%d@example.test", round)) + draft := fixture.draft(t, fixture.owner, candidate.ID, nil, &threeDays) + sent := fixture.send(t, fixture.owner, draft) + deadline := *sent.ResponseDeadlineAt + charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, sent.ID) + + worker := newDeadlineJobWorker(ctx, t, fixture.databaseURL, fixture.clock) + fixture.clock.Set(deadline) + acceptCommand := invitationusecase.AcceptCommand{ + ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "accept-" + uuid.NewString(), + ExpectedVersion: sent.Version, TermsVersion: sent.TermsVersion, TextVersion: "c4-2026-10-01", + Fields: []domain.ContactField{domain.ContactFieldEmail}, + } + var group sync.WaitGroup + var acceptErr error + var runErr error + group.Go(func() { + _, acceptErr = fixture.service.AcceptMine(ctx, acceptCommand) + }) + group.Go(func() { + _, runErr = worker.RunDue(ctx) + }) + group.Wait() + if runErr != nil { + t.Fatalf("round %d: RunDue() error = %v", round, runErr) + } + if !errors.Is(acceptErr, invitationusecase.ErrAnswerBlocked) { + t.Fatalf("round %d: AcceptMine(at the deadline) error = %v, want ErrAnswerBlocked", round, acceptErr) + } + + assertExpiredAtDeadline(t, fixture, sent.ID, deadline, charges) + if grants := fixture.count(t, `SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1`, sent.ID); grants != 0 { + t.Fatalf("round %d: %d contact grants after a late acceptance, want none", round, grants) + } + if consents := fixture.count(t, `SELECT count(*) FROM consent_records WHERE invitation_id = $1 AND purpose = 'c4'`, sent.ID); consents != 0 { + t.Fatalf("round %d: %d consent C4 records after a late acceptance, want none", round, consents) + } + var jobStatus string + var jobError *string + if err := fixture.pool.QueryRow(ctx, `SELECT status, last_error_class FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2`, + invitationExpiryJobKind, sent.ID.String()).Scan(&jobStatus, &jobError); err != nil { + t.Fatalf("round %d: read the deadline job: %v", round, err) + } + if jobStatus != "done" { + t.Fatalf("round %d: the deadline job is %s with error %v, want done", round, jobStatus, jobError) + } + } +} + +func TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) + threeDays := int32(3) + candidate := fixture.candidate(t, "limits-candidate-job-first@example.test") + draft := fixture.draft(t, fixture.owner, candidate.ID, nil, &threeDays) + sent := fixture.send(t, fixture.owner, draft) + deadline := *sent.ResponseDeadlineAt + charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, sent.ID) + + // The job runs first at its due time and expires the invitation. + fixture.clock.Set(deadline) + worker := newDeadlineJobWorker(ctx, t, fixture.databaseURL, fixture.clock) + if _, err := worker.RunDue(ctx); err != nil { + t.Fatalf("RunDue() error = %v", err) + } + assertExpiredAtDeadline(t, fixture, sent.ID, deadline, charges) + + // The acceptance that arrives afterwards finds the expiry and grants nothing. + _, err := fixture.service.AcceptMine(ctx, invitationusecase.AcceptCommand{ + ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "accept-after-job", + ExpectedVersion: sent.Version, TermsVersion: sent.TermsVersion, TextVersion: "c4-2026-10-01", + Fields: []domain.ContactField{domain.ContactFieldEmail}, + }) + if !errors.Is(err, invitationusecase.ErrAnswerBlocked) { + t.Fatalf("AcceptMine(after the job) error = %v, want ErrAnswerBlocked", err) + } + if grants := fixture.count(t, `SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1`, sent.ID); grants != 0 { + t.Fatalf("contact grants = %d after the job won, want none", grants) + } + if events := fixture.count(t, `SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'expired'`, sent.ID); events != 1 { + t.Fatalf("expiry events = %d, want one", events) + } +} + +// newDeadlineJobWorker builds the scheduled job worker with the response +// deadline handler, against the store of the isolated test database and the +// fixture clock, as the application does. +func newDeadlineJobWorker(ctx context.Context, t *testing.T, databaseURL string, clock *testClock) *jobrunner.Worker { + t.Helper() + pool := newPoolFor(ctx, t, databaseURL) + settings := jobrunner.Settings{ + BatchSize: 10, PollInterval: 10 * time.Millisecond, Lease: time.Minute, MaxAttempts: 3, + Backoff: retry.Backoff{Initial: time.Millisecond, Max: time.Millisecond}, + ShutdownGrace: time.Second, StoreTimeout: 5 * time.Second, BacklogInterval: time.Second, + } + worker, err := jobrunner.New( + []inbound.JobHandler{invitationusecase.NewResponseDeadlineJob(clock.Now)}, + postgresadapter.NewScheduledJobStore(pool, settings.Lease), prometheus.New(), slog.New(slog.DiscardHandler), settings, clock.Now, + ) + if err != nil { + t.Fatalf("jobrunner.New() error = %v", err) + } + return worker +} + +// assertExpiredAtDeadline checks the stored state of an expired invitation: the +// deadline and terms are kept, the timeout reason is set, the audit event has +// no actor, and the quota charge is unchanged. +func assertExpiredAtDeadline(t *testing.T, fixture invitationLimitsFixture, invitationID uuid.UUID, deadline time.Time, charges int64) { + t.Helper() + var state, reason string + var storedDeadline time.Time + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT state, expiry_reason, response_deadline_at FROM invitations WHERE id = $1`, invitationID).Scan(&state, &reason, &storedDeadline); err != nil { + t.Fatalf("read invitation: %v", err) + } + if state != string(domain.InvitationExpired) || reason != string(domain.InvitationExpiryTimeout) || !storedDeadline.Equal(deadline) { + t.Fatalf("invitation = %s/%s deadline %v, want expired by the timeout at %v", state, reason, storedDeadline, deadline) + } + events := fixture.count(t, ` + SELECT count(*) FROM invitation_events + WHERE invitation_id = $1 AND kind = 'expired' AND actor_id IS NULL AND cardinality(changed_fields) = 0`, invitationID) + if events != 1 { + t.Fatalf("expiry events without an actor = %d, want one", events) + } + if stored := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, invitationID); stored != charges { + t.Fatalf("quota charges of the invitation = %d, want the %d of the send", stored, charges) + } +} + +func TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) + rollBackAboveVersion(ctx, t, migrator, invitationExpiryMigrationVersion-1) + + // A delivery made before the migration has no deadline job yet. + draft := fixture.draft(t) + delivered, err := draft.Deliver(draft.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + event, err := delivered.DeliveryEvent(fixture.owner.ID) + if err != nil { + t.Fatalf("DeliveryEvent() error = %v", err) + } + if err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) + }); err != nil { + t.Fatalf("Deliver() through the repository error = %v", err) + } + deadline := *delivered.Snapshot().ResponseDeadlineAt + + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up(43) error = %v", err) + } + var jobs int + var dueAt time.Time + if err := pool.QueryRow(ctx, ` + SELECT count(*), coalesce(max(due_at), now()) + FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2 AND status = 'pending'`, + invitationExpiryJobKind, delivered.ID().String()).Scan(&jobs, &dueAt); err != nil { + t.Fatalf("read the backfilled job: %v", err) + } + if jobs != 1 || !dueAt.Equal(deadline) { + t.Fatalf("backfilled jobs = %d due %v, want one due at the deadline %v", jobs, dueAt, deadline) + } + + // The trigger refuses an expiry that is recorded before the deadline, and + // an expiry of an invitation that is not waiting for an answer. + if _, err := pool.Exec(ctx, ` + UPDATE invitations + SET state = 'expired', expiry_reason = 'invitation_timeout', version = version + 1, updated_at = $2 + WHERE id = $1`, delivered.ID(), deadline.Add(-time.Second)); err == nil { + t.Fatal("an expiry before the deadline was stored") + } + if _, err := pool.Exec(ctx, ` + UPDATE invitations + SET state = 'expired', expiry_reason = 'invitation_timeout', version = version + 1, updated_at = $2 + WHERE id = $1`, delivered.ID(), deadline); err != nil { + t.Fatalf("expiry at the deadline error = %v", err) + } + + // A rollback keeps the expiry, which the previous schema cannot represent. + if _, err := migrator.DownOne(ctx); err == nil { + t.Fatal("rollback with an expired invitation succeeded, want it refused") + } + var expired int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM invitations WHERE state = 'expired'`).Scan(&expired); err != nil || expired != 1 { + t.Fatalf("expired invitations after the refused rollback = %d, %v; want the stored expiry", expired, err) + } +} diff --git a/backend/integration_test/invitation_http_test.go b/backend/integration_test/invitation_http_test.go index bc8d194..743d2c7 100644 --- a/backend/integration_test/invitation_http_test.go +++ b/backend/integration_test/invitation_http_test.go @@ -28,6 +28,7 @@ import ( "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/candidateprivacy" "lincodex/backend/internal/usecase/candidateview" "lincodex/backend/internal/usecase/companyquota" "lincodex/backend/internal/usecase/consent" @@ -130,16 +131,25 @@ func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnviro if err != nil { t.Fatalf("notification.NewInboxService() error = %v", err) } + // The consent and the visibility operations are served too, so the contact + // read can be revoked through the same routes a candidate uses. + privacySettings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock.Now}) + if err != nil { + t.Fatalf("candidateprivacy.NewService() error = %v", err) + } logs := &strings.Builder{} logger := slog.New(slog.NewJSONHandler(logs, nil)) responder := problem.NewResponder(logger) healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessionService), v1.WithPublicOrigin(env.Config.AppPublicURL)) organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + consentHandler := v1.NewConsentHandler(consent.NewQueryService(postgresadapter.NewConsentStore(pool), clock.Now), consent.NewService(transactor, clock.Now)) + privacyHandler := v1.NewPrivacyHandler(views, privacySettings, env.Config.AppPublicURL) handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), v1.WithNeed(v1.NewNeedHandler(needService)), v1.WithInvitation(v1.NewInvitationHandler(invitationService)), v1.WithNotifications(v1.NewNotificationHandler(inbox)), + v1.WithConsent(consentHandler), v1.WithPrivacy(privacyHandler), ) router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler)) 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 883be10..4062c68 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -14035,8 +14035,8 @@ func (s *Server) handleSearchOrganizationMatchesRequest(args [1]string, argsEsca // answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the // organization and the candidate after a decline or a no deal, regardless of the member or the need, // both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and -// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are -// not checked yet. +// Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced; +// the pause after a no deal is planned, because no operation produces the state `no_deal` yet. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a send of an invitation that was already sent answers 200 with the invitation in its current 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 1d37895..9b4dd32 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -1725,8 +1725,8 @@ type Handler interface { // answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the // organization and the candidate after a decline or a no deal, regardless of the member or the need, // both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and - // Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are - // not checked yet. + // Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced; + // the pause after a no deal is planned, because no operation produces the state `no_deal` yet. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a send of an invitation that was already sent answers 200 with the invitation in its current 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 886174d..54d022f 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -1916,8 +1916,8 @@ func (UnimplementedHandler) SearchOrganizationMatches(ctx context.Context, req M // answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the // organization and the candidate after a decline or a no deal, regardless of the member or the need, // both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and -// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are -// not checked yet. +// Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced; +// the pause after a no deal is planned, because no operation produces the state `no_deal` yet. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a send of an invitation that was already sent answers 200 with the invitation in its current diff --git a/backend/internal/adapter/primary/http/v1/contacts.go b/backend/internal/adapter/primary/http/v1/contacts.go new file mode 100644 index 0000000..8a215e6 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/contacts.go @@ -0,0 +1,91 @@ +package v1 + +import ( + "context" + "errors" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func (handler *Handler) GetOrganizationInvitationContacts(ctx context.Context, params api.GetOrganizationInvitationContactsParams) (api.GetOrganizationInvitationContactsRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.GetOrganizationInvitationContacts(ctx, params) + } + return handler.invitation.GetOrganizationInvitationContacts(ctx, params) +} + +// GetOrganizationInvitationContacts serves the only operation that returns +// contact values. The company middleware has already checked the session, the +// owner membership, and the path, and the usecase repeats the owner check in +// its transaction. Every failure of the grant read answers the same not found, +// so the response never tells which condition applies. +func (handler *InvitationHandler) GetOrganizationInvitationContacts( + ctx context.Context, + params api.GetOrganizationInvitationContactsParams, +) (api.GetOrganizationInvitationContactsRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.GetOrganizationInvitationContactsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + disclosure, err := handler.operations.ReadContacts(ctx, principal.UserID, params.OrgID, params.InvitationID) + if err != nil { + return contactsReadFailure(ctx, err) + } + return &api.ContactDisclosureHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: contactDisclosureResponse(disclosure)}, nil +} + +func contactsReadFailure(ctx context.Context, err error) (api.GetOrganizationInvitationContactsRes, error) { + // A missing grant is the not found of the contract. It is handled before the + // shared classification, which treats an unexpected missing grant as a + // storage defect on the other invitation paths. + if errors.Is(err, outbound.ErrContactGrantNotFound) { + return (*api.GetOrganizationInvitationContactsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + } + switch classifyInvitationError(err) { + case invitationFailureForbidden: + return (*api.GetOrganizationInvitationContactsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case invitationFailureNotFound: + return (*api.GetOrganizationInvitationContactsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case invitationFailureKeyReused, invitationFailureBadKey, invitationFailureInvalid, + invitationFailureVersionConflict, invitationFailureStateConflict, invitationFailureOther: + return nil, err + } + return nil, err +} + +// contactDisclosureResponse maps the disclosure field by field. A kind that the +// grant does not cover, or that the profile no longer holds, is null. +func contactDisclosureResponse(disclosure domain.ContactDisclosure) api.ContactDisclosure { + fields := make([]api.ContactFieldKind, 0, len(disclosure.Fields())) + for _, field := range disclosure.Fields() { + fields = append(fields, api.ContactFieldKind(field)) + } + response := api.ContactDisclosure{ + InvitationID: disclosure.InvitationID(), GrantID: disclosure.GrantID(), + Fields: fields, GrantedAt: api.Timestamp(disclosure.GrantedAt()), + } + if value, present := disclosure.FullName(); present { + response.FullName = api.NewNilContactFullName(api.ContactFullName(value)) + } else { + response.FullName.SetToNull() + } + if value, present := disclosure.Email(); present { + response.Email = api.NewNilEmailAddress(api.EmailAddress(value)) + } else { + response.Email.SetToNull() + } + if value, present := disclosure.Phone(); present { + response.Phone = api.NewNilContactPhoneNumber(api.ContactPhoneNumber(value)) + } else { + response.Phone.SetToNull() + } + if value, present := disclosure.Telegram(); present { + response.Telegram = api.NewNilContactTelegramUsername(api.ContactTelegramUsername(value)) + } else { + response.Telegram.SetToNull() + } + return response +} diff --git a/backend/internal/adapter/primary/http/v1/invitation.go b/backend/internal/adapter/primary/http/v1/invitation.go index 8268a46..7ab9187 100644 --- a/backend/internal/adapter/primary/http/v1/invitation.go +++ b/backend/internal/adapter/primary/http/v1/invitation.go @@ -31,6 +31,7 @@ type InvitationOperations interface { ViewMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) DeclineMine(ctx context.Context, command invitationusecase.DeclineCommand) (domain.CandidateInvitationView, error) AcceptMine(ctx context.Context, command invitationusecase.AcceptCommand) (domain.CandidateInvitationView, error) + ReadContacts(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.ContactDisclosure, error) } // InvitationHandler serves the organization side of invitation drafts and @@ -590,10 +591,14 @@ func nullableTimestamp(value *time.Time) api.NilTimestamp { return response } -func invitationContactAccessResponse(access domain.InvitationContactAccess) api.InvitationContactAccess { - // No contact grant exists before an acceptance, so no kind of contact is - // listed and no contact value is ever part of this response. - return api.InvitationContactAccess{Status: api.InvitationContactAccessState(access), Fields: []api.ContactFieldKind{}} +func invitationContactAccessResponse(access domain.InvitationContactAccessView) api.InvitationContactAccess { + // The usecase lists kinds only while the access is available. The kinds + // name the contact read; no contact value is ever part of this response. + fields := make([]api.ContactFieldKind, 0, len(access.Fields)) + for _, field := range access.Fields { + fields = append(fields, api.ContactFieldKind(field)) + } + return api.InvitationContactAccess{Status: api.InvitationContactAccessState(access.Status), Fields: fields} } func organizationInvitationResponse(view domain.OrganizationInvitationView) api.OrganizationInvitation { diff --git a/backend/internal/adapter/primary/http/v1/invitation_test.go b/backend/internal/adapter/primary/http/v1/invitation_test.go index 0ff2054..1bef514 100644 --- a/backend/internal/adapter/primary/http/v1/invitation_test.go +++ b/backend/internal/adapter/primary/http/v1/invitation_test.go @@ -83,7 +83,8 @@ func TestInvitationResponseNeverCarriesACandidateIdentifierOrAContact(t *testing } view := domain.OrganizationInvitationView{ InvitationSnapshot: draft.Snapshot(), CandidateHandle: "cv1_" + strings.Repeat("A", 43), - SalaryFit: domain.InvitationSalaryNotAvailable, ContactAccess: domain.InvitationContactAccessNone, + SalaryFit: domain.InvitationSalaryNotAvailable, + ContactAccess: domain.NewInvitationContactAccessView(domain.InvitationContactAccessNone, nil), } for name, response := range map[string]any{ "invitation": organizationInvitationResponse(view), diff --git a/backend/internal/adapter/secondary/postgres/consent_revocation.go b/backend/internal/adapter/secondary/postgres/consent_revocation.go index 5993048..c6e9703 100644 --- a/backend/internal/adapter/secondary/postgres/consent_revocation.go +++ b/backend/internal/adapter/secondary/postgres/consent_revocation.go @@ -94,6 +94,9 @@ func (effects consentRevocationEffects) Apply( return fmt.Errorf("consentRevocationEffects.Apply - close publication: %w", err) } } + if err := effects.closeContactGrants(ctx, revocation, records); err != nil { + return fmt.Errorf("consentRevocationEffects.Apply - close contact grants: %w", err) + } if err := effects.appendRevocationIntent(ctx, revocation, records); err != nil { return fmt.Errorf("consentRevocationEffects.Apply - append outbox intent: %w", err) } @@ -145,6 +148,42 @@ func (effects consentRevocationEffects) closePublication( return nil } +// closeContactGrants closes the grants that the revoked consent gave. A C2 +// revocation closes every grant of the candidate, because it closes the +// profile for every organization, whether or not a publication row exists. A +// C4 revocation closes the grants of its organization that name the revoked +// records, so the grants of other organizations and other invitations stay. +func (effects consentRevocationEffects) closeContactGrants( + ctx context.Context, + revocation domain.ConsentRevocation, + records []domain.ConsentRecord, +) error { + const location = "consentRevocationEffects.closeContactGrants" + switch revocation.Purpose() { + case domain.ConsentPurposePublication: + return closeActiveContactGrants(ctx, effects.queries, contactGrantClosure{ + candidateID: revocation.SubjectID(), reason: domain.ContactRevocationVisibilityClosed, + at: revocation.RevokedAt(), + }) + case domain.ConsentPurposeContactDisclosure: + recordIDs := make([]uuid.UUID, 0, len(records)) + for _, record := range records { + recordIDs = append(recordIDs, record.ID()) + } + if len(recordIDs) == 0 { + return fmt.Errorf("%s - revoked C4 record IDs are required: %w", location, domain.ErrInvalidConsent) + } + return closeActiveContactGrants(ctx, effects.queries, contactGrantClosure{ + candidateID: revocation.SubjectID(), organizationID: revocation.OrganizationID(), + consentRecordIDs: recordIDs, reason: domain.ContactRevocationConsentRevoked, at: revocation.RevokedAt(), + }) + case domain.ConsentPurposePersonalData, domain.ConsentPurposeAutoCategorization, domain.ConsentPurposeFSPImport: + // These purposes never gave a contact grant, so their revocation closes none. + return nil + } + return fmt.Errorf("%s - purpose %q has no grant rule: %w", location, revocation.Purpose(), domain.ErrInvalidConsent) +} + type consentRevocationPayload struct { RevocationID uuid.UUID `json:"revocation_id"` RecordID uuid.UUID `json:"record_id"` diff --git a/backend/internal/adapter/secondary/postgres/contact_grant_closure.go b/backend/internal/adapter/secondary/postgres/contact_grant_closure.go new file mode 100644 index 0000000..69a57cb --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/contact_grant_closure.go @@ -0,0 +1,56 @@ +package postgres + +import ( + "context" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgtype" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" +) + +// contactGrantClosure names the active grants that one change closes. The +// caller runs it in the transaction of the change, so the grants and the change +// commit or roll back together. +type contactGrantClosure struct { + candidateID uuid.UUID + // organizationID limits the closure to one organization. Nil closes every + // organization of the candidate. + organizationID uuid.UUID + // consentRecordIDs limits the closure to the grants that these C4 records + // gave. Nil applies no record filter. + consentRecordIDs []uuid.UUID + reason domain.ContactRevocationReason + at time.Time +} + +// closeActiveContactGrants stamps the active grants of the closure with its +// reason and time. A grant already closed keeps its first stamp, and the +// revocation time is never earlier than the grant time, as the grant requires. +func closeActiveContactGrants(ctx context.Context, queries *sqlc.Queries, closure contactGrantClosure) error { + const location = "postgres.closeActiveContactGrants" + if closure.candidateID == uuid.Nil || closure.at.IsZero() || closure.reason == "" { + return fmt.Errorf("%s - candidate, time, and reason are required: %w", location, domain.ErrInvalidContactGrant) + } + params := sqlc.CloseActiveContactGrantsParams{ + RevokedAt: pgTime(closure.at), + RevocationReason: pgtype.Text{String: string(closure.reason), Valid: true}, + CandidateID: pgUUID(closure.candidateID), + } + if closure.organizationID != uuid.Nil { + params.OrganizationID = pgUUID(closure.organizationID) + } + if closure.consentRecordIDs != nil { + params.ConsentRecordIds = make([]pgtype.UUID, 0, len(closure.consentRecordIDs)) + for _, id := range closure.consentRecordIDs { + params.ConsentRecordIds = append(params.ConsentRecordIds, pgUUID(id)) + } + } + if _, err := queries.CloseActiveContactGrants(ctx, params); err != nil { + return fmt.Errorf("%s - close active grants: %w", location, markTransactionConflict(sanitizeConnectError(err))) + } + return nil +} diff --git a/backend/internal/adapter/secondary/postgres/invitation_accept.go b/backend/internal/adapter/secondary/postgres/invitation_accept.go index 75beea1..51799c7 100644 --- a/backend/internal/adapter/secondary/postgres/invitation_accept.go +++ b/backend/internal/adapter/secondary/postgres/invitation_accept.go @@ -207,3 +207,48 @@ func storedContactGrantRow(row sqlc.ContactGrant) (domain.StoredContactGrant, er } return stored, nil } + +// LockForRead locks the C4 record before the grant, the order of the consent +// revocation, so a read and a revocation of the same consent cannot wait for +// each other in opposite orders. The locked grant is restored through the +// domain like GetByInvitation, and it must still name the grant that was read. +func (repository contactGrantRepository) LockForRead( + ctx context.Context, + grant domain.ContactGrant, +) (domain.ContactGrant, bool, error) { + const location = "contactGrantRepository.LockForRead" + if grant.IsZero() { + return domain.ContactGrant{}, false, fmt.Errorf("%s - grant must be built by the domain: %w", location, domain.ErrInvalidContactGrant) + } + consentCurrent := true + _, err := repository.queries.LockCurrentContactConsentRecord(ctx, sqlc.LockCurrentContactConsentRecordParams{ + ConsentRecordID: pgUUID(grant.ConsentRecordID()), CandidateID: pgUUID(grant.CandidateID()), + OrganizationID: pgUUID(grant.OrganizationID()), + }) + switch { + case errors.Is(err, pgx.ErrNoRows): + consentCurrent = false + case err != nil: + return domain.ContactGrant{}, false, fmt.Errorf("%s - lock consent C4 record: %w", location, mapInvitationError(err)) + } + row, err := repository.queries.LockContactGrant(ctx, pgUUID(grant.ID())) + if errors.Is(err, pgx.ErrNoRows) { + return domain.ContactGrant{}, false, fmt.Errorf("%s - lock contact grant: %w", location, outbound.ErrContactGrantNotFound) + } + if err != nil { + return domain.ContactGrant{}, false, fmt.Errorf("%s - lock contact grant: %w", location, mapInvitationError(err)) + } + stored, err := storedContactGrantRow(row) + if err != nil { + return domain.ContactGrant{}, false, fmt.Errorf("%s - read stored grant: %w", location, err) + } + current, err := domain.RestoreContactGrant(stored) + if err != nil { + return domain.ContactGrant{}, false, fmt.Errorf("%s - restore contact grant: %w", location, err) + } + if current.OrganizationID() != grant.OrganizationID() || current.CandidateID() != grant.CandidateID() || + current.InvitationID() != grant.InvitationID() || current.ConsentRecordID() != grant.ConsentRecordID() { + return domain.ContactGrant{}, false, fmt.Errorf("%s - locked grant has another scope: %w", location, domain.ErrInvalidContactGrant) + } + return current, consentCurrent, nil +} diff --git a/backend/internal/adapter/secondary/postgres/invitation_expiry.go b/backend/internal/adapter/secondary/postgres/invitation_expiry.go new file mode 100644 index 0000000..17bfba7 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/invitation_expiry.go @@ -0,0 +1,115 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// CountPendingNeedInvitations counts the waiting invitations of one need. The +// count is only exact under the organization lock, which the caller holds. +func (repository invitationRepository) CountPendingNeedInvitations( + ctx context.Context, + organizationID, needID uuid.UUID, +) (int64, error) { + const location = "invitationRepository.CountPendingNeedInvitations" + if organizationID == uuid.Nil || needID == uuid.Nil { + return 0, fmt.Errorf("%s - organization and need IDs must be set: %w", location, domain.ErrInvalidInvitation) + } + count, err := repository.queries.CountPendingNeedInvitations(ctx, sqlc.CountPendingNeedInvitationsParams{ + OrganizationID: pgUUID(organizationID), NeedID: pgUUID(needID), + }) + if err != nil { + return 0, fmt.Errorf("%s - count pending invitations: %w", location, mapInvitationError(err)) + } + return count, nil +} + +// LatestDeclineTime reads the latest decline of the pair of the organization +// and the candidate. It reports false when the pair has none. +func (repository invitationRepository) LatestDeclineTime( + ctx context.Context, + organizationID, candidateID uuid.UUID, +) (time.Time, bool, error) { + const location = "invitationRepository.LatestDeclineTime" + if organizationID == uuid.Nil || candidateID == uuid.Nil { + return time.Time{}, false, fmt.Errorf("%s - organization and candidate IDs must be set: %w", location, domain.ErrInvalidInvitation) + } + declinedAt, err := repository.queries.LatestInvitationDecline(ctx, sqlc.LatestInvitationDeclineParams{ + OrganizationID: pgUUID(organizationID), CandidateID: pgUUID(candidateID), + }) + if errors.Is(err, pgx.ErrNoRows) { + return time.Time{}, false, nil + } + if err != nil { + return time.Time{}, false, fmt.Errorf("%s - read latest decline: %w", location, mapInvitationError(err)) + } + if !declinedAt.Valid { + return time.Time{}, false, fmt.Errorf("%s - declined invitation has no answer time: %w", location, domain.ErrInvalidInvitation) + } + return declinedAt.Time.UTC(), true, nil +} + +// GetForDeadline locks the invitation row first and reads it with its scope +// afterwards, as the other locking reads of invitations do. +func (repository invitationRepository) GetForDeadline( + ctx context.Context, + invitationID uuid.UUID, +) (domain.Invitation, error) { + const location = "invitationRepository.GetForDeadline" + if invitationID == uuid.Nil { + return domain.Invitation{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidInvitation) + } + organizationID, err := repository.queries.LockInvitationByID(ctx, pgUUID(invitationID)) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - lock invitation: %w", location, mapInvitationNoRows(err)) + } + if !organizationID.Valid { + return domain.Invitation{}, fmt.Errorf("%s - invitation has no organization: %w", location, domain.ErrInvalidInvitation) + } + invitation, err := repository.Get(ctx, uuid.UUID(organizationID.Bytes), invitationID) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - read locked invitation: %w", location, err) + } + return invitation, nil +} + +// Expire stores the expired version. The conditional update is the +// compare-and-swap that makes the expiry idempotent: a row that another +// transaction already answered or expired, or whose deadline has not passed at +// the expiry time, matches nothing and the caller learns of the conflict. +func (repository invitationRepository) Expire( + ctx context.Context, + expectedVersion int64, + next domain.Invitation, + event domain.InvitationEvent, +) error { + const location = "invitationRepository.Expire" + stored := next.Stored() + if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationExpired) || + stored.ExpiryReason == nil || event.Kind != domain.InvitationEventExpired { + return fmt.Errorf("%s - the next version must be the expiry that follows the expected one: %w", location, domain.ErrInvalidInvitation) + } + if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil { + return err + } + _, err := repository.queries.ExpireInvitation(ctx, sqlc.ExpireInvitationParams{ + NextVersion: stored.Version, ExpiredAt: pgTime(stored.UpdatedAt), OrganizationID: pgUUID(stored.OrganizationID), + InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, + }) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s - expire invitation: %w", location, outbound.ErrInvitationVersionConflict) + } + if err != nil { + return fmt.Errorf("%s - expire invitation: %w", location, mapInvitationError(err)) + } + return repository.insertEvent(ctx, location, event) +} diff --git a/backend/internal/adapter/secondary/postgres/invitations.go b/backend/internal/adapter/secondary/postgres/invitations.go index 7f7e228..20cc394 100644 --- a/backend/internal/adapter/secondary/postgres/invitations.go +++ b/backend/internal/adapter/secondary/postgres/invitations.go @@ -268,15 +268,17 @@ func (repository invitationRepository) GetCreationResult( } // insertEventPrerequisites checks that the audit event describes the version -// that the caller is about to store. +// that the caller is about to store. Only the server's expiry has no actor. func (repository invitationRepository) insertEventPrerequisites( location string, invitation domain.Invitation, event domain.InvitationEvent, version int64, ) error { + actorMissing := event.ActorID == uuid.Nil if event.ID == uuid.Nil || event.InvitationID != invitation.ID() || event.OrganizationID != invitation.OrganizationID() || - event.Version != version || event.TermsVersion != invitation.TermsVersion() || event.ActorID == uuid.Nil || + event.Version != version || event.TermsVersion != invitation.TermsVersion() || + actorMissing != (event.Kind == domain.InvitationEventExpired) || !validStoredInvitationTime(event.OccurredAt) { return fmt.Errorf("%s - the audit event does not describe the stored version: %w", location, domain.ErrInvalidInvitation) } @@ -311,9 +313,14 @@ func (repository invitationRepository) insertEvent(ctx context.Context, location fields = append(fields, string(field)) } slices.Sort(fields) + // The expiry is the server's own change, so its event has no actor. + actor := pgtype.UUID{} + if event.ActorID != uuid.Nil { + actor = pgUUID(event.ActorID) + } if err := repository.queries.InsertInvitationEvent(ctx, sqlc.InsertInvitationEventParams{ ID: pgUUID(event.ID), InvitationID: pgUUID(event.InvitationID), OrganizationID: pgUUID(event.OrganizationID), - Version: event.Version, TermsVersion: event.TermsVersion, Kind: string(event.Kind), ActorID: pgUUID(event.ActorID), + Version: event.Version, TermsVersion: event.TermsVersion, Kind: string(event.Kind), ActorID: actor, ChangedFields: fields, OccurredAt: pgTime(event.OccurredAt), }); err != nil { return fmt.Errorf("%s - record audit event: %w", location, mapInvitationError(err)) diff --git a/backend/internal/adapter/secondary/postgres/privacy_view.go b/backend/internal/adapter/secondary/postgres/privacy_view.go index fd5c41c..fd0443b 100644 --- a/backend/internal/adapter/secondary/postgres/privacy_view.go +++ b/backend/internal/adapter/secondary/postgres/privacy_view.go @@ -17,15 +17,28 @@ import ( var _ outbound.PrivacyViewRepository = privacyCohortRepository{} -// CurrentFields stays closed until invitation grants have transaction-bound -// persistence. The C4 ledger alone does not identify a live invitation grant. +// CurrentFields stays closed. The card-handle contact read has no contract +// operation; contact values are read only through the invitation grant of +// GetOrganizationInvitationContacts, which locks its own grant and C4 record. func (privacyCohortRepository) CurrentFields(context.Context, uuid.UUID, uuid.UUID) (domain.ContactFieldSet, error) { return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed } -func (privacyCohortRepository) CloseForVisibility(context.Context, uuid.UUID, uuid.UUID, time.Time) error { - // No C4 contact-grant persistence exists in this release. Contact reads are - // closed by default, so there is no persisted grant to reactivate later. +// CloseForVisibility closes the active grants of the candidate, or of one +// organization when organizationID is set, with the reason visibility_closed. +// The publication and the hiding call it in their own transactions. +func (repository privacyCohortRepository) CloseForVisibility( + ctx context.Context, + candidateID, organizationID uuid.UUID, + at time.Time, +) error { + const location = "privacyCohortRepository.CloseForVisibility" + if err := closeActiveContactGrants(ctx, repository.queries, contactGrantClosure{ + candidateID: candidateID, organizationID: organizationID, + reason: domain.ContactRevocationVisibilityClosed, at: at, + }); err != nil { + return fmt.Errorf("%s - close contact grants: %w", location, err) + } return nil } diff --git a/backend/internal/adapter/secondary/postgres/sqlc/contact_grants.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/contact_grants.sql.go index 04299be..129cbb1 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/contact_grants.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/contact_grants.sql.go @@ -11,6 +11,60 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const closeActiveContactGrants = `-- name: CloseActiveContactGrants :execrows +WITH targets AS ( + SELECT contact_grants.id + FROM contact_grants + WHERE + contact_grants.candidate_id = $3 + AND ( + $4::uuid IS NULL + OR contact_grants.organization_id = $4::uuid + ) + AND ( + $5::uuid [] IS NULL + OR contact_grants.consent_record_id = ANY($5::uuid []) + ) + AND contact_grants.revoked_at IS NULL + ORDER BY contact_grants.id + FOR NO KEY UPDATE +) +UPDATE contact_grants +SET + revoked_at = greatest(contact_grants.granted_at, $1::timestamptz), + revocation_reason = $2 +FROM targets +WHERE contact_grants.id = targets.id +` + +type CloseActiveContactGrantsParams struct { + RevokedAt pgtype.Timestamptz + RevocationReason pgtype.Text + CandidateID pgtype.UUID + OrganizationID pgtype.UUID + ConsentRecordIds []pgtype.UUID +} + +// Closes the active grants of one candidate with one reason. A nil organization +// closes every organization of the candidate, and a non-nil list of consent +// records closes only the grants that those records gave. The grant rows are +// locked in identifier order, so two closures that overlap take their locks in +// the same order. The revocation time never precedes the grant time, which the +// grant checks. A grant that is already closed keeps its first stamp. +func (q *Queries) CloseActiveContactGrants(ctx context.Context, arg CloseActiveContactGrantsParams) (int64, error) { + result, err := q.db.Exec(ctx, closeActiveContactGrants, + arg.RevokedAt, + arg.RevocationReason, + arg.CandidateID, + arg.OrganizationID, + arg.ConsentRecordIds, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const getContactGrantByInvitation = `-- name: GetContactGrantByInvitation :one SELECT id, @@ -109,3 +163,72 @@ func (q *Queries) InsertContactGrant(ctx context.Context, arg InsertContactGrant ) return err } + +const lockContactGrant = `-- name: LockContactGrant :one +SELECT + id, + organization_id, + candidate_id, + source_invitation_id, + consent_record_id, + terms_version, + fields, + consent_text_version, + granted_at, + revoked_at, + revocation_reason +FROM contact_grants +WHERE id = $1 +FOR SHARE +` + +// Share-locks one grant for the duration of a contact read and returns its +// stored state. The caller decides whether the state still allows the read. +func (q *Queries) LockContactGrant(ctx context.Context, id pgtype.UUID) (ContactGrant, error) { + row := q.db.QueryRow(ctx, lockContactGrant, id) + var i ContactGrant + err := row.Scan( + &i.ID, + &i.OrganizationID, + &i.CandidateID, + &i.SourceInvitationID, + &i.ConsentRecordID, + &i.TermsVersion, + &i.Fields, + &i.ConsentTextVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationReason, + ) + return i, err +} + +const lockCurrentContactConsentRecord = `-- name: LockCurrentContactConsentRecord :one +SELECT consent_records.id +FROM consent_records +WHERE + consent_records.id = $1 + AND consent_records.subject_id = $2 + AND consent_records.organization_id = $3 + AND consent_records.purpose = 'c4' + AND consent_records.revoked_at IS NULL +FOR SHARE +` + +type LockCurrentContactConsentRecordParams struct { + ConsentRecordID pgtype.UUID + CandidateID pgtype.UUID + OrganizationID pgtype.UUID +} + +// Share-locks the consent C4 record of a grant for the duration of a contact +// read. The read locks the record before the grant, the order that a C4 +// revocation follows when it stamps the record and then closes its grants. No +// row means the record is revoked or belongs to another scope, which closes +// the read. +func (q *Queries) LockCurrentContactConsentRecord(ctx context.Context, arg LockCurrentContactConsentRecordParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, lockCurrentContactConsentRecord, arg.ConsentRecordID, arg.CandidateID, arg.OrganizationID) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/invitation_cooldowns.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/invitation_cooldowns.sql.go new file mode 100644 index 0000000..28f3db7 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/invitation_cooldowns.sql.go @@ -0,0 +1,39 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: invitation_cooldowns.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const latestInvitationDecline = `-- name: LatestInvitationDecline :one +SELECT responded_at AS declined_at +FROM invitations +WHERE + organization_id = $1 + AND candidate_id = $2 + AND state = 'declined' +ORDER BY responded_at DESC +LIMIT 1 +` + +type LatestInvitationDeclineParams struct { + OrganizationID pgtype.UUID + CandidateID pgtype.UUID +} + +// The time of the latest decline of one candidate by one organization, across +// every need and every member of the organization. The pause that follows it is +// applied by the send, from the policy in force. A candidate without a decline +// finds no row. +func (q *Queries) LatestInvitationDecline(ctx context.Context, arg LatestInvitationDeclineParams) (pgtype.Timestamptz, error) { + row := q.db.QueryRow(ctx, latestInvitationDecline, arg.OrganizationID, arg.CandidateID) + var declined_at pgtype.Timestamptz + err := row.Scan(&declined_at) + return declined_at, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/invitation_expiry.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/invitation_expiry.sql.go new file mode 100644 index 0000000..dba8eeb --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/invitation_expiry.sql.go @@ -0,0 +1,73 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: invitation_expiry.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const expireInvitation = `-- name: ExpireInvitation :one +UPDATE invitations +SET + state = 'expired', + expiry_reason = 'invitation_timeout', + version = $1, + updated_at = $2 +WHERE + organization_id = $3 + AND id = $4 + AND state IN ('delivered', 'viewed') + AND version = $5 + AND response_deadline_at <= $2 + AND $1::bigint = $5::bigint + 1 +RETURNING id +` + +type ExpireInvitationParams struct { + NextVersion int64 + ExpiredAt pgtype.Timestamptz + OrganizationID pgtype.UUID + InvitationID pgtype.UUID + ExpectedVersion int64 +} + +// The compare-and-swap of the expiry: it applies only to a delivered or viewed +// invitation at the version the caller read, whose deadline has passed at the +// expiry time. It keeps the deadline, the terms, and every answer field, and it +// sets the timeout reason. No row is returned when it lost a race or the +// deadline has not passed. +func (q *Queries) ExpireInvitation(ctx context.Context, arg ExpireInvitationParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, expireInvitation, + arg.NextVersion, + arg.ExpiredAt, + arg.OrganizationID, + arg.InvitationID, + arg.ExpectedVersion, + ) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + +const lockInvitationByID = `-- name: LockInvitationByID :one +SELECT organization_id +FROM invitations +WHERE id = $1 +FOR UPDATE +` + +// Takes the row lock of one invitation by its identifier alone. Only the +// response deadline job reads an invitation without an organization or a +// candidate of the request; it reads the organization from this row and then +// reads the locked invitation with its scope. +func (q *Queries) LockInvitationByID(ctx context.Context, invitationID pgtype.UUID) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, lockInvitationByID, invitationID) + var organization_id pgtype.UUID + err := row.Scan(&organization_id) + return organization_id, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/invitation_pending.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/invitation_pending.sql.go new file mode 100644 index 0000000..90c3955 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/invitation_pending.sql.go @@ -0,0 +1,37 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: invitation_pending.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const countPendingNeedInvitations = `-- name: CountPendingNeedInvitations :one +SELECT count(*)::bigint AS pending +FROM invitations +WHERE + organization_id = $1 + AND need_id = $2 + AND state IN ('delivered', 'viewed', 'counter') +` + +type CountPendingNeedInvitationsParams struct { + OrganizationID pgtype.UUID + NeedID pgtype.UUID +} + +// Counts the invitations of one organization need that wait for an answer: +// delivered, viewed, or the planned counter offer. The send counts them under +// the organization lock, which every send takes first, so no other send can +// add a waiting invitation between the count and its own delivery. +func (q *Queries) CountPendingNeedInvitations(ctx context.Context, arg CountPendingNeedInvitationsParams) (int64, error) { + row := q.db.QueryRow(ctx, countPendingNeedInvitations, arg.OrganizationID, arg.NeedID) + var pending int64 + err := row.Scan(&pending) + return pending, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index cd47447..e489783 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -114,6 +114,13 @@ type Querier interface { // jobs belong to kinds without a handler in the claiming process, an index // on (kind, available_at, id) is the next step. ClaimScheduledJobs(ctx context.Context, arg ClaimScheduledJobsParams) ([]ClaimScheduledJobsRow, error) + // Closes the active grants of one candidate with one reason. A nil organization + // closes every organization of the candidate, and a non-nil list of consent + // records closes only the grants that those records gave. The grant rows are + // locked in identifier order, so two closures that overlap take their locks in + // the same order. The revocation time never precedes the grant time, which the + // grant checks. A grant that is already closed keeps its first stamp. + CloseActiveContactGrants(ctx context.Context, arg CloseActiveContactGrantsParams) (int64, error) // Completes a job in the transaction of its handler effect. The guard is // the lease owner and the attempt, so a worker that lost its lease cannot // complete the job. @@ -147,6 +154,11 @@ type Querier interface { // row stays attributed to the organization that consumed it. CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error) CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error) + // Counts the invitations of one organization need that wait for an answer: + // delivered, viewed, or the planned counter offer. The send counts them under + // the organization lock, which every send takes first, so no other send can + // add a waiting invitation between the count and its own delivery. + CountPendingNeedInvitations(ctx context.Context, arg CountPendingNeedInvitationsParams) (int64, error) // Counts the families of a category that have at least one published // version, however many versions each has. CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error) @@ -235,6 +247,12 @@ type Querier interface { // for the first transaction and then inserts nothing. Existing rows are // neither changed nor locked here. EnsureMailQuotaRows(ctx context.Context, arg EnsureMailQuotaRowsParams) error + // The compare-and-swap of the expiry: it applies only to a delivered or viewed + // invitation at the version the caller read, whose deadline has passed at the + // expiry time. It keeps the deadline, the terms, and every answer field, and it + // sets the timeout reason. No row is returned when it lost a race or the + // deadline has not passed. + ExpireInvitation(ctx context.Context, arg ExpireInvitationParams) (pgtype.UUID, error) // Records a failed attempt after its handler transaction rolled back: the // job waits for its retry at retry_at (status failed) or is dead, with a // NULL retry_at. due_at keeps the deadline. The same guard as the @@ -576,6 +594,11 @@ type Querier interface { // version number of a stored snapshot whose own requirements version is that // number, so a later edit that only renamed the need is not accepted. InvitationNeedVersionExists(ctx context.Context, arg InvitationNeedVersionExistsParams) (bool, error) + // The time of the latest decline of one candidate by one organization, across + // every need and every member of the organization. The pause that follows it is + // applied by the send, from the policy in force. A candidate without a decline + // finds no row. + LatestInvitationDecline(ctx context.Context, arg LatestInvitationDeclineParams) (pgtype.Timestamptz, error) // Read the latest serialized event so a temporarily regressing application // clock cannot make the next request fall before an event already counted. LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error) @@ -793,6 +816,9 @@ type Querier interface { // transaction. The result carries the holding, whose pool an E0 organization // shares; the caller locks that holding right after this lock. LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationFirstRow, error) + // Share-locks one grant for the duration of a contact read and returns its + // stored state. The caller decides whether the state still allows the read. + LockContactGrant(ctx context.Context, id pgtype.UUID) (ContactGrant, error) // Lock the current C2 before locking the publication. C2 revocation updates // this row before it locks the publication, so preserving this order avoids // a lock inversion and makes the current consent stable through the read. @@ -809,6 +835,12 @@ type Querier interface { // Keeps the current C3 grant stable through a real assessment transaction. // Revocation updates this row and therefore waits until the caller commits. LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error) + // Share-locks the consent C4 record of a grant for the duration of a contact + // read. The read locks the record before the grant, the order that a C4 + // revocation follows when it stamps the record and then closes its grants. No + // row means the record is revoked or belongs to another scope, which closes + // the read. + LockCurrentContactConsentRecord(ctx context.Context, arg LockCurrentContactConsentRecordParams) (pgtype.UUID, error) // Takes the row lock of one invitation. It is a statement of its own, ahead of // ReadInvitation, because a locking read that joins the terms table is // re-checked against the new row version after a wait and then pairs the @@ -816,6 +848,11 @@ type Querier interface { // finds nothing. Once the lock is held, the following read sees the committed // state and no writer can change it. LockInvitation(ctx context.Context, arg LockInvitationParams) (pgtype.UUID, error) + // Takes the row lock of one invitation by its identifier alone. Only the + // response deadline job reads an invitation without an organization or a + // candidate of the request; it reads the organization from this row and then + // reads the locked invitation with its scope. + LockInvitationByID(ctx context.Context, invitationID pgtype.UUID) (pgtype.UUID, error) // Locks the listed window rows until the transaction ends, in // (period_kind, period_start) order, the same order for every caller, and // returns their usage. Under READ COMMITTED a waiting caller reads the usage diff --git a/backend/internal/bootstrap/jobs.go b/backend/internal/bootstrap/jobs.go index be52974..c79e4f8 100644 --- a/backend/internal/bootstrap/jobs.go +++ b/backend/internal/bootstrap/jobs.go @@ -11,6 +11,7 @@ import ( "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/invitation" "lincodex/backend/internal/worker/jobrunner" "lincodex/backend/internal/worker/retry" ) @@ -32,10 +33,14 @@ var _ jobrunner.Metrics = (*prometheus.Metrics)(nil) // jobHandlers lists the scheduled job handlers, one per kind. A product // module adds its handler here, and the worker then claims jobs of that kind // with the next deployment. Jobs of a kind without a handler wait in the -// database. The only kind now is the computation of the assessment review -// band, which can never block or change a result. +// database. The kinds are the computation of the assessment review band, which +// can never block or change a result, and the expiry of an invitation at its +// response deadline. func jobHandlers(logger *slog.Logger) []inbound.JobHandler { - return []inbound.JobHandler{assessment.NewSignalReviewJob(logger)} + return []inbound.JobHandler{ + assessment.NewSignalReviewJob(logger), + invitation.NewResponseDeadlineJob(time.Now), + } } func newJobWorker( diff --git a/backend/internal/bootstrap/jobs_test.go b/backend/internal/bootstrap/jobs_test.go index 4137a67..308ba64 100644 --- a/backend/internal/bootstrap/jobs_test.go +++ b/backend/internal/bootstrap/jobs_test.go @@ -4,6 +4,7 @@ import ( "context" "log/slog" "net/http" + "slices" "strings" "testing" "time" @@ -55,10 +56,14 @@ func TestBuildJobWorkerSkipsWithoutWork(t *testing.T) { } } -func TestBootstrapRegistersTheReviewJobKind(t *testing.T) { +func TestBootstrapRegistersTheProductJobKinds(t *testing.T) { handlers := jobHandlers(slog.New(slog.DiscardHandler)) - if len(handlers) != 1 || handlers[0].JobKind() != "assessment.signal_review" { - t.Fatalf("jobHandlers() = %v; update the documentation when the registered job kinds change", handlers) + kinds := make([]string, 0, len(handlers)) + for _, handler := range handlers { + kinds = append(kinds, handler.JobKind()) + } + if !slices.Equal(kinds, []string{"assessment.signal_review", "invitation.response_deadline"}) { + t.Fatalf("jobHandlers() kinds = %v; update the documentation when the registered job kinds change", kinds) } } diff --git a/backend/internal/domain/contact_disclosure.go b/backend/internal/domain/contact_disclosure.go new file mode 100644 index 0000000..4f0245b --- /dev/null +++ b/backend/internal/domain/contact_disclosure.go @@ -0,0 +1,112 @@ +package domain + +import ( + "fmt" + "log/slog" + "slices" + "time" + + "github.com/google/uuid" +) + +const redactedContactDisclosure = "[redacted contact disclosure]" + +// ContactDisclosure holds the contact values that one active grant allows an +// organization to read now. It is the only domain value that carries contact +// values, so it redacts itself in fmt and slog output. It names no candidate +// and no organization: the caller already knows both from its own request. +type ContactDisclosure struct { + invitationID uuid.UUID + grantID uuid.UUID + fields []ContactField + grantedAt time.Time + fullName *string + email *string + phone *string + telegram *string +} + +// NewContactDisclosure builds the values of an active grant from the profile. +// Only the kinds of the grant are read, and a kind yields its value only when +// the profile holds it as a confirmed claim, so a suggestion that nobody +// confirmed is never disclosed. A kind the profile no longer holds stays nil. +func NewContactDisclosure(grant ContactGrant, profile CandidateProfile) (ContactDisclosure, error) { + const location = "domain.NewContactDisclosure" + if grant.IsZero() || grant.Status() != ContactGrantActive { + return ContactDisclosure{}, fmt.Errorf("%s - only an active grant discloses contacts: %w", location, ErrInvalidContactGrant) + } + content := profile.Content() + disclosure := ContactDisclosure{ + invitationID: grant.InvitationID(), grantID: grant.ID(), + fields: grant.Fields().Fields(), grantedAt: grant.GrantedAt(), + } + for _, field := range disclosure.fields { + switch field { + case ContactFieldFullName: + disclosure.fullName = confirmedContactValue(content.FullName()) + case ContactFieldEmail: + disclosure.email = confirmedContactValue(content.Email()) + case ContactFieldPhone: + disclosure.phone = confirmedContactValue(content.Phone()) + case ContactFieldTelegram: + disclosure.telegram = confirmedContactValue(content.Telegram()) + } + } + return disclosure, nil +} + +// confirmedContactValue returns the value of a claim the candidate confirmed, +// and nil for a missing claim or an unconfirmed suggestion. +func confirmedContactValue(claim ProfileClaim[string], present bool) *string { + if !present || claim.Status() != ProfileClaimConfirmed { + return nil + } + value := claim.Value() + return &value +} + +// InvitationID is the invitation whose acceptance created the grant. +func (disclosure ContactDisclosure) InvitationID() uuid.UUID { return disclosure.invitationID } + +// GrantID is the grant that allowed the read. +func (disclosure ContactDisclosure) GrantID() uuid.UUID { return disclosure.grantID } + +// Fields are the kinds that the grant covers, in canonical order. +func (disclosure ContactDisclosure) Fields() []ContactField { return slices.Clone(disclosure.fields) } + +// GrantedAt is the time of the consent that the grant stores. +func (disclosure ContactDisclosure) GrantedAt() time.Time { return disclosure.grantedAt } + +// FullName returns the full name and whether it is disclosed. +func (disclosure ContactDisclosure) FullName() (string, bool) { + return valueOfContact(disclosure.fullName) +} + +// Email returns the email address and whether it is disclosed. +func (disclosure ContactDisclosure) Email() (string, bool) { return valueOfContact(disclosure.email) } + +// Phone returns the phone number and whether it is disclosed. +func (disclosure ContactDisclosure) Phone() (string, bool) { return valueOfContact(disclosure.phone) } + +// Telegram returns the Telegram username and whether it is disclosed. +func (disclosure ContactDisclosure) Telegram() (string, bool) { + return valueOfContact(disclosure.telegram) +} + +func valueOfContact(value *string) (string, bool) { + if value == nil { + return "", false + } + return *value, true +} + +func (disclosure ContactDisclosure) String() string { return redactedContactDisclosure } +func (disclosure ContactDisclosure) GoString() string { return redactedContactDisclosure } +func (disclosure ContactDisclosure) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedContactDisclosure) +} + +// LogValue carries the grant identifier and the number of kinds only. +func (disclosure ContactDisclosure) LogValue() slog.Value { + return slog.GroupValue(slog.String("grant_id", disclosure.grantID.String()), slog.Int("fields", len(disclosure.fields))) +} diff --git a/backend/internal/domain/contact_disclosure_test.go b/backend/internal/domain/contact_disclosure_test.go new file mode 100644 index 0000000..8afef50 --- /dev/null +++ b/backend/internal/domain/contact_disclosure_test.go @@ -0,0 +1,172 @@ +package domain + +import ( + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestNewContactDisclosureReadsOnlyTheGrantedConfirmedKinds(t *testing.T) { + now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC) + candidateID, organizationID, invitationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + profile := contactTestProfile(t, candidateID, now, map[string]ProfileClaimInput[string]{ + "full_name": {Value: "Test Candidate", Status: ProfileClaimConfirmed}, + "phone": {Value: "+70000000000", Status: ProfileClaimConfirmed}, + "telegram": {Value: "@candidate_test", Status: ProfileClaimConfirmed}, + }) + grant := contactTestGrant(t, candidateID, organizationID, invitationID, now, "email", "phone", "telegram") + + disclosure, err := NewContactDisclosure(grant, profile) + if err != nil { + t.Fatalf("NewContactDisclosure() error = %v", err) + } + if disclosure.InvitationID() != invitationID || disclosure.GrantID() != grant.ID() || !disclosure.GrantedAt().Equal(now) { + t.Fatalf("disclosure identity = %v %v %v, want the grant's", disclosure.InvitationID(), disclosure.GrantID(), disclosure.GrantedAt()) + } + if !equalContactFields(disclosure.Fields(), ContactFieldEmail, ContactFieldPhone, ContactFieldTelegram) { + t.Fatalf("fields = %v, want the grant's three kinds", disclosure.Fields()) + } + // The profile holds no email, so the granted email has no value. + if value, ok := disclosure.Email(); ok || value != "" { + t.Fatalf("email = %q, %v; want no value for a kind the profile does not hold", value, ok) + } + if value, ok := disclosure.Phone(); !ok || value != "+70000000000" { + t.Fatalf("phone = %q, %v; want the confirmed number", value, ok) + } + if value, ok := disclosure.Telegram(); !ok || value != "@candidate_test" { + t.Fatalf("telegram = %q, %v; want the confirmed name", value, ok) + } + // The full name is held but not granted, so it stays undisclosed. + if value, ok := disclosure.FullName(); ok || value != "" { + t.Fatalf("full name = %q, %v; want none because the grant does not cover it", value, ok) + } +} + +func TestConfirmedContactValueIgnoresUnconfirmedSuggestions(t *testing.T) { + source, err := RestoreProfileClaimSource(ProfileOriginImported, ProfileClaimTrustLevel, "", "extractor-1", time.Time{}) + if err != nil { + t.Fatalf("RestoreProfileClaimSource() error = %v", err) + } + suggestion, err := RestoreProfileClaim("candidate@example.test", ProfileClaimExtracted, source) + if err != nil { + t.Fatalf("RestoreProfileClaim() error = %v", err) + } + if value := confirmedContactValue(suggestion, true); value != nil { + t.Fatalf("confirmedContactValue(suggestion) = %q, want nil", *value) + } + if value := confirmedContactValue(suggestion, false); value != nil { + t.Fatal("confirmedContactValue(missing claim) returned a value") + } +} + +func TestNewContactDisclosureRefusesAGrantThatIsNotActive(t *testing.T) { + now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC) + candidateID, organizationID, invitationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + profile := contactTestProfile(t, candidateID, now, map[string]ProfileClaimInput[string]{ + "email": {Value: "candidate@example.test", Status: ProfileClaimConfirmed}, + }) + grant := contactTestGrant(t, candidateID, organizationID, invitationID, now, "email") + stored := grant.Stored() + revokedAt := now.Add(time.Hour) + stored.RevokedAt, stored.RevocationReason = &revokedAt, string(ContactRevocationVisibilityClosed) + revoked, err := RestoreContactGrant(stored) + if err != nil { + t.Fatalf("RestoreContactGrant() error = %v", err) + } + if _, err := NewContactDisclosure(revoked, profile); !errors.Is(err, ErrInvalidContactGrant) { + t.Fatalf("NewContactDisclosure(revoked) error = %v, want ErrInvalidContactGrant", err) + } + if _, err := NewContactDisclosure(ContactGrant{}, profile); !errors.Is(err, ErrInvalidContactGrant) { + t.Fatalf("NewContactDisclosure(zero) error = %v, want ErrInvalidContactGrant", err) + } +} + +func TestContactDisclosureRedactsItsValuesInFormatting(t *testing.T) { + now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC) + candidateID, organizationID, invitationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + profile := contactTestProfile(t, candidateID, now, map[string]ProfileClaimInput[string]{ + "phone": {Value: "+70000000001", Status: ProfileClaimConfirmed}, + }) + disclosure, err := NewContactDisclosure(contactTestGrant(t, candidateID, organizationID, invitationID, now, "phone"), profile) + if err != nil { + t.Fatalf("NewContactDisclosure() error = %v", err) + } + for _, rendered := range []string{ + fmt.Sprint(disclosure), fmt.Sprintf("%+v", disclosure), fmt.Sprintf("%#v", disclosure), + } { + if strings.Contains(rendered, "+70000000001") || strings.Contains(rendered, candidateID.String()) { + t.Fatalf("formatted disclosure leaks a value or the candidate: %q", rendered) + } + } +} + +// contactTestGrant builds an active grant of the kinds, as the acceptance does. +func contactTestGrant(t *testing.T, candidateID, organizationID, invitationID uuid.UUID, at time.Time, kinds ...string) ContactGrant { + t.Helper() + grant, err := RestoreContactGrant(StoredContactGrant{ + ID: uuid.Must(uuid.NewV7()), OrganizationID: organizationID, CandidateID: candidateID, + InvitationID: invitationID, ConsentRecordID: uuid.Must(uuid.NewV7()), TermsVersion: 1, + Fields: canonicalKinds(kinds...), ConsentTextVersion: "c4-2026-10-01", GrantedAt: at, + }) + if err != nil { + t.Fatalf("RestoreContactGrant() error = %v", err) + } + return grant +} + +// contactTestProfile builds a profile whose claims have the given statuses. +func contactTestProfile(t *testing.T, candidateID uuid.UUID, at time.Time, claims map[string]ProfileClaimInput[string]) CandidateProfile { + t.Helper() + var input CandidateProfileInput + for kind, claim := range claims { + switch kind { + case "full_name": + input.FullName = &claim + case "email": + input.Email = &claim + case "phone": + input.Phone = &claim + case "telegram": + input.Telegram = &claim + } + } + empty, err := EmptyCandidateProfile(candidateID) + if err != nil { + t.Fatalf("EmptyCandidateProfile() error = %v", err) + } + profile, _, err := empty.Replace(input, 0, at) + if err != nil { + t.Fatalf("Replace() error = %v", err) + } + return profile +} + +// canonicalKinds returns the kinds in the order of the stored form. +func canonicalKinds(kinds ...string) []string { + order := []string{"full_name", "email", "phone", "telegram"} + var canonical []string + for _, kind := range order { + for _, given := range kinds { + if given == kind { + canonical = append(canonical, kind) + } + } + } + return canonical +} + +func equalContactFields(got []ContactField, want ...ContactField) bool { + if len(got) != len(want) { + return false + } + for index := range got { + if got[index] != want[index] { + return false + } + } + return true +} diff --git a/backend/internal/domain/contact_grant.go b/backend/internal/domain/contact_grant.go index a69c0f6..90c7ea9 100644 --- a/backend/internal/domain/contact_grant.go +++ b/backend/internal/domain/contact_grant.go @@ -17,7 +17,8 @@ var ( ) // ContactRevocationReason says why a contact grant was revoked. It is shown -// only to the candidate. The revocation itself belongs to a later operation. +// only to the candidate. The consent revocation and the visibility changes +// stamp it in the transaction of the change; a stamp is never cleared. type ContactRevocationReason string const ( diff --git a/backend/internal/domain/invitation.go b/backend/internal/domain/invitation.go index e67e1c2..36d08a6 100644 --- a/backend/internal/domain/invitation.go +++ b/backend/internal/domain/invitation.go @@ -459,6 +459,26 @@ const ( InvitationContactAccessClosed InvitationContactAccess = "closed" ) +// InvitationContactAccessView is the contact access of the organization through +// one invitation. Fields are the kinds that the contact read returns while the +// status is available; the other states list none. It never holds a contact +// value, and it names no reason, because the organization is not told one. +type InvitationContactAccessView struct { + Status InvitationContactAccess `json:"status"` + Fields []ContactField `json:"fields"` +} + +// NewInvitationContactAccessView builds the view of a status. Fields are kept +// only for an available access, and the list is never nil, so it serializes as +// an empty array. +func NewInvitationContactAccessView(status InvitationContactAccess, fields []ContactField) InvitationContactAccessView { + view := InvitationContactAccessView{Status: status, Fields: []ContactField{}} + if status == InvitationContactAccessAvailable { + view.Fields = append(view.Fields, fields...) + } + return view +} + // InvitationSnapshot is the serializable part of an invitation that an // organization may read. It has no candidate identifier, so it cannot reveal // who the invitation is for. @@ -500,15 +520,14 @@ func (invitation Invitation) Snapshot() InvitationSnapshot { // OrganizationInvitationView is an invitation as its organization reads it: // the snapshot, the organization-scoped alias of the candidate, the coarse -// salary indicator, and the state of the contact access without any contact -// value. It also serves as the stored original response of an idempotent -// create. +// salary indicator, and the contact access without any contact value. It also +// serves as the stored original response of an idempotent create or send. type OrganizationInvitationView struct { InvitationSnapshot - CandidateHandle string `json:"candidate_handle"` - SalaryFit InvitationSalaryFit `json:"salary_fit"` - ContactAccess InvitationContactAccess `json:"contact_access"` + CandidateHandle string `json:"candidate_handle"` + SalaryFit InvitationSalaryFit `json:"salary_fit"` + ContactAccess InvitationContactAccessView `json:"contact_access"` } func (invitation Invitation) String() string { return redactedInvitation } diff --git a/backend/internal/domain/invitation_expiry.go b/backend/internal/domain/invitation_expiry.go new file mode 100644 index 0000000..4c23650 --- /dev/null +++ b/backend/internal/domain/invitation_expiry.go @@ -0,0 +1,74 @@ +package domain + +import ( + "fmt" + "time" + + "github.com/google/uuid" +) + +// InvitationEventExpired is the audit event of an expiry that the server made +// at the response deadline. No candidate or organization acted, so the event +// names no actor and no field. +const InvitationEventExpired InvitationEventKind = "expired" + +// AwaitsAnswer reports the states in which the candidate's answer is still +// open: a delivered or a viewed invitation. The planned counter offer is not +// among them, because no operation produces it yet. +func (invitation Invitation) AwaitsAnswer() bool { + return invitation.IsDelivered() && (invitation.State() == InvitationDelivered || invitation.State() == InvitationViewed) +} + +// ExpiryDue reports whether the invitation still awaits an answer at the time +// and its response deadline has passed. At the deadline or later the answer is +// late, so the expiry is due. +func (invitation Invitation) ExpiryDue(at time.Time) bool { + return invitation.AwaitsAnswer() && invitation.ResponseDeadlinePassed(at) +} + +// Expire returns the next version in the terminal state expired with the +// timeout reason, when the invitation is due at the time. An invitation that is +// not due, because it is answered, expired, or its deadline has not passed yet, +// is returned as it is with changed false. The expiry keeps the deadline, the +// terms, and the answer fields. It creates no consent and no contact grant, and +// it never returns a weekly quota or a pending slot that the organization +// spent: the pending limit counts only the invitations that still wait. +func (invitation Invitation) Expire(at time.Time) (Invitation, bool, error) { + const location = "Invitation.Expire" + if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) { + return Invitation{}, false, fmt.Errorf("%s - expiry time must be set and not before the last change: %w", location, ErrInvalidInvitation) + } + if !invitation.ExpiryDue(at) { + return invitation, false, nil + } + at = at.UTC() + next := invitation.Stored() + reason := string(InvitationExpiryTimeout) + next.State = string(InvitationExpired) + next.ExpiryReason = &reason + next.Version++ + next.UpdatedAt = at + expired, err := RestoreInvitation(next) + if err != nil { + return Invitation{}, false, fmt.Errorf("%s - restore expired invitation: %w", location, err) + } + return expired, true, nil +} + +// ExpiryEvent builds the audit event of the expired version this invitation has +// just reached. The event has no actor, because the server made the change. +func (invitation Invitation) ExpiryEvent() (InvitationEvent, error) { + const location = "Invitation.ExpiryEvent" + if invitation.State() != InvitationExpired { + return InvitationEvent{}, fmt.Errorf("%s - the invitation must be expired: %w", location, ErrInvalidInvitation) + } + id, err := uuid.NewV7() + if err != nil { + return InvitationEvent{}, fmt.Errorf("%s - generate event ID: %w", location, err) + } + return InvitationEvent{ + ID: id, InvitationID: invitation.record.ID, OrganizationID: invitation.record.OrganizationID, + Version: invitation.record.Version, TermsVersion: invitation.record.TermsVersion, Kind: InvitationEventExpired, + ActorID: uuid.Nil, ChangedFields: []InvitationChangedField{}, OccurredAt: invitation.record.UpdatedAt, + }, nil +} diff --git a/backend/internal/domain/invitation_expiry_test.go b/backend/internal/domain/invitation_expiry_test.go new file mode 100644 index 0000000..603222d --- /dev/null +++ b/backend/internal/domain/invitation_expiry_test.go @@ -0,0 +1,86 @@ +package domain + +import ( + "errors" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestExpireMovesADueInvitationToTheTimeoutReasonAndKeepsItsDeadline(t *testing.T) { + delivered, _ := deliveredTestInvitation(t) + deadline := *delivered.Snapshot().ResponseDeadlineAt + viewed, _, err := delivered.RecordView(delivered.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("RecordView() error = %v", err) + } + + for name, invitation := range map[string]Invitation{"delivered": delivered, "viewed": viewed} { + t.Run(name, func(t *testing.T) { + expired, changed, err := invitation.Expire(deadline) + if err != nil || !changed { + t.Fatalf("Expire(at the deadline) = %v, %v; want a change", changed, err) + } + snapshot := expired.Snapshot() + if snapshot.State != InvitationExpired || snapshot.ExpiryReason == nil || *snapshot.ExpiryReason != InvitationExpiryTimeout || + snapshot.Version != invitation.Version()+1 || snapshot.TermsVersion != invitation.TermsVersion() || + !snapshot.ResponseDeadlineAt.Equal(deadline) || !snapshot.UpdatedAt.Equal(deadline) || + snapshot.RespondedAt != nil || !snapshot.DeliveredAt.Equal(*invitation.Snapshot().DeliveredAt) { + t.Fatalf("expired = %+v, want the next version expired by the timeout with the same deadline and terms", snapshot) + } + event, err := expired.ExpiryEvent() + if err != nil { + t.Fatalf("ExpiryEvent() error = %v", err) + } + if event.Kind != InvitationEventExpired || event.ActorID != uuid.Nil || + event.Version != snapshot.Version || len(event.ChangedFields) != 0 || !event.OccurredAt.Equal(deadline) { + t.Fatalf("ExpiryEvent() = %+v, want one system event of the expired version", event) + } + }) + } +} + +func TestExpireLeavesAnInvitationAloneBeforeItsDeadlineAndAfterAnAnswer(t *testing.T) { + delivered, _ := deliveredTestInvitation(t) + deadline := *delivered.Snapshot().ResponseDeadlineAt + expiring := deadline.Add(-time.Microsecond) + declined, _, err := delivered.Decline(InvitationDeclineChoice{Reason: InvitationDeclineOther}, expiring) + if err != nil { + t.Fatalf("Decline() error = %v", err) + } + accepted := withState(t, delivered, InvitationAccepted, func(stored *StoredInvitation) { + responded := expiring + stored.RespondedAt = &responded + }) + + for name, test := range map[string]struct { + invitation Invitation + at time.Time + }{ + "one microsecond before the deadline": {delivered, expiring}, + "declined after the deadline": {declined, deadline.Add(time.Hour)}, + "accepted after the deadline": {accepted, deadline.Add(time.Hour)}, + } { + t.Run(name, func(t *testing.T) { + unchanged, changed, err := test.invitation.Expire(test.at) + if err != nil || changed || unchanged.Version() != test.invitation.Version() || unchanged.State() != test.invitation.State() { + t.Fatalf("Expire() = %v, %v, %v; want the invitation unchanged", unchanged.State(), changed, err) + } + }) + } +} + +func TestExpireRefusesATimeBeforeTheLastChange(t *testing.T) { + delivered, _ := deliveredTestInvitation(t) + if _, _, err := delivered.Expire(delivered.UpdatedAt().Add(-time.Second)); !errors.Is(err, ErrInvalidInvitation) { + t.Fatalf("Expire(before the last change) error = %v, want ErrInvalidInvitation", err) + } +} + +func TestExpiryEventRequiresAnExpiredInvitation(t *testing.T) { + delivered, _ := deliveredTestInvitation(t) + if _, err := delivered.ExpiryEvent(); !errors.Is(err, ErrInvalidInvitation) { + t.Fatalf("ExpiryEvent(delivered) error = %v, want ErrInvalidInvitation", err) + } +} diff --git a/backend/internal/port/outbound/consents.go b/backend/internal/port/outbound/consents.go index c4f1bb9..d47b5a1 100644 --- a/backend/internal/port/outbound/consents.go +++ b/backend/internal/port/outbound/consents.go @@ -57,25 +57,23 @@ type AccountDeletionRequests interface { CreateOrGet(ctx context.Context, request domain.AccountDeletionRequest) (record domain.AccountDeletionRequest, created bool, err error) } -// ConsentRevocationEffects applies every currently available local privacy -// change and records downstream revocation intents in the same transaction as -// the ledger stamps. Future C2 and C4 grant adapters must bind each downstream -// grant to its source consent record ID and synchronously close grants for -// revoked record IDs before returning; a later consent record may create a -// new grant, but must never reactivate an older record's grant. Future C5 -// readers and importers must check the current consent ledger before reading +// ConsentRevocationEffects applies every local privacy change of a revocation +// and records downstream revocation intents in the same transaction as the +// ledger stamps. The local grants are closed synchronously there: a C4 +// revocation closes the grants that name the revoked records, and a C2 +// revocation closes every grant of the candidate. A later consent record may +// create a new grant, but must never reactivate an older record's grant. Future +// C5 readers and importers must check the current consent ledger before reading // or synchronizing data and fail closed on a missing grant or ledger error. // An outbox event communicates a committed change; it is never an // authorization check and cannot make a revoked grant current again. This // release has no external FSP or downstream contact-grant adapter, so those // external effects are not claimed as complete. type ConsentRevocationEffects interface { - // Apply synchronously closes and records a C2 publication when present, - // then appends one bounded durable outbox intent per affected consent record - // with its stored scope. It must not truncate or omit affected records. A - // future local C2/C4 grant adapter must implement record-bound closure in - // this same UnitOfWork before the outbox intent is appended. An empty record - // set is not a valid call. + // Apply closes the local grants and the C2 publication when present, in the + // caller's transaction, then appends one bounded durable outbox intent per + // affected consent record with its stored scope. It must not truncate or + // omit affected records. An empty record set is not a valid call. Apply(ctx context.Context, revocation domain.ConsentRevocation, records []domain.ConsentRecord) error } diff --git a/backend/internal/port/outbound/contact_grants.go b/backend/internal/port/outbound/contact_grants.go index 33ff843..599b70a 100644 --- a/backend/internal/port/outbound/contact_grants.go +++ b/backend/internal/port/outbound/contact_grants.go @@ -16,14 +16,25 @@ var ErrContactGrantNotFound = errors.New("contact grant not found") // ContactGrantRepository stores the contact grants of accepted invitations. A // grant is created in the acceptance transaction next to its consent C4 -// record; it is never updated here, and a read is always scoped by the -// organization. +// record. Its revocation stamp is set only by the consent revocation and the +// visibility changes, through the closing statements of the postgres adapter. +// A read is always scoped by the organization. type ContactGrantRepository interface { // Create inserts the grant in the surrounding transaction. The database // checks that the grant agrees with its consent record and invitation. Create(ctx context.Context, grant domain.ContactGrant) error // GetByInvitation returns the grant of one invitation of one organization, - // or ErrContactGrantNotFound. + // or ErrContactGrantNotFound. It takes no lock, so its result is only a + // starting point: a contact read locks the grant with LockForRead before it + // decides. GetByInvitation(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.ContactGrant, error) + + // LockForRead share-locks the consent C4 record and then the grant that + // grant names, in that order, and returns the grant as stored now. The + // boolean reports whether the C4 record is still unrevoked. Both locks + // last until the surrounding transaction ends, so a revocation that commits + // first is seen here, and a revocation that waits closes the grant after the + // read. It returns ErrContactGrantNotFound when the grant has no row. + LockForRead(ctx context.Context, grant domain.ContactGrant) (domain.ContactGrant, bool, error) } diff --git a/backend/internal/port/outbound/invitations.go b/backend/internal/port/outbound/invitations.go index 71d1ad0..bfd7c3c 100644 --- a/backend/internal/port/outbound/invitations.go +++ b/backend/internal/port/outbound/invitations.go @@ -144,6 +144,29 @@ type InvitationRepository interface { // expectedVersion, at its terms version, or before its deadline. The consent // C4 and the contact grant are stored by the caller in the same transaction. Accept(ctx context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error + + // CountPendingNeedInvitations counts the invitations of the organization + // under the need that wait for an answer: delivered, viewed, or counter. + // The caller holds the organization lock, which every send takes first. + CountPendingNeedInvitations(ctx context.Context, organizationID, needID uuid.UUID) (int64, error) + + // LatestDeclineTime returns the time of the latest decline of the candidate + // by the organization, across its needs and members. It reports false when + // the pair has no decline. + LatestDeclineTime(ctx context.Context, organizationID, candidateID uuid.UUID) (time.Time, bool, error) + + // GetForDeadline locks the row of an invitation by its identifier alone and + // returns it, or ErrInvitationNotFound. Only the response deadline job reads + // an invitation without the organization or the candidate of a request. + GetForDeadline(ctx context.Context, invitationID uuid.UUID) (domain.Invitation, error) + + // Expire moves a delivered or viewed invitation from expectedVersion to the + // expired version of next, when its deadline has passed at the expiry time + // of next, and records the audit event. It returns + // ErrInvitationVersionConflict when the stored row is not waiting for an + // answer at expectedVersion or its deadline has not passed. Nothing else + // changes: no consent, grant, or quota is written or returned. + Expire(ctx context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error } // InvitationCreationResultRepository stores the original response of a diff --git a/backend/internal/usecase/invitation/accept.go b/backend/internal/usecase/invitation/accept.go index f8548f4..3ba7dc2 100644 --- a/backend/internal/usecase/invitation/accept.go +++ b/backend/internal/usecase/invitation/accept.go @@ -171,7 +171,9 @@ func (service *Service) acceptInTransaction( } // acceptFound applies the checks that follow a found invitation and, when they -// pass, stores the acceptance with its consent and grant. +// pass, stores the acceptance with its consent and grant. The deadline is judged +// at the time the row is held, and a due expiry is applied first, so an +// acceptance at the deadline or later is refused with the expired state. func (service *Service) acceptFound( ctx context.Context, unit outbound.UnitOfWork, @@ -179,8 +181,16 @@ func (service *Service) acceptFound( request acceptRequest, entry outbound.CandidateInvitationEntry, ) (acceptOutcome, error) { + now, err := service.now(acceptLocation) + if err != nil { + return acceptOutcome{}, err + } + entry, err = settleCandidateEntry(ctx, unit, entry, now) + if err != nil { + return acceptOutcome{}, fmt.Errorf("%s - expire due invitation: %w", acceptLocation, err) + } current := entry.Invitation - at := notBefore(request.now, current.UpdatedAt()) + at := notBefore(now, current.UpdatedAt()) switch { case current.State() == domain.InvitationAccepted: return service.repeatAccept(ctx, unit, command, request, entry) diff --git a/backend/internal/usecase/invitation/accept_test.go b/backend/internal/usecase/invitation/accept_test.go index 9659979..6a96a8e 100644 --- a/backend/internal/usecase/invitation/accept_test.go +++ b/backend/internal/usecase/invitation/accept_test.go @@ -372,8 +372,11 @@ func TestAcceptMineAtTheDeadlineStoresTheConflictAndGrantsNothing(t *testing.T) if result := state.acceptResults[testKeyring{}.IdempotencyScope(acceptOperation, "late", candidateID.String())]; result.Outcome != outbound.InvitationAcceptStateConflict { t.Fatalf("stored outcome = %+v, want state_conflict under the key", result) } - if len(state.grants) != 0 || len(state.consentRecords) != 0 || state.invitations[sent.ID].State() != domain.InvitationDelivered { - t.Fatalf("a late acceptance changed the invitation: grants %d, consents %d", len(state.grants), len(state.consentRecords)) + // The late command applies the due expiry first, so the invitation is + // expired, and it grants and records nothing. + if len(state.grants) != 0 || len(state.consentRecords) != 0 || state.invitations[sent.ID].State() != domain.InvitationExpired { + t.Fatalf("a late acceptance left %v with grants %d, consents %d; want expired with none", + state.invitations[sent.ID].State(), len(state.grants), len(state.consentRecords)) } } diff --git a/backend/internal/usecase/invitation/answer_test.go b/backend/internal/usecase/invitation/answer_test.go index 14ed39f..39d438c 100644 --- a/backend/internal/usecase/invitation/answer_test.go +++ b/backend/internal/usecase/invitation/answer_test.go @@ -134,13 +134,13 @@ func TestGetMineHasNoSideEffectAndViewMineKeepsTheDeadline(t *testing.T) { } } -func TestViewMineAtTheDeadlineChangesNothing(t *testing.T) { +func TestViewMineAtTheDeadlineExpiresTheInvitationAndRecordsNoView(t *testing.T) { test := newHarness(t) sent, candidateID := test.deliveredTo(t) test.setTime(*sent.ResponseDeadlineAt) view, err := test.service.ViewMine(t.Context(), candidateID, sent.ID) - if err != nil || view.State != domain.InvitationDelivered || view.Version != sent.Version || view.ViewedAt != nil { - t.Fatalf("late view = %+v, %v; want the delivered invitation unchanged", view, err) + if err != nil || view.State != domain.InvitationExpired || view.Version != sent.Version+1 || view.ViewedAt != nil { + t.Fatalf("late view = %+v, %v; want the invitation expired by the due expiry and no view", view, err) } } @@ -211,8 +211,8 @@ func TestDeclineMineFollowsTheOrderOfChecks(t *testing.T) { t.Fatalf("late decline error = %v, want ErrAnswerBlocked", err) } } - if state := test.transactor.snapshot(); len(state.declineResults) != 1 || state.invitations[sent.ID].State() != domain.InvitationDelivered { - t.Fatal("a late decline was not stored once or changed the invitation") + if state := test.transactor.snapshot(); len(state.declineResults) != 1 || state.invitations[sent.ID].State() != domain.InvitationExpired || len(state.declines) != 0 { + t.Fatal("a late decline was not stored once, or it recorded a decline or left the expired state unchanged") } // An unknown identifier is not found and stored as well. diff --git a/backend/internal/usecase/invitation/contact_access.go b/backend/internal/usecase/invitation/contact_access.go new file mode 100644 index 0000000..1e25203 --- /dev/null +++ b/backend/internal/usecase/invitation/contact_access.go @@ -0,0 +1,48 @@ +package invitation + +import ( + "context" + "errors" + "fmt" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const contactAccessLocation = "invitation.contactAccessOf" + +// contactAccessOf derives the contact access that the organization sees +// through one invitation. An invitation without a grant is not_granted. A +// revoked grant, and a grant that the contact read refuses now, are closed. +// Only an active grant that the read allows is available, and it lists the +// kinds of the grant. +// +// The derivation uses the checks and the locks of the contact read, through +// readableContactGrant, so the view never claims access that a read would +// refuse. It runs in the caller's transaction, and the locks it takes last +// until that transaction ends. Every state is checked, not only the accepted +// one, because a withdrawn invitation keeps its grant. +func contactAccessOf(ctx context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) (domain.InvitationContactAccessView, error) { + organizationID := invitation.OrganizationID() + grant, err := unit.ContactGrants().GetByInvitation(ctx, organizationID, invitation.ID()) + if errors.Is(err, outbound.ErrContactGrantNotFound) { + return domain.NewInvitationContactAccessView(domain.InvitationContactAccessNone, nil), nil + } + if err != nil { + return domain.InvitationContactAccessView{}, fmt.Errorf("%s - read contact grant: %w", contactAccessLocation, err) + } + // A revoked grant never becomes readable again, so the unlocked read is final. + if grant.Status() == domain.ContactGrantRevoked { + return domain.NewInvitationContactAccessView(domain.InvitationContactAccessClosed, nil), nil + } + stored, readable, err := readableContactGrant(ctx, unit, grant, organizationID) + switch { + case errors.Is(err, outbound.ErrContactGrantNotFound): + return domain.NewInvitationContactAccessView(domain.InvitationContactAccessClosed, nil), nil + case err != nil: + return domain.InvitationContactAccessView{}, fmt.Errorf("%s - check contact read: %w", contactAccessLocation, err) + case !readable: + return domain.NewInvitationContactAccessView(domain.InvitationContactAccessClosed, nil), nil + } + return domain.NewInvitationContactAccessView(domain.InvitationContactAccessAvailable, stored.Fields().Fields()), nil +} diff --git a/backend/internal/usecase/invitation/contact_access_test.go b/backend/internal/usecase/invitation/contact_access_test.go new file mode 100644 index 0000000..0100db7 --- /dev/null +++ b/backend/internal/usecase/invitation/contact_access_test.go @@ -0,0 +1,199 @@ +package invitation + +import ( + "errors" + "slices" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// organizationAccess reads the invitation as its organization and returns the +// contact access of the response. +func organizationAccess(t *testing.T, test *harness, invitationID uuid.UUID) domain.InvitationContactAccessView { + t.Helper() + view, err := test.service.Get(t.Context(), test.actorID, test.organizationID, invitationID) + if err != nil { + t.Fatalf("Get() error = %v", err) + } + return view.ContactAccess +} + +func requireContactAccess(t *testing.T, got domain.InvitationContactAccessView, status domain.InvitationContactAccess, fields ...domain.ContactField) { + t.Helper() + if got.Status != status || !slices.Equal(got.Fields, fields) { + t.Fatalf("contact access = %+v, want status %q with fields %v", got, status, fields) + } +} + +func TestOrganizationAccessIsNotGrantedBeforeAnAcceptance(t *testing.T) { + test := newHarness(t) + sent, _ := test.deliveredTo(t) + + requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessNone) + page, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 10}) + if err != nil || len(page.Items) != 1 { + t.Fatalf("List() = %d items, %v; want the delivered invitation", len(page.Items), err) + } + requireContactAccess(t, page.Items[0].ContactAccess, domain.InvitationContactAccessNone) +} + +func TestOrganizationAccessIsAvailableWithTheGrantedKindsAfterAnAcceptance(t *testing.T) { + test := newHarness(t) + sent, _ := acceptedForContacts(t, test) + + requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessAvailable, domain.ContactFieldEmail) + page, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 10}) + if err != nil || len(page.Items) != 1 { + t.Fatalf("List() = %d items, %v; want the accepted invitation", len(page.Items), err) + } + requireContactAccess(t, page.Items[0].ContactAccess, domain.InvitationContactAccessAvailable, domain.ContactFieldEmail) +} + +// TestOrganizationAccessAgreesWithTheContactRead checks each state of a grant +// against the read: the view claims available exactly when the read answers. +func TestOrganizationAccessAgreesWithTheContactRead(t *testing.T) { + tests := []struct { + name string + change func(t *testing.T, test *harness, candidateID uuid.UUID, sent domain.OrganizationInvitationView) + want domain.InvitationContactAccess + }{ + { + name: "no change", + change: func(*testing.T, *harness, uuid.UUID, domain.OrganizationInvitationView) {}, + want: domain.InvitationContactAccessAvailable, + }, + { + name: "the C4 revocation stamps the grant and its record", + change: func(t *testing.T, test *harness, _ uuid.UUID, sent domain.OrganizationInvitationView) { + t.Helper() + stored := test.transactor.snapshot().grants[sent.ID].Stored() + revokedAt := sent.DeliveredAt.Add(2 * time.Hour) + stored.RevokedAt, stored.RevocationReason = &revokedAt, string(domain.ContactRevocationConsentRevoked) + revoked, err := domain.RestoreContactGrant(stored) + if err != nil { + t.Fatalf("RestoreContactGrant() error = %v", err) + } + test.setState(func(state *testState) { + state.grants[sent.ID] = revoked + delete(state.consentRecords, sent.ID) + }) + }, + want: domain.InvitationContactAccessClosed, + }, + { + name: "the C4 record is no longer current while the grant is active", + change: func(_ *testing.T, test *harness, _ uuid.UUID, sent domain.OrganizationInvitationView) { + test.setState(func(state *testState) { delete(state.consentRecords, sent.ID) }) + }, + want: domain.InvitationContactAccessClosed, + }, + { + name: "the organization is hidden", + change: func(_ *testing.T, test *harness, candidateID uuid.UUID, _ domain.OrganizationInvitationView) { + test.setState(func(state *testState) { state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] = true }) + }, + want: domain.InvitationContactAccessClosed, + }, + { + name: "the publication is closed", + change: func(_ *testing.T, test *harness, candidateID uuid.UUID, _ domain.OrganizationInvitationView) { + test.setState(func(state *testState) { delete(state.publications, candidateID) }) + }, + want: domain.InvitationContactAccessClosed, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + test := newHarness(t) + sent, candidateID := acceptedForContacts(t, test) + tc.change(t, test, candidateID, sent) + + access := organizationAccess(t, test, sent.ID) + if access.Status != tc.want { + t.Fatalf("contact access = %+v, want %q", access, tc.want) + } + if access.Status == domain.InvitationContactAccessClosed && len(access.Fields) != 0 { + t.Fatalf("closed access lists fields %v", access.Fields) + } + _, readErr := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID) + readable := readErr == nil + if readErr != nil && !errors.Is(readErr, outbound.ErrContactGrantNotFound) { + t.Fatalf("ReadContacts() error = %v, want nil or not found", readErr) + } + if readable != (access.Status == domain.InvitationContactAccessAvailable) { + t.Fatalf("read succeeds = %t while the view says %q", readable, access.Status) + } + }) + } +} + +func TestOrganizationAccessOpensOnlyAGrantThatWasBlockedFromTheStart(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + test.setProfile(t, candidateID, domain.ContactFieldEmail) + test.setTime(sent.DeliveredAt.Add(time.Hour)) + test.publish(candidateID, *sent.DeliveredAt) + test.setState(func(state *testState) { state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] = true }) + + if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, + "accept-blocked-access", domain.ContactFieldEmail)); err != nil { + t.Fatalf("AcceptMine() while hidden error = %v", err) + } + requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessClosed) + + test.setState(func(state *testState) { delete(state.hidden, [2]uuid.UUID{candidateID, test.organizationID}) }) + requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessAvailable, domain.ContactFieldEmail) +} + +func TestOrganizationAccessStaysClosedForARevokedGrantAfterItIsVisibleAgain(t *testing.T) { + test := newHarness(t) + sent, candidateID := acceptedForContacts(t, test) + revokedAt := sent.DeliveredAt.Add(2 * time.Hour) + stored := test.transactor.snapshot().grants[sent.ID].Stored() + stored.RevokedAt, stored.RevocationReason = &revokedAt, string(domain.ContactRevocationVisibilityClosed) + revoked, err := domain.RestoreContactGrant(stored) + if err != nil { + t.Fatalf("RestoreContactGrant() error = %v", err) + } + test.setState(func(state *testState) { state.grants[sent.ID] = revoked }) + requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessClosed) + + // Publishing again and unhiding never reopen a revoked grant. + test.publish(candidateID, revokedAt.Add(time.Hour)) + requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessClosed) +} + +func TestOrganizationAccessIsNotGrantedForADeclinedOrAnExpiredInvitation(t *testing.T) { + t.Run("declined", func(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + if _, err := test.service.DeclineMine(t.Context(), declineCommand(candidateID, sent.ID, sent.Version, + "decline-access", domain.InvitationDeclineOther, nil)); err != nil { + t.Fatalf("DeclineMine() error = %v", err) + } + requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessNone) + }) + t.Run("expired", func(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + test.setTime(*sent.ResponseDeadlineAt) + if expired, err := test.service.GetMine(t.Context(), candidateID, sent.ID); err != nil || expired.State != domain.InvitationExpired { + t.Fatalf("GetMine() at the deadline = %v, %v; want expired", expired.State, err) + } + requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessNone) + }) +} + +func TestOrganizationAccessOfAnotherOrganizationIsNotFound(t *testing.T) { + test := newHarness(t) + sent, _ := acceptedForContacts(t, test) + other := uuid.Must(uuid.NewV7()) + if _, err := test.service.Get(t.Context(), test.actorID, other, sent.ID); !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("Get(other organization) error = %v, want not found", err) + } +} diff --git a/backend/internal/usecase/invitation/contacts.go b/backend/internal/usecase/invitation/contacts.go new file mode 100644 index 0000000..9b434b0 --- /dev/null +++ b/backend/internal/usecase/invitation/contacts.go @@ -0,0 +1,153 @@ +package invitation + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const contactsReadLocation = "invitation.Service.ReadContacts" + +// ReadContacts returns the contacts that the active grant of one invitation +// allows the organization to read now. Only the owner of the organization +// reads contacts in the MVP. Every other case answers ErrContactGrantNotFound, +// which the caller maps to the same not found: no grant of the invitation, a +// grant of another organization, a revoked grant, a revoked C4 record, and a +// profile that the candidate does not publish or has hidden from the +// organization. +// +// The read checks everything on every call, with no cache. It takes the locks +// in the order of the other candidate-scoped reads: the organization and the +// membership (authorizeOwner), the candidate account, the current C2 record, +// the publication, the C4 record, and the grant. A grant read is the only +// read that records an audit event; it does not consume the card-view quota, +// because the contract does not count contact reads against it. +func (service *Service) ReadContacts( + ctx context.Context, + actorID, organizationID, invitationID uuid.UUID, +) (domain.ContactDisclosure, error) { + if actorID == uuid.Nil || organizationID == uuid.Nil { + return domain.ContactDisclosure{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", contactsReadLocation, ErrForbidden) + } + at, err := service.now(contactsReadLocation) + if err != nil { + return domain.ContactDisclosure{}, err + } + var result domain.ContactDisclosure + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + result, err = service.readContactsInTransaction(ctx, unit, actorID, organizationID, invitationID, at) + return err + }) + if err != nil { + return domain.ContactDisclosure{}, fmt.Errorf("%s - run transaction: %w", contactsReadLocation, err) + } + return result, nil +} + +func (service *Service) readContactsInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, organizationID, invitationID uuid.UUID, + at time.Time, +) (domain.ContactDisclosure, error) { + if err := authorizeOwner(ctx, unit, actorID, organizationID, contactsReadLocation); err != nil { + return domain.ContactDisclosure{}, err + } + if invitationID == uuid.Nil { + return domain.ContactDisclosure{}, fmt.Errorf("%s - the nil identifier names no grant: %w", contactsReadLocation, outbound.ErrContactGrantNotFound) + } + // The unlocked read only names the candidate, which never changes for a + // grant, so readableContactGrant can take the visibility locks before the + // grant lock. + grant, err := unit.ContactGrants().GetByInvitation(ctx, organizationID, invitationID) + if err != nil { + return domain.ContactDisclosure{}, fmt.Errorf("%s - read contact grant: %w", contactsReadLocation, err) + } + stored, readable, err := readableContactGrant(ctx, unit, grant, organizationID) + if err != nil { + return domain.ContactDisclosure{}, fmt.Errorf("%s - check contact read: %w", contactsReadLocation, err) + } + if !readable { + return domain.ContactDisclosure{}, fmt.Errorf("%s - the grant does not allow the read now: %w", contactsReadLocation, outbound.ErrContactGrantNotFound) + } + profile, err := unit.CandidateProfiles().Get(ctx, stored.CandidateID()) + if err != nil { + return domain.ContactDisclosure{}, fmt.Errorf("%s - read candidate profile: %w", contactsReadLocation, err) + } + disclosure, err := domain.NewContactDisclosure(stored, profile) + if err != nil { + return domain.ContactDisclosure{}, fmt.Errorf("%s - build disclosure: %w", contactsReadLocation, err) + } + access, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{ + CandidateID: stored.CandidateID(), OrganizationID: organizationID, ActorID: actorID, + Kind: domain.CandidateCardAccessContactRead, ContactFields: stored.Fields().Fields(), OccurredAt: at, + }) + if err != nil { + return domain.ContactDisclosure{}, fmt.Errorf("%s - build access audit: %w", contactsReadLocation, err) + } + if err := unit.PrivacyView().RecordCandidateCardAccess(ctx, access); err != nil { + return domain.ContactDisclosure{}, fmt.Errorf("%s - record access audit: %w", contactsReadLocation, err) + } + return disclosure, nil +} + +// readableContactGrant applies the checks that decide whether the organization +// may read the contacts of a grant now. It takes the visibility locks first and +// then the C4 record and the grant, the order that the revocations follow. It +// reports true only for an active grant under a current consent, while the +// organization may read the profile, and it returns the grant as stored under +// those locks. The caller holds the locks until its transaction ends. +func readableContactGrant( + ctx context.Context, + unit outbound.UnitOfWork, + grant domain.ContactGrant, + organizationID uuid.UUID, +) (domain.ContactGrant, bool, error) { + visible, err := lockContactVisibility(ctx, unit, grant.CandidateID(), organizationID) + if err != nil { + return domain.ContactGrant{}, false, fmt.Errorf("lock visibility: %w", err) + } + if !visible { + return domain.ContactGrant{}, false, nil + } + stored, consentCurrent, err := unit.ContactGrants().LockForRead(ctx, grant) + if err != nil { + return domain.ContactGrant{}, false, fmt.Errorf("lock contact grant: %w", err) + } + return stored, consentCurrent && stored.Status() == domain.ContactGrantActive, nil +} + +// lockContactVisibility share-locks the candidate account, the current C2 +// record, and the publication, in the order of the card reads. It reports +// false when the candidate has no active C2 or the publication is not visible +// to the organization, and it holds the locks until the transaction ends, so a +// hiding or a revocation that commits later waits for the read. +func lockContactVisibility( + ctx context.Context, + unit outbound.UnitOfWork, + candidateID, organizationID uuid.UUID, +) (bool, error) { + repository := unit.PrivacyView() + if err := repository.LockCandidateAccountForView(ctx, candidateID); err != nil { + return false, fmt.Errorf("lock candidate account: %w", err) + } + c2RecordID, err := repository.LockCurrentC2ForView(ctx, candidateID) + if errors.Is(err, outbound.ErrCandidateC2Unavailable) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("lock current C2: %w", err) + } + visible, err := repository.LockVisiblePublicationForView(ctx, organizationID, candidateID, c2RecordID) + if err != nil { + return false, fmt.Errorf("lock visible publication: %w", err) + } + return visible, nil +} diff --git a/backend/internal/usecase/invitation/contacts_test.go b/backend/internal/usecase/invitation/contacts_test.go new file mode 100644 index 0000000..f407be6 --- /dev/null +++ b/backend/internal/usecase/invitation/contacts_test.go @@ -0,0 +1,205 @@ +package invitation + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// testPrivacyView is the visibility barrier of the fakes. A published +// publication has one active C2 record, and a hidden organization may not read +// the profile. The database keeps the stamps; these fakes only answer. +type testPrivacyView struct { + outbound.PrivacyViewRepository + + state *testState +} + +func (unit *testUnit) PrivacyView() outbound.PrivacyViewRepository { + return testPrivacyView{state: unit.state} +} + +func (testPrivacyView) LockCandidateAccountForView(context.Context, uuid.UUID) error { return nil } + +func (repository testPrivacyView) LockCurrentC2ForView(_ context.Context, candidateID uuid.UUID) (uuid.UUID, error) { + publication, ok := repository.state.publications[candidateID] + if !ok || publication.State() != domain.PublicationPublished { + return uuid.Nil, outbound.ErrCandidateC2Unavailable + } + return publication.ConsentRecordID(), nil +} + +func (repository testPrivacyView) LockVisiblePublicationForView(_ context.Context, organizationID, candidateID, _ uuid.UUID) (bool, error) { + publication, ok := repository.state.publications[candidateID] + return ok && publication.State() == domain.PublicationPublished && + !repository.state.hidden[[2]uuid.UUID{candidateID, organizationID}], nil +} + +func (testPrivacyView) RecordCandidateCardAccess(context.Context, domain.CandidateCardAccess) error { + return nil +} + +// LockForRead answers from the stored grant and its C4 record, the way the +// database does: the record must be unrevoked for the grant to be current. +func (repository testContactGrants) LockForRead(_ context.Context, grant domain.ContactGrant) (domain.ContactGrant, bool, error) { + stored, ok := repository.state.grants[grant.InvitationID()] + if !ok || stored.ID() != grant.ID() { + return domain.ContactGrant{}, false, outbound.ErrContactGrantNotFound + } + record, ok := repository.state.consentRecords[grant.InvitationID()] + if !ok { + return stored, false, nil + } + _, revoked := record.RevokedAt() + return stored, !revoked, nil +} + +// acceptedForContacts delivers an invitation to a published candidate who +// holds an email and a phone number, and accepts it for the email only. +func acceptedForContacts(t *testing.T, test *harness) (domain.OrganizationInvitationView, uuid.UUID) { + t.Helper() + sent, candidateID := test.deliveredTo(t) + test.setProfile(t, candidateID, domain.ContactFieldEmail, domain.ContactFieldPhone) + test.setTime(sent.DeliveredAt.Add(time.Hour)) + test.publish(candidateID, *sent.DeliveredAt) + if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, + "accept-for-contacts", domain.ContactFieldEmail)); err != nil { + t.Fatalf("AcceptMine() error = %v", err) + } + return sent, candidateID +} + +func (test *harness) addMember(t *testing.T, organizationID, actorID uuid.UUID, role domain.OrganizationRole) { + t.Helper() + verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC) + test.setState(func(state *testState) { + state.users[actorID] = domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verified} + membership, err := domain.NewMembership(domain.MembershipInput{ + OrganizationID: organizationID, UserID: actorID, Role: role, At: verified, + }) + if err != nil { + t.Fatalf("NewMembership() error = %v", err) + } + state.memberships[[2]uuid.UUID{organizationID, actorID}] = membership + }) +} + +func TestReadContactsReturnsOnlyTheGrantedKindsToTheOwner(t *testing.T) { + test := newHarness(t) + sent, _ := acceptedForContacts(t, test) + + disclosure, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID) + if err != nil { + t.Fatalf("ReadContacts() error = %v", err) + } + if email, ok := disclosure.Email(); !ok || email != "candidate@example.test" { + t.Fatalf("email = %q, %v; want the confirmed address", email, ok) + } + if _, ok := disclosure.Phone(); ok { + t.Fatal("phone was disclosed although the grant names only the email") + } + if len(disclosure.Fields()) != 1 || disclosure.Fields()[0] != domain.ContactFieldEmail { + t.Fatalf("fields = %v, want the email only", disclosure.Fields()) + } + if disclosure.GrantID() != test.transactor.snapshot().grants[sent.ID].ID() { + t.Fatal("the disclosure names another grant than the stored one") + } +} + +func TestReadContactsRefusesEveryOtherActorBeforeTheGrant(t *testing.T) { + test := newHarness(t) + sent, candidateID := acceptedForContacts(t, test) + recruiter := uuid.Must(uuid.NewV7()) + test.addMember(t, test.organizationID, recruiter, domain.OrganizationRoleRecruiter) + outsider := uuid.Must(uuid.NewV7()) + test.addMember(t, uuid.Must(uuid.NewV7()), outsider, domain.OrganizationRoleOwner) + otherOrganization := uuid.Must(uuid.NewV7()) + otherOwner := uuid.Must(uuid.NewV7()) + test.addMember(t, otherOrganization, otherOwner, domain.OrganizationRoleOwner) + + tests := []struct { + name string + actorID uuid.UUID + organizationID uuid.UUID + want error + }{ + {"non-owner member of the organization", recruiter, test.organizationID, outbound.ErrOrganizationManagerRequired}, + {"candidate account", candidateID, test.organizationID, ErrForbidden}, + {"employer without a membership in the organization", outsider, test.organizationID, outbound.ErrOrganizationNotFound}, + {"owner of another organization", otherOwner, otherOrganization, outbound.ErrContactGrantNotFound}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + _, err := test.service.ReadContacts(t.Context(), tc.actorID, tc.organizationID, sent.ID) + if !errors.Is(err, tc.want) { + t.Fatalf("ReadContacts() error = %v, want %v", err, tc.want) + } + }) + } +} + +func TestReadContactsIsClosedWhileTheProfileIsNotReadable(t *testing.T) { + test := newHarness(t) + sent, candidateID := acceptedForContacts(t, test) + publication := test.transactor.snapshot().publications[candidateID] + + test.setState(func(state *testState) { state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] = true }) + if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID); !errors.Is(err, outbound.ErrContactGrantNotFound) { + t.Fatalf("ReadContacts() while hidden error = %v, want not found", err) + } + test.setState(func(state *testState) { + delete(state.hidden, [2]uuid.UUID{candidateID, test.organizationID}) + delete(state.publications, candidateID) + }) + if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID); !errors.Is(err, outbound.ErrContactGrantNotFound) { + t.Fatalf("ReadContacts() without a publication error = %v, want not found", err) + } + // The same grant is readable again once the profile is visible, which + // shows that the refusals above came from the visibility and not the grant. + test.setState(func(state *testState) { state.publications[candidateID] = publication }) + if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID); err != nil { + t.Fatalf("ReadContacts() after publishing again error = %v", err) + } +} + +func TestReadContactsRefusesARevokedGrantOrAnInvitationWithoutOne(t *testing.T) { + test := newHarness(t) + sent, _ := acceptedForContacts(t, test) + grant := test.transactor.snapshot().grants[sent.ID] + stored := grant.Stored() + revokedAt := sent.DeliveredAt.Add(2 * time.Hour) + stored.RevokedAt, stored.RevocationReason = &revokedAt, string(domain.ContactRevocationConsentRevoked) + revoked, err := domain.RestoreContactGrant(stored) + if err != nil { + t.Fatalf("RestoreContactGrant() error = %v", err) + } + test.setState(func(state *testState) { state.grants[sent.ID] = revoked }) + if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID); !errors.Is(err, outbound.ErrContactGrantNotFound) { + t.Fatalf("ReadContacts() of a revoked grant error = %v, want not found", err) + } + + delivered, _ := test.deliveredTo(t) + if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, delivered.ID); !errors.Is(err, outbound.ErrContactGrantNotFound) { + t.Fatalf("ReadContacts() of a delivered invitation error = %v, want not found", err) + } + for _, invitationID := range []uuid.UUID{uuid.Nil, uuid.Must(uuid.NewV7())} { + if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, invitationID); !errors.Is(err, outbound.ErrContactGrantNotFound) { + t.Fatalf("ReadContacts(%v) error = %v, want not found", invitationID, err) + } + } +} + +func TestReadContactsRefusesAConsentRecordThatIsRevoked(t *testing.T) { + test := newHarness(t) + sent, _ := acceptedForContacts(t, test) + test.setState(func(state *testState) { delete(state.consentRecords, sent.ID) }) + if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID); !errors.Is(err, outbound.ErrContactGrantNotFound) { + t.Fatalf("ReadContacts() without a current C4 record error = %v, want not found", err) + } +} diff --git a/backend/internal/usecase/invitation/decline.go b/backend/internal/usecase/invitation/decline.go index 8b315f5..ca3e7d6 100644 --- a/backend/internal/usecase/invitation/decline.go +++ b/backend/internal/usecase/invitation/decline.go @@ -62,13 +62,15 @@ type declineFingerprint struct { // structured reason. In one transaction it checks the candidate, the key, // the invitation, the repeat of the same decline, a terminal state or a // passed deadline, the version, and the state, then moves the invitation to -// declined, stores the decline, and appends the audit event. The decline is -// the candidate's answer for the responsiveness metrics; it creates no -// consent and no contact grant, and the organization sees only the state and -// the time of the answer. +// declined, stores the decline, and appends the audit event. A due expiry is +// applied first. The decline is the candidate's answer for the responsiveness +// metrics; it creates no consent and no contact grant, and the organization +// sees only the state and the time of the answer. // -// Locks: the idempotency record of the candidate's own key and then only the -// invitation row, never the organization, as for the view. +// Locks: the idempotency record of the candidate's own key, then the +// organization lock, then the invitation row. The organization lock is what +// orders a decline against a send of the same pair, so a send never misses a +// decline that committed before it counted the pause. func (service *Service) DeclineMine(ctx context.Context, command DeclineCommand) (domain.CandidateInvitationView, error) { request, err := service.prepareDecline(command) if err != nil { @@ -146,6 +148,20 @@ func (service *Service) declineInTransaction( if !created { return service.replayDecline(ctx, unit, request, command, stored) } + // A decline changes the pause of the organization and the candidate, so it + // takes the organization lock before the invitation row, as every command + // that may change a pair does. The organization of an invitation never + // changes, so the unlocked read names the lock to take. + unlocked, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, false) + if errors.Is(err, outbound.ErrInvitationNotFound) { + return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineNotFound) + } + if err != nil { + return declineOutcome{}, err + } + if err := lockOrganizationFirst(ctx, unit, unlocked.Invitation.OrganizationID(), declineLocation); err != nil { + return declineOutcome{}, err + } entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true) if errors.Is(err, outbound.ErrInvitationNotFound) { return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineNotFound) @@ -158,7 +174,9 @@ func (service *Service) declineInTransaction( // declineFound applies the checks that follow a found invitation: the repeat // of the same decline, a terminal state or a passed deadline, the version, -// and the state, and then stores the decline. +// and the state, and then stores the decline. A delivered invitation whose +// deadline has passed is expired first, so the late decline answers with the +// expired state. func (service *Service) declineFound( ctx context.Context, unit outbound.UnitOfWork, @@ -166,8 +184,16 @@ func (service *Service) declineFound( request declineRequest, entry outbound.CandidateInvitationEntry, ) (declineOutcome, error) { + now, err := service.now(declineLocation) + if err != nil { + return declineOutcome{}, err + } + entry, err = settleCandidateEntry(ctx, unit, entry, now) + if err != nil { + return declineOutcome{}, fmt.Errorf("%s - expire due invitation: %w", declineLocation, err) + } current := entry.Invitation - at := notBefore(request.now, current.UpdatedAt()) + at := notBefore(now, current.UpdatedAt()) if current.State() == domain.InvitationDeclined { previous, err := unit.Invitations().GetDecline(ctx, current.OrganizationID(), current.ID()) if err != nil { diff --git a/backend/internal/usecase/invitation/draft.go b/backend/internal/usecase/invitation/draft.go index 86f5f82..dab65b1 100644 --- a/backend/internal/usecase/invitation/draft.go +++ b/backend/internal/usecase/invitation/draft.go @@ -122,7 +122,7 @@ func (service *Service) createInTransaction( if err := unit.Invitations().Create(ctx, invitation, event); err != nil { return domain.OrganizationInvitationView{}, fmt.Errorf("%s - store draft: %w", createLocation, err) } - view, err := service.view(invitation) + view, err := service.view(ctx, unit, invitation) if err != nil { return domain.OrganizationInvitationView{}, err } @@ -300,7 +300,7 @@ func (service *Service) updateInTransaction( merged := mergeDraft(before, command) changed := before.ChangedFields(merged) if len(changed) == 0 { - return service.view(current) + return service.view(ctx, unit, current) } if command.ExpectedVersion != current.Version() { return domain.OrganizationInvitationView{}, fmt.Errorf("%s - compare expected version: %w", updateLocation, domain.ErrInvitationVersionConflict) @@ -333,7 +333,7 @@ func (service *Service) updateInTransaction( } return domain.OrganizationInvitationView{}, fmt.Errorf("%s - save draft: %w", updateLocation, err) } - return service.view(next) + return service.view(ctx, unit, next) } // mergeDraft applies the fields the command sets over the current content. @@ -407,7 +407,7 @@ func (service *Service) Get(ctx context.Context, actorID, organizationID, invita if err != nil { return fmt.Errorf("%s - read invitation: %w", getLocation, err) } - result, err = service.view(current) + result, err = service.view(ctx, unit, current) return err }) if err != nil { @@ -452,7 +452,7 @@ func (service *Service) List(ctx context.Context, command ListCommand) (Page, er } result = Page{Items: make([]domain.OrganizationInvitationView, 0, len(page.Items)), HasMore: page.HasMore} for _, invitation := range page.Items { - item, err := service.view(invitation) + item, err := service.view(ctx, unit, invitation) if err != nil { return err } diff --git a/backend/internal/usecase/invitation/expire.go b/backend/internal/usecase/invitation/expire.go new file mode 100644 index 0000000..d6cacb2 --- /dev/null +++ b/backend/internal/usecase/invitation/expire.go @@ -0,0 +1,166 @@ +package invitation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" +) + +// ResponseDeadlineJobKind names the scheduled job that expires an invitation +// at its response deadline. The delivery schedules it in its own transaction. +const ResponseDeadlineJobKind = "invitation.response_deadline" + +const ( + responseDeadlineLocation = "invitation.ResponseDeadlineJob.Handle" + scheduleDeadlineLocation = "invitation.scheduleResponseDeadline" +) + +// ResponseDeadlineJob expires a delivered or viewed invitation whose response +// deadline has passed. The job is keyed by its invitation, so a delivery has one +// job, and the job is idempotent: a run that finds the invitation answered or +// expired changes nothing. The expiry creates no consent, no contact grant, and +// no quota change. +type ResponseDeadlineJob struct { + clock func() time.Time +} + +// NewResponseDeadlineJob returns the handler of ResponseDeadlineJobKind. A nil +// clock is the process clock. +func NewResponseDeadlineJob(clock func() time.Time) *ResponseDeadlineJob { + if clock == nil { + clock = time.Now + } + return &ResponseDeadlineJob{clock: clock} +} + +// JobKind is the stable kind name. +func (*ResponseDeadlineJob) JobKind() string { return ResponseDeadlineJobKind } + +// Handle expires the invitation of the job when it still waits for an answer. +// The row is locked before the answer is read, so a candidate command that +// answers at the same moment either wins first, and the job then changes +// nothing, or waits and finds the expiry. The job runs at its due time, which is +// the deadline the invitation stores; a clock that has not reached that deadline +// returns an error, so the job is retried instead of completing unexpired. +func (job *ResponseDeadlineJob) Handle(ctx context.Context, unit outbound.UnitOfWork, scheduled outbound.ClaimedJob) error { + invitationID, err := responseDeadlinePayload(scheduled.Payload) + if err != nil { + return fmt.Errorf("%s - read payload: %w", responseDeadlineLocation, err) + } + current, err := unit.Invitations().GetForDeadline(ctx, invitationID) + if errors.Is(err, outbound.ErrInvitationNotFound) { + return nil + } + if err != nil { + return fmt.Errorf("%s - lock invitation: %w", responseDeadlineLocation, err) + } + if !current.AwaitsAnswer() { + return nil + } + now := job.clock().UTC().Truncate(time.Microsecond) + if !current.ResponseDeadlinePassed(now) { + return fmt.Errorf("%s - the response deadline has not passed by the application clock", responseDeadlineLocation) + } + if _, err := expireDueInvitation(ctx, unit, current, notBefore(now, current.UpdatedAt())); err != nil { + return fmt.Errorf("%s - expire invitation: %w", responseDeadlineLocation, err) + } + return nil +} + +// responseDeadlinePayload reads the invitation that a job names. A payload that +// names no invitation can never run, so it is final. +func responseDeadlinePayload(payload json.RawMessage) (uuid.UUID, error) { + var fields struct { + InvitationID string `json:"invitation_id"` + } + if err := json.Unmarshal(payload, &fields); err != nil { + return uuid.Nil, fmt.Errorf("decode payload: %w", inbound.ErrJobRejected) + } + parsed, err := uuid.Parse(fields.InvitationID) + if err != nil || parsed == uuid.Nil { + return uuid.Nil, fmt.Errorf("payload names no invitation: %w", inbound.ErrJobRejected) + } + return parsed, nil +} + +// scheduleResponseDeadline schedules the expiry of a delivered invitation at +// its response deadline. It runs in the delivery transaction, so the job exists +// exactly when the delivery committed. The first schedule of the key wins, and +// a key that already exists means the delivery ran twice, which is refused. +func scheduleResponseDeadline(ctx context.Context, unit outbound.UnitOfWork, delivered domain.Invitation) error { + snapshot := delivered.Snapshot() + if snapshot.ResponseDeadlineAt == nil { + return fmt.Errorf("%s - a delivered invitation has a response deadline: %w", scheduleDeadlineLocation, domain.ErrInvalidInvitation) + } + payload, err := json.Marshal(map[string]string{"invitation_id": snapshot.ID.String()}) + if err != nil { + return fmt.Errorf("%s - encode payload: %w", scheduleDeadlineLocation, err) + } + job, err := domain.NewScheduledJob(domain.ScheduledJobInput{ + Kind: ResponseDeadlineJobKind, Key: snapshot.ID.String(), DueAt: *snapshot.ResponseDeadlineAt, Payload: payload, + }) + if err != nil { + return fmt.Errorf("%s - build job: %w", scheduleDeadlineLocation, err) + } + scheduled, err := unit.ScheduledJobs().Schedule(ctx, job) + if err != nil { + return fmt.Errorf("%s - schedule job: %w", scheduleDeadlineLocation, err) + } + if !scheduled { + return fmt.Errorf("%s - the deadline job of the invitation exists already: %w", scheduleDeadlineLocation, domain.ErrInvalidInvitation) + } + return nil +} + +// expireDueInvitation stores the expiry of an invitation whose deadline has +// passed at the given time, inside the caller's transaction, and returns the +// invitation as it stands afterwards. The caller holds the row lock. An +// invitation that is not due is returned unchanged. +func expireDueInvitation( + ctx context.Context, + unit outbound.UnitOfWork, + current domain.Invitation, + at time.Time, +) (domain.Invitation, error) { + expired, changed, err := current.Expire(at) + if err != nil { + return domain.Invitation{}, fmt.Errorf("expire invitation: %w", err) + } + if !changed { + return current, nil + } + event, err := expired.ExpiryEvent() + if err != nil { + return domain.Invitation{}, fmt.Errorf("build audit event: %w", err) + } + if err := unit.Invitations().Expire(ctx, current.Version(), expired, event); err != nil { + return domain.Invitation{}, fmt.Errorf("store expiry: %w", err) + } + return expired, nil +} + +// settleCandidateEntry applies the due expiry to an invitation that a candidate +// read or command has locked or is about to read, at the time that command +// decided on. A read that found the invitation due must lock it first; the +// caller holds the lock. +func settleCandidateEntry( + ctx context.Context, + unit outbound.UnitOfWork, + entry outbound.CandidateInvitationEntry, + now time.Time, +) (outbound.CandidateInvitationEntry, error) { + current, err := expireDueInvitation(ctx, unit, entry.Invitation, notBefore(now, entry.Invitation.UpdatedAt())) + if err != nil { + return outbound.CandidateInvitationEntry{}, err + } + entry.Invitation = current + return entry, nil +} diff --git a/backend/internal/usecase/invitation/expire_test.go b/backend/internal/usecase/invitation/expire_test.go new file mode 100644 index 0000000..82d383e --- /dev/null +++ b/backend/internal/usecase/invitation/expire_test.go @@ -0,0 +1,272 @@ +package invitation + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" +) + +func (repository testInvitations) GetForDeadline(_ context.Context, invitationID uuid.UUID) (domain.Invitation, error) { + invitation, ok := repository.state.invitations[invitationID] + if !ok { + return domain.Invitation{}, outbound.ErrInvitationNotFound + } + return invitation, nil +} + +func (repository testInvitations) Expire(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error { + current, ok := repository.state.invitations[next.ID()] + if !ok || current.Version() != expectedVersion || !current.ExpiryDue(next.UpdatedAt()) { + return outbound.ErrInvitationVersionConflict + } + repository.state.invitations[next.ID()] = next + repository.state.events = append(repository.state.events, event) + return nil +} + +func (repository testInvitations) CountPendingNeedInvitations(_ context.Context, organizationID, needID uuid.UUID) (int64, error) { + var count int64 + for _, invitation := range repository.state.invitations { + need := invitation.Snapshot().Need + if invitation.OrganizationID() != organizationID || need == nil || need.NeedID != needID { + continue + } + if state := invitation.State(); state == domain.InvitationDelivered || state == domain.InvitationViewed || state == domain.InvitationCounter { + count++ + } + } + return count, nil +} + +func (repository testInvitations) LatestDeclineTime(_ context.Context, organizationID, candidateID uuid.UUID) (time.Time, bool, error) { + var latest time.Time + found := false + for _, invitation := range repository.state.invitations { + if invitation.OrganizationID() != organizationID || invitation.CandidateID() != candidateID || invitation.State() != domain.InvitationDeclined { + continue + } + if at := *invitation.Snapshot().RespondedAt; !found || at.After(latest) { + latest, found = at, true + } + } + return latest, found, nil +} + +// deadlineJob returns the scheduled deadline job of an invitation, which the +// delivery stored in the transaction of the send. +func (test *harness) deadlineJob(t *testing.T, invitationID uuid.UUID) domain.ScheduledJob { + t.Helper() + job, ok := test.transactor.snapshot().jobs[ResponseDeadlineJobKind+"\x00"+invitationID.String()] + if !ok { + t.Fatalf("no deadline job for invitation %s", invitationID) + } + return job +} + +// runDeadlineJob runs the handler on a claimed job in its own transaction, as +// the worker does, with the given application clock. +func (test *harness) runDeadlineJob(t *testing.T, claimed outbound.ClaimedJob, clock func() time.Time) error { + t.Helper() + handler := NewResponseDeadlineJob(clock) + return test.transactor.WithinTransaction(t.Context(), func(ctx context.Context, unit outbound.UnitOfWork) error { + return handler.Handle(ctx, unit, claimed) + }) +} + +// claimOf turns a stored job into the claim that the worker hands to a handler. +func claimOf(job domain.ScheduledJob) outbound.ClaimedJob { + return outbound.ClaimedJob{Kind: job.Kind(), Key: job.Key(), DueAt: job.DueAt(), Payload: job.Payload()} +} + +func (test *harness) acceptCommand(candidateID, invitationID uuid.UUID, version int64, key string) AcceptCommand { + return AcceptCommand{ + ActorID: candidateID, InvitationID: invitationID, IdempotencyKey: key, ExpectedVersion: version, + TermsVersion: 1, TextVersion: "c4-2026-10-01", Fields: []domain.ContactField{domain.ContactFieldEmail}, + } +} + +func expiryEvents(state testState) []domain.InvitationEvent { + var events []domain.InvitationEvent + for _, event := range state.events { + if event.Kind == domain.InvitationEventExpired { + events = append(events, event) + } + } + return events +} + +func TestDeliveryScheduleTheExpiryJobAtTheResponseDeadline(t *testing.T) { + test := newHarness(t) + sent, _ := test.deliveredTo(t) + job := test.deadlineJob(t, sent.ID) + if job.Kind() != ResponseDeadlineJobKind || job.Key() != sent.ID.String() || !job.DueAt().Equal(*sent.ResponseDeadlineAt) { + t.Fatalf("deadline job = %s/%s due %v, want the invitation key due at its deadline %v", + job.Kind(), job.Key(), job.DueAt(), *sent.ResponseDeadlineAt) + } + var payload map[string]string + if err := json.Unmarshal(job.Payload(), &payload); err != nil || len(payload) != 1 || payload["invitation_id"] != sent.ID.String() { + t.Fatalf("job payload = %s, want only the invitation identifier", job.Payload()) + } +} + +func TestCandidateReadAtTheDeadlineExpiresTheInvitationOnceWithoutAGrant(t *testing.T) { + test := newHarness(t) + sent, candidate := test.deliveredTo(t) + deadline := *sent.ResponseDeadlineAt + charges := len(test.transactor.snapshot().charged) + + test.setTime(deadline.Add(-time.Microsecond)) + before, err := test.service.GetMine(t.Context(), candidate, sent.ID) + if err != nil || before.State != domain.InvitationDelivered { + t.Fatalf("GetMine(one microsecond before the deadline) = %v, %v; want delivered", before.State, err) + } + + test.setTime(deadline) + expired, err := test.service.GetMine(t.Context(), candidate, sent.ID) + if err != nil || expired.State != domain.InvitationExpired || expired.ExpiryReason == nil || *expired.ExpiryReason != domain.InvitationExpiryTimeout { + t.Fatalf("GetMine(at the deadline) = %v, %v; want expired by the timeout", expired.State, err) + } + if !expired.ResponseDeadlineAt.Equal(deadline) || expired.ContactGrant != nil || expired.ContactConsent != nil { + t.Fatalf("expired view has deadline %v, grant %v, and offer %v; want the deadline and no consent or grant", + expired.ResponseDeadlineAt, expired.ContactGrant, expired.ContactConsent) + } + state := test.transactor.snapshot() + if len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.charged) != charges { + t.Fatalf("expiry created %d grants and %d consents and charged %d; want no grant, no consent, and the same charges", + len(state.grants), len(state.consentRecords), len(state.charged)) + } + events := expiryEvents(state) + if len(events) != 1 || events[0].ActorID != uuid.Nil || events[0].Version != expired.Version { + t.Fatalf("expiry events = %+v, want one system event of the expired version", events) + } + + // Later reads show the same invitation and write nothing more. + again, err := test.service.GetMine(t.Context(), candidate, sent.ID) + if err != nil || again.State != domain.InvitationExpired || again.Version != expired.Version || len(expiryEvents(test.transactor.snapshot())) != 1 { + t.Fatalf("second GetMine = %v, %v; want the same expired invitation and no second event", again.State, err) + } +} + +func TestAcceptAtTheDeadlineIsRefusedAndStoresTheExpiry(t *testing.T) { + test := newHarness(t) + sent, candidate := test.deliveredTo(t) + test.setTime(*sent.ResponseDeadlineAt) + command := test.acceptCommand(candidate, sent.ID, sent.Version, "accept-late") + + if _, err := test.service.AcceptMine(t.Context(), command); !errors.Is(err, ErrAnswerBlocked) { + t.Fatalf("AcceptMine(at the deadline) error = %v, want ErrAnswerBlocked", err) + } + state := test.transactor.snapshot() + if state.invitations[sent.ID].State() != domain.InvitationExpired || len(state.grants) != 0 || len(state.consentRecords) != 0 { + t.Fatalf("late acceptance left state %v with %d grants and %d consents", + state.invitations[sent.ID].State(), len(state.grants), len(state.consentRecords)) + } + // The refusal is stored under the key, and the replay refuses the same way. + if _, err := test.service.AcceptMine(t.Context(), command); !errors.Is(err, ErrAnswerBlocked) { + t.Fatalf("AcceptMine(replay) error = %v, want the stored ErrAnswerBlocked", err) + } +} + +func TestViewAndDeclineAtTheDeadlineFindTheExpiry(t *testing.T) { + test := newHarness(t) + sent, candidate := test.deliveredTo(t) + test.setTime(*sent.ResponseDeadlineAt) + + viewed, err := test.service.ViewMine(t.Context(), candidate, sent.ID) + if err != nil || viewed.State != domain.InvitationExpired { + t.Fatalf("ViewMine(at the deadline) = %v, %v; want the expired invitation", viewed.State, err) + } + declineCommand := DeclineCommand{ + ActorID: candidate, InvitationID: sent.ID, IdempotencyKey: "decline-late", ExpectedVersion: viewed.Version, + Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther}, + } + if _, err := test.service.DeclineMine(t.Context(), declineCommand); !errors.Is(err, ErrAnswerBlocked) { + t.Fatalf("DeclineMine(expired) error = %v, want ErrAnswerBlocked", err) + } + if declines := len(test.transactor.snapshot().declines); declines != 0 { + t.Fatalf("a late decline stored %d declines", declines) + } +} + +func TestResponseDeadlineJobExpiresADueInvitationExactlyOnce(t *testing.T) { + test := newHarness(t) + sent, _ := test.deliveredTo(t) + deadline := *sent.ResponseDeadlineAt + claimed := claimOf(test.deadlineJob(t, sent.ID)) + clock := deadline.Add(-time.Second) + now := func() time.Time { return clock } + + if err := test.runDeadlineJob(t, claimed, now); err == nil { + t.Fatal("the deadline job completed before the deadline, want a retry") + } + if state := test.transactor.snapshot(); state.invitations[sent.ID].State() != domain.InvitationDelivered { + t.Fatalf("a job before the deadline changed the invitation to %v", state.invitations[sent.ID].State()) + } + + clock = deadline + if err := test.runDeadlineJob(t, claimed, now); err != nil { + t.Fatalf("deadline job at the deadline error = %v", err) + } + state := test.transactor.snapshot() + if state.invitations[sent.ID].State() != domain.InvitationExpired || len(state.grants) != 0 || len(state.charged) != 1 { + t.Fatalf("job left %v with %d grants and %d charges", state.invitations[sent.ID].State(), len(state.grants), len(state.charged)) + } + if events := expiryEvents(state); len(events) != 1 { + t.Fatalf("job wrote %d expiry events, want one", len(events)) + } + + // A repeat, such as a retry after a crash, finds nothing left to expire. + clock = deadline.Add(time.Hour) + if err := test.runDeadlineJob(t, claimed, now); err != nil { + t.Fatalf("repeated deadline job error = %v", err) + } + if events := expiryEvents(test.transactor.snapshot()); len(events) != 1 { + t.Fatalf("a repeated job wrote %d expiry events, want still one", len(events)) + } +} + +func TestResponseDeadlineJobLeavesAnAnsweredInvitationAlone(t *testing.T) { + test := newHarness(t) + sent, candidate := test.deliveredTo(t) + deadline := *sent.ResponseDeadlineAt + claimed := claimOf(test.deadlineJob(t, sent.ID)) + + declined, err := test.service.DeclineMine(t.Context(), DeclineCommand{ + ActorID: candidate, InvitationID: sent.ID, IdempotencyKey: "decline-before-deadline", ExpectedVersion: sent.Version, + Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther}, + }) + if err != nil { + t.Fatalf("DeclineMine() error = %v", err) + } + if err := test.runDeadlineJob(t, claimed, func() time.Time { return deadline }); err != nil { + t.Fatalf("deadline job for a declined invitation error = %v", err) + } + state := test.transactor.snapshot() + if state.invitations[sent.ID].State() != domain.InvitationDeclined || state.invitations[sent.ID].Version() != declined.Version || len(expiryEvents(state)) != 0 { + t.Fatalf("the job changed a declined invitation to %v at version %d", state.invitations[sent.ID].State(), state.invitations[sent.ID].Version()) + } +} + +func TestResponseDeadlineJobRefusesAPayloadThatNamesNoInvitation(t *testing.T) { + for name, payload := range map[string]json.RawMessage{ + "not an object": json.RawMessage(`[1]`), + "no identifier": json.RawMessage(`{}`), + "nil identifier": json.RawMessage(`{"invitation_id":"00000000-0000-0000-0000-000000000000"}`), + } { + t.Run(name, func(t *testing.T) { + test := newHarness(t) + err := test.runDeadlineJob(t, outbound.ClaimedJob{Kind: ResponseDeadlineJobKind, Payload: payload}, time.Now) + if !errors.Is(err, inbound.ErrJobRejected) { + t.Fatalf("Handle(%s) error = %v, want ErrJobRejected", payload, err) + } + }) + } +} diff --git a/backend/internal/usecase/invitation/pending_limit.go b/backend/internal/usecase/invitation/pending_limit.go new file mode 100644 index 0000000..4de7fd6 --- /dev/null +++ b/backend/internal/usecase/invitation/pending_limit.go @@ -0,0 +1,50 @@ +package invitation + +import ( + "context" + "fmt" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// sendLimitsReached applies the two send limits of the product policy in force +// at the send: the number of invitations that wait for an answer under the +// need, and the pause of the pair of the organization and the candidate after a +// decline. Both answer the same conflict, so the caller refuses the send with +// one state conflict and says nothing about which limit applied. +// +// The pending count is exact because the caller holds the organization lock: +// every send takes that lock first, and every other change of a waiting +// invitation only removes it from the count. An invitation without a need has +// no need limit, and a direct invitation is bounded by the quota alone. +// +// The pause counts a decline only. The planned no-deal state has no operation +// that produces it, so it has no pause yet. +func (service *Service) sendLimitsReached( + ctx context.Context, + unit outbound.UnitOfWork, + command SendCommand, + current domain.Invitation, + at time.Time, +) (bool, error) { + policy, _, err := effectiveInvitationPolicy(ctx, unit, at, sendLocation) + if err != nil { + return false, err + } + if need := current.Snapshot().Need; need != nil { + pending, err := unit.Invitations().CountPendingNeedInvitations(ctx, command.OrganizationID, need.NeedID) + if err != nil { + return false, fmt.Errorf("%s - count pending invitations of the need: %w", sendLocation, err) + } + if pending >= int64(policy.MaxPendingPerNeed) { + return true, nil + } + } + declinedAt, found, err := unit.Invitations().LatestDeclineTime(ctx, command.OrganizationID, current.CandidateID()) + if err != nil { + return false, fmt.Errorf("%s - read the latest decline of the candidate: %w", sendLocation, err) + } + return found && at.Before(declinedAt.Add(policy.RepeatAfterDecline.Duration())), nil +} diff --git a/backend/internal/usecase/invitation/pending_limit_test.go b/backend/internal/usecase/invitation/pending_limit_test.go new file mode 100644 index 0000000..5ccf53f --- /dev/null +++ b/backend/internal/usecase/invitation/pending_limit_test.go @@ -0,0 +1,231 @@ +package invitation + +import ( + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +// needDraft creates a draft under the need for a new visible candidate. The +// need is one stored requirements version of the organization. +func (test *harness) needDraft(t *testing.T, need uuid.UUID) domain.OrganizationInvitationView { + t.Helper() + test.transactor.state.needVersions[[3]string{test.organizationID.String(), need.String(), "1"}] = true + handle, _ := test.showCandidate(t) + command := test.createCommand(handle, "create-need-"+uuid.NewString()) + command.Need = &domain.InvitationNeedRef{NeedID: need, RequirementsVersion: 1} + view, err := test.service.Create(t.Context(), command) + if err != nil { + t.Fatalf("Create(under the need) error = %v", err) + } + return view +} + +func TestSendRefusesTheTwentyFirstWaitingInvitationOfANeed(t *testing.T) { + test := newHarness(t) + test.quotaLeft = 100 + need := uuid.Must(uuid.NewV7()) + drafts := make([]domain.OrganizationInvitationView, 0, 21) + for range 21 { + drafts = append(drafts, test.needDraft(t, need)) + } + for index, draft := range drafts[:20] { + if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, fmt.Sprint("send-", index))); err != nil { + t.Fatalf("Send(%d) error = %v, want the twenty waiting invitations to be allowed", index, err) + } + } + last := drafts[20] + if _, err := test.service.Send(t.Context(), test.sendCommand(last.ID, last.Version, "send-over-limit")); !errors.Is(err, ErrSendBlocked) { + t.Fatalf("Send(21st waiting) error = %v, want ErrSendBlocked", err) + } + state := test.transactor.snapshot() + if state.invitations[last.ID].State() != domain.InvitationDraft || len(state.charged) != 20 { + t.Fatalf("a refused send changed the draft to %v or charged %d invitations", state.invitations[last.ID].State(), len(state.charged)) + } + // The refusal is stored under its key and replayed. + if _, err := test.service.Send(t.Context(), test.sendCommand(last.ID, last.Version, "send-over-limit")); !errors.Is(err, ErrSendBlocked) { + t.Fatalf("Send(replay of the refusal) error = %v, want ErrSendBlocked", err) + } +} + +func TestConcurrentSendsOfTheTwentiethWaitingInvitationLetOnlyOneThrough(t *testing.T) { + test := newHarness(t) + test.quotaLeft = 100 + need := uuid.Must(uuid.NewV7()) + for index := range 19 { + draft := test.needDraft(t, need) + if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, fmt.Sprint("nineteen-", index))); err != nil { + t.Fatalf("Send(%d) error = %v", index, err) + } + } + first, second := test.needDraft(t, need), test.needDraft(t, need) + + var group sync.WaitGroup + errs := make([]error, 2) + for index, draft := range []domain.OrganizationInvitationView{first, second} { + group.Go(func() { + _, errs[index] = test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, fmt.Sprint("race-", index))) + }) + } + group.Wait() + + admitted, refused := 0, 0 + for _, err := range errs { + switch { + case err == nil: + admitted++ + case errors.Is(err, ErrSendBlocked): + refused++ + default: + t.Fatalf("concurrent Send() error = %v", err) + } + } + if admitted != 1 || refused != 1 { + t.Fatalf("admitted %d and refused %d of two sends with nineteen waiting; want one each", admitted, refused) + } + count := 0 + for _, draft := range []domain.OrganizationInvitationView{first, second} { + view, err := test.service.Get(t.Context(), test.actorID, test.organizationID, draft.ID) + if err != nil { + t.Fatalf("Get(%s) error = %v", draft.ID, err) + } + if view.State == domain.InvitationDelivered { + count++ + } + } + if count != 1 { + t.Fatalf("%d of the two race invitations were delivered; want exactly one", count) + } +} + +func TestLeavingTheWaitingStateFreesTheNeedSlotWithoutReturningTheQuota(t *testing.T) { + test := newHarness(t) + test.quotaLeft = 100 + need := uuid.Must(uuid.NewV7()) + sent := make([]domain.OrganizationInvitationView, 0, 20) + for index := range 20 { + draft := test.needDraft(t, need) + view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, fmt.Sprint("fill-", index))) + if err != nil { + t.Fatalf("Send(%d) error = %v", index, err) + } + sent = append(sent, view) + } + blocked := test.needDraft(t, need) + if _, err := test.service.Send(t.Context(), test.sendCommand(blocked.ID, blocked.Version, "blocked")); !errors.Is(err, ErrSendBlocked) { + t.Fatalf("Send(full need) error = %v, want ErrSendBlocked", err) + } + + // The first invitation expires at its deadline, which frees one place. + deadline := *sent[0].ResponseDeadlineAt + if err := test.runDeadlineJob(t, claimOf(test.deadlineJob(t, sent[0].ID)), func() time.Time { return deadline }); err != nil { + t.Fatalf("deadline job error = %v", err) + } + chargesBefore := len(test.transactor.snapshot().charged) + if view, err := test.service.Send(t.Context(), test.sendCommand(blocked.ID, blocked.Version, "after-expiry")); err != nil || view.State != domain.InvitationDelivered { + t.Fatalf("Send(after one expiry) = %v, %v; want delivered", view.State, err) + } + if chargesAfter := len(test.transactor.snapshot().charged); chargesAfter != chargesBefore+1 { + t.Fatalf("charges went from %d to %d; the expiry must not return quota and the new send must charge once", chargesBefore, chargesAfter) + } +} + +func TestPauseAfterADeclineHoldsForThirtyDaysForEveryNeedAndMember(t *testing.T) { + test := newHarness(t) + test.quotaLeft = 100 + sent, candidate := test.deliveredTo(t) + declinedAt := sent.DeliveredAt.Add(time.Hour) + test.setTime(declinedAt) + if _, err := test.service.DeclineMine(t.Context(), DeclineCommand{ + ActorID: candidate, InvitationID: sent.ID, IdempotencyKey: "decline-pause", ExpectedVersion: sent.Version, + Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther}, + }); err != nil { + t.Fatalf("DeclineMine() error = %v", err) + } + + // A second owner of the same organization, with another need. + secondOwner := uuid.Must(uuid.NewV7()) + verified := declinedAt.Add(-time.Hour) + test.transactor.state.users[secondOwner] = domain.User{ID: secondOwner, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verified} + membership, err := domain.NewOwnerMembership(test.organizationID, secondOwner, declinedAt) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + test.transactor.state.memberships[[2]uuid.UUID{test.organizationID, secondOwner}] = membership + other := uuid.Must(uuid.NewV7()) + test.transactor.state.needVersions[[3]string{test.organizationID.String(), other.String(), "1"}] = true + handle, err := test.key.ForOrganization(test.organizationID, candidate) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + draftOther := func(key string) domain.OrganizationInvitationView { + t.Helper() + command := test.createCommand(handle, key) + command.ActorID = secondOwner + command.Need = &domain.InvitationNeedRef{NeedID: other, RequirementsVersion: 1} + view, err := test.service.Create(t.Context(), command) + if err != nil { + t.Fatalf("Create(%s) error = %v", key, err) + } + return view + } + draft := draftOther("create-pause") + sendAs := func(view domain.OrganizationInvitationView, key string) error { + command := test.sendCommand(view.ID, view.Version, key) + command.ActorID = secondOwner + _, err := test.service.Send(t.Context(), command) + return err + } + + test.setTime(declinedAt.Add(29 * 24 * time.Hour)) + if err := sendAs(draft, "send-day-29"); !errors.Is(err, ErrSendBlocked) { + t.Fatalf("Send(day 29 after the decline) error = %v, want ErrSendBlocked", err) + } + + test.setTime(declinedAt.Add(30 * 24 * time.Hour)) + if err := sendAs(draft, "send-day-30"); err != nil { + t.Fatalf("Send(day 30 after the decline) error = %v, want the pause to be over", err) + } +} + +func TestPauseAfterADeclineDoesNotHoldAnotherCandidate(t *testing.T) { + test := newHarness(t) + test.quotaLeft = 100 + sent, candidate := test.deliveredTo(t) + test.setTime(sent.DeliveredAt.Add(time.Hour)) + if _, err := test.service.DeclineMine(t.Context(), DeclineCommand{ + ActorID: candidate, InvitationID: sent.ID, IdempotencyKey: "decline-other", ExpectedVersion: sent.Version, + Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther}, + }); err != nil { + t.Fatalf("DeclineMine() error = %v", err) + } + next, _, _ := test.draftFor(t, nil) + if _, err := test.service.Send(t.Context(), test.sendCommand(next.ID, next.Version, "send-other-candidate")); err != nil { + t.Fatalf("Send(another candidate) error = %v, want delivered", err) + } +} + +// The pause is judged only from declines, so an invitation that expired is +// not a decline and starts no pause. +func TestAnExpiredInvitationStartsNoPause(t *testing.T) { + test := newHarness(t) + test.quotaLeft = 100 + sent, candidate := test.deliveredTo(t) + test.setTime(*sent.ResponseDeadlineAt) + if _, err := test.service.GetMine(t.Context(), candidate, sent.ID); err != nil { + t.Fatalf("GetMine(expiry) error = %v", err) + } + next, _, _ := test.draftFor(t, nil) + if _, err := test.service.Send(t.Context(), test.sendCommand(next.ID, next.Version, "send-after-expiry")); err != nil { + t.Fatalf("Send(after an expiry of another invitation) error = %v", err) + } + if _, found, err := (testInvitations{state: &test.transactor.state}).LatestDeclineTime(t.Context(), test.organizationID, candidate); err != nil || found { + t.Fatalf("LatestDeclineTime() = %v, %v; an expiry must not count as a decline", found, err) + } +} diff --git a/backend/internal/usecase/invitation/send.go b/backend/internal/usecase/invitation/send.go index fa192ef..2496334 100644 --- a/backend/internal/usecase/invitation/send.go +++ b/backend/internal/usecase/invitation/send.go @@ -66,10 +66,11 @@ type sendOutcome struct { // Send delivers the current terms version of a draft to the candidate's // inbox. In one transaction it checks the owner, the key, the invitation, its -// version and state, and the current visibility of the candidate, spends one -// invitation of the organization quota, records the delivery with its -// deadline and the audit event, and writes the outbox events of the -// notification. The internal sending step is never visible: a success means +// version and state, the current visibility of the candidate, the pending limit +// of the need, and the pause after a decline; it then spends one invitation of +// the organization quota, records the delivery with its deadline, the audit +// event, and the expiry job at the deadline, and writes the outbox events of +// the notification. The internal sending step is never visible: a success means // the invitation is already delivered. A send of an invitation that was // already delivered answers with its current state and charges nothing. func (service *Service) Send(ctx context.Context, command SendCommand) (domain.OrganizationInvitationView, error) { @@ -126,8 +127,9 @@ func (service *Service) prepareSend(command SendCommand) (sendRequest, error) { // sendInTransaction follows the order of checks of the contract after the // HTTP boundary: the owner, the key, the invitation (404, stored), the repeat -// of a completed send (200), the version (412, not stored), the state and the -// visibility of the candidate (409, stored), and the quota (429, not stored). +// of a completed send (200), the version (412, not stored), the state, the +// visibility of the candidate, the pending limit, and the pause (409, stored), +// and the quota (429, not stored). // The locks follow the order of every invitation command: the organization, // the membership, the invitation row, and then the cohort of the cards. func (service *Service) sendInTransaction( @@ -170,23 +172,52 @@ func (service *Service) sendInTransaction( if current.State() != domain.InvitationDraft { return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendStateConflict) } - visible, err := service.candidateStillVisible(ctx, unit, command, current) + at, admitted, err := service.admitSend(ctx, unit, command, current) if err != nil { return sendOutcome{}, err } - if !visible { + if !admitted { return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendStateConflict) } if err := service.chargeQuota(ctx, unit, command, current); err != nil { return sendOutcome{}, err } - delivered, err := service.deliver(ctx, unit, command, current, request.now) + delivered, err := service.deliver(ctx, unit, command, current, at) if err != nil { return sendOutcome{}, err } return service.completeSend(ctx, unit, request, delivered) } +// admitSend applies the rules that refuse a send with a state conflict: the +// visibility of the candidate, then the pending limit of the need and the pause +// after a decline. It returns the time of the decision, which the caller uses for +// the delivery, and whether the send is admitted. The decision is made at the time +// the send holds the organization lock, not at the time it started to wait for it. +func (service *Service) admitSend( + ctx context.Context, + unit outbound.UnitOfWork, + command SendCommand, + current domain.Invitation, +) (time.Time, bool, error) { + visible, err := service.candidateStillVisible(ctx, unit, command, current) + if err != nil { + return time.Time{}, false, err + } + if !visible { + return time.Time{}, false, nil + } + at, err := service.now(sendLocation) + if err != nil { + return time.Time{}, false, err + } + limited, err := service.sendLimitsReached(ctx, unit, command, current, at) + if err != nil { + return time.Time{}, false, err + } + return at, !limited, nil +} + // candidateStillVisible runs the visibility barrier of the card read again: // a draft keeps its candidate after a revoked publication C2, a hiding of the // organization, or a cohort that fell below its minimum, and none of them may @@ -258,6 +289,11 @@ func (service *Service) deliver( } return domain.Invitation{}, fmt.Errorf("%s - store delivery: %w", sendLocation, err) } + // The expiry at the deadline is scheduled in the delivery transaction, so no + // delivered invitation exists without its job. + if err := scheduleResponseDeadline(ctx, unit, delivered); err != nil { + return domain.Invitation{}, fmt.Errorf("%s - schedule response deadline: %w", sendLocation, err) + } if err := service.notifier.InvitationDelivered(ctx, unit, delivered); err != nil { return domain.Invitation{}, fmt.Errorf("%s - record notification: %w", sendLocation, err) } @@ -271,7 +307,7 @@ func (service *Service) completeSend( request sendRequest, invitation domain.Invitation, ) (sendOutcome, error) { - view, err := service.view(invitation) + view, err := service.view(ctx, unit, invitation) if err != nil { return sendOutcome{}, err } diff --git a/backend/internal/usecase/invitation/service.go b/backend/internal/usecase/invitation/service.go index 192e102..45f3e9d 100644 --- a/backend/internal/usecase/invitation/service.go +++ b/backend/internal/usecase/invitation/service.go @@ -142,20 +142,30 @@ func (service *Service) now(location string) (time.Time, error) { return now, nil } -// view is the invitation as its organization reads it. The salary indicator -// and the contact access are not derived from the candidate's minimum or from -// a grant yet: the indicator is not_available, the least revealing value, and -// no grant exists before an acceptance. -func (service *Service) view(invitation domain.Invitation) (domain.OrganizationInvitationView, error) { +// view is the invitation as its organization reads it. The contact access is +// derived in the caller's transaction from the grant of the invitation, with +// the checks of the contact read, so the view shows what a read would decide +// at that time. The salary indicator is not derived from the candidate's +// minimum yet, so it stays not_available, the least revealing value. +func (service *Service) view( + ctx context.Context, + unit outbound.UnitOfWork, + invitation domain.Invitation, +) (domain.OrganizationInvitationView, error) { + const location = "invitation.Service.view" handle, err := service.pseudonymKey.ForOrganization(invitation.OrganizationID(), invitation.CandidateID()) if err != nil { - return domain.OrganizationInvitationView{}, fmt.Errorf("invitation.Service.view - derive candidate alias: %w", err) + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - derive candidate alias: %w", location, err) + } + access, err := contactAccessOf(ctx, unit, invitation) + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - derive contact access: %w", location, err) } return domain.OrganizationInvitationView{ InvitationSnapshot: invitation.Snapshot(), CandidateHandle: handle, SalaryFit: domain.InvitationSalaryNotAvailable, - ContactAccess: domain.InvitationContactAccessNone, + ContactAccess: access, }, nil } diff --git a/backend/internal/usecase/invitation/service_test.go b/backend/internal/usecase/invitation/service_test.go index ef283d7..e71930f 100644 --- a/backend/internal/usecase/invitation/service_test.go +++ b/backend/internal/usecase/invitation/service_test.go @@ -62,6 +62,8 @@ type testState struct { // and notified the delivered invitations that were notified. charged []uuid.UUID notified []uuid.UUID + // jobs holds the scheduled jobs by kind and key. + jobs map[string]domain.ScheduledJob } func newTestState() testState { @@ -80,6 +82,7 @@ func newTestState() testState { profiles: map[uuid.UUID]domain.CandidateProfile{}, publications: map[uuid.UUID]domain.Publication{}, hidden: map[[2]uuid.UUID]bool{}, + jobs: map[string]domain.ScheduledJob{}, } } @@ -136,6 +139,9 @@ func (state testState) clone() testState { } cloned.charged = slices.Clone(state.charged) cloned.notified = slices.Clone(state.notified) + for key, job := range state.jobs { + cloned.jobs[key] = job + } return cloned } @@ -193,6 +199,26 @@ func (unit *testUnit) InvitationSendResults() outbound.InvitationSendResultRepos func (unit *testUnit) InvitationDeclineResults() outbound.InvitationDeclineResultRepository { return testInvitations{state: unit.state} } +func (unit *testUnit) ScheduledJobs() outbound.JobScheduler { return testJobs{state: unit.state} } + +// testJobs keeps the scheduled jobs of one transaction: the first schedule of a +// kind and key wins, as in the database. +type testJobs struct { + state *testState +} + +func (jobs testJobs) Schedule(_ context.Context, job domain.ScheduledJob) (bool, error) { + key := job.Kind() + "\x00" + job.Key() + if _, exists := jobs.state.jobs[key]; exists { + return false, nil + } + jobs.state.jobs[key] = job + return true, nil +} + +func (jobs testJobs) Cancel(context.Context, string, string) (bool, error) { + return false, errors.New("testJobs.Cancel - not used by the invitation usecases") +} type testUsers struct { outbound.UserRepository @@ -542,7 +568,7 @@ func TestCreateStoresADraftForAVisibleCandidateWithTheDefaultPeriod(t *testing.T } if view.State != domain.InvitationDraft || view.Version != 1 || view.TermsVersion != 1 || view.ResponsePeriodDays != 7 || view.CandidateHandle != handle || view.SalaryFit != domain.InvitationSalaryNotAvailable || - view.ContactAccess != domain.InvitationContactAccessNone || view.ResponseDeadlineAt != nil { + view.ContactAccess.Status != domain.InvitationContactAccessNone || len(view.ContactAccess.Fields) != 0 || view.ResponseDeadlineAt != nil { t.Fatalf("created view = %+v, want an unsent version 1 with the default period for the card handle", view.InvitationSnapshot) } state := test.transactor.snapshot() diff --git a/backend/internal/usecase/invitation/view.go b/backend/internal/usecase/invitation/view.go index 7b37018..56bad6e 100644 --- a/backend/internal/usecase/invitation/view.go +++ b/backend/internal/usecase/invitation/view.go @@ -18,10 +18,11 @@ const ( ) // GetMine reads one invitation delivered to the session candidate with the -// current terms. Reading has no side effect: it never records a view, so a -// prefetch or a cache refresh never changes what the organization sees. A -// draft, an invitation of another candidate, and an unknown identifier are -// not found alike. +// current terms. Reading never records a view, so a prefetch or a cache refresh +// never changes what the organization sees. The one change a read can cause is +// the due expiry: a delivered or viewed invitation read at its deadline or later +// is expired first, and the response shows it. A draft, an invitation of another +// candidate, and an unknown identifier are not found alike. func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) { if actorID == uuid.Nil { return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", getMineLocation, ErrForbidden) @@ -39,6 +40,19 @@ func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid. if err != nil { return err } + if entry.Invitation.ExpiryDue(now) { + // The expiry writes, so the row is locked, read again, and judged at + // the time that the lock is held. + if entry, err = readCandidateEntry(ctx, unit, actorID, invitationID, true); err != nil { + return err + } + if now, err = service.now(getMineLocation); err != nil { + return err + } + if entry, err = settleCandidateEntry(ctx, unit, entry, now); err != nil { + return fmt.Errorf("%s - expire due invitation: %w", getMineLocation, err) + } + } view, err = service.candidateView(ctx, unit, entry, now) return err }) @@ -51,8 +65,9 @@ func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid. // ViewMine records that the session candidate opened the terms. A delivered // invitation moves to viewed with the next version and keeps its deadline; // every other state, and a view at the deadline or later, changes nothing and -// returns the invitation as it is. The command is idempotent by its effect, -// so it takes neither a key nor an expected version. +// returns the invitation as it is. A due expiry is applied first. The command +// is idempotent by its effect, so it takes neither a key nor an expected +// version. // // Locks: only the invitation row, never the organization. A candidate // command therefore never holds the row while it waits for an organization @@ -62,12 +77,8 @@ func (service *Service) ViewMine(ctx context.Context, actorID, invitationID uuid if actorID == uuid.Nil { return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", viewMineLocation, ErrForbidden) } - now, err := service.now(viewMineLocation) - if err != nil { - return domain.CandidateInvitationView{}, err - } var view domain.CandidateInvitationView - err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := authorizeCandidate(ctx, unit, actorID); err != nil { return err } @@ -75,6 +86,13 @@ func (service *Service) ViewMine(ctx context.Context, actorID, invitationID uuid if err != nil { return err } + now, err := service.now(viewMineLocation) + if err != nil { + return err + } + if entry, err = settleCandidateEntry(ctx, unit, entry, now); err != nil { + return fmt.Errorf("%s - expire due invitation: %w", viewMineLocation, err) + } current := entry.Invitation viewed, changed, err := current.RecordView(notBefore(now, current.UpdatedAt())) if err != nil { diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index d6f209a..d84ff67 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -174,7 +174,7 @@ The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts fini ### Scheduled jobs -Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. One product handler is registered in `jobHandlers()` (`backend/internal/bootstrap/jobs.go`): `assessment.signal_review`, which computes the [assessment review band](#assessment-signals-and-the-review-band). The tests also use a test-only kind. The first planned deadline kind is the invitation response deadline. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs). +Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. Two product handlers are registered in `jobHandlers()` (`backend/internal/bootstrap/jobs.go`): `assessment.signal_review`, which computes the [assessment review band](#assessment-signals-and-the-review-band), and `invitation.response_deadline`, which moves an invitation to `expired` when its response deadline passes ([Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry)). The tests also use a test-only kind. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs). Scheduling. A usecase calls `unit.ScheduledJobs().Schedule(ctx, job)` in its business transaction, so the job exists exactly when the change that needs it committed, and `Cancel(ctx, kind, key)` stops a job that has not finished. A job has a kind (the handler name, a lowercase dotted name), a key that identifies the logical job within its kind (for example an aggregate ID), a due time from the application clock, an optional attempt limit, and a payload: a flat JSON object of identifiers of at most 2 KiB. Neither the key nor the payload may contain personal data; the handler reads everything else from the source tables when it runs. `(kind, key)` is unique and the first schedule wins: a repeat inserts nothing (`INSERT ... ON CONFLICT DO NOTHING`) and reports `false`, also after the job ran or was canceled. This is insert-or-ignore rather than an upsert on purpose: a repeated command cannot move a deadline that must not be reset, and a stale writer cannot revive a finished job. A new occurrence needs a new key, for example `:`. @@ -184,7 +184,7 @@ Claim and lease. The worker claims up to `JOBS_BATCH_SIZE` jobs in one statement Run and completion. Each job runs in its own READ COMMITTED transaction: it sets `statement_timeout` and `idle_in_transaction_session_timeout` to the lease duration, locks the job row with a guard on `status = running`, the lease owner, and the attempt number, calls the handler with an `outbound.UnitOfWork` of the same transaction, marks the job `done` with the same guard, and commits. The handler effect and the completion therefore commit together: for an effect that stays in PostgreSQL a job is applied exactly once even when workers race, restart, or a lease expires. While the handler runs the row is locked, so another worker's claim skips it even after the lease expired by the clock; when the guard fails because the job was canceled or reclaimed, the handler is not called and nothing commits (`lease_lost`). A handler may cancel its own job through the unit, for example an expiry that also cancels the deadline job it stands for: the completion then finds the job `cancelled` in its own transaction, treats it as finished, and commits the effect, and the job stays `cancelled`. Any other change of its own job by the handler rolls back and makes the job `dead` with `completion_conflict`, because it would repeat on every attempt. A handler whose effect leaves the database, such as a call to another service, can repeat after a crash between that call and the commit and must be idempotent itself. The handler context ends with the renewed lease. A handler decides by `job.DueAt`, the deadline the job stands for, which a retry keeps, not by when it happens to run. -Lock order. The handler holds the job row lock and may then lock product rows. A business transaction that cancels a job, such as accepting an invitation at its deadline, should call `Cancel` before it locks those product rows. `Cancel` waits for a handler transaction in progress: after its commit the job is done and `Cancel` reports `false`, so the caller sees the expiry; otherwise the job is canceled and the worker finds its lease gone. The opposite order can deadlock, which PostgreSQL resolves by aborting one side with `ErrTransactionConflict`; the job side counts a failed attempt and retries. +Lock order. The handler holds the job row lock and may then lock product rows. A business transaction that cancels a job should call `Cancel` before it locks those product rows. A candidate's answer does not cancel the response deadline job: the run finds the answered invitation and changes nothing ([Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry)). `Cancel` waits for a handler transaction in progress: after its commit the job is done and `Cancel` reports `false`, so the caller sees the finished job; otherwise the job is canceled and the worker finds its lease gone. The opposite order can deadlock, which PostgreSQL resolves by aborting one side with `ErrTransactionConflict`; the job side counts a failed attempt and retries. Failures. A failed attempt rolls back its effect; a second statement, guarded the same way, records it. A handler error, a lease timeout, a deadlock or serialization failure (`conflict`), or a commit that PostgreSQL refuses (`effect_rejected`, for a handler that ignored a failed statement or a deferred constraint) moves the job to `failed` with `available_at = now + backoff`, where the backoff is the shared `worker/retry` delay from `JOBS_BACKOFF_INITIAL`, doubling up to `JOBS_BACKOFF_MAX`, with jitter. `inbound.ErrJobRejected`, a handler panic, and `completion_conflict` are final, also when they happen during shutdown. After the last allowed attempt (the job's own limit or `JOBS_MAX_ATTEMPTS`) the job is `dead`: it is logged at error level and counted as `dead`, and it needs an operator. `last_error_class` stores only a bounded class; a sanitized reason appears only in the log. A database failure outside the handler is not the job's fault: the worker releases its unfinished jobs without counting the attempt and backs off before the next claim, so an outage causes no hot loop. When the failure record itself cannot be written, the job keeps its started lease; a later claim then counts it as `lease_expired`, which on the last attempt makes it dead. @@ -805,7 +805,7 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo - `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. -- `ConsentRevocationEffects.Apply` runs in the same `UnitOfWork` transaction as the ledger revocation. It closes the current publication's effective C2 access only when that publication references one of the revoked records, appends its privacy-history event once, and writes bounded outbox intents from the exact revoked records. A future C2/C4 grant adapter must bind each downstream grant to its source consent-record ID and synchronously close that old grant in this transaction; a later grant may open only a new record-bound grant, never reopen an old one. C5 readers and importers must check the current ledger and fail closed; an outbox message alone does not authorize access or prove that an external system deleted data. +- `ConsentRevocationEffects.Apply` runs in the same `UnitOfWork` transaction as the ledger revocation. It closes the current publication's effective C2 access only when that publication references one of the revoked records, appends its privacy-history event once, and writes bounded outbox intents from the exact revoked records. The contact grants of the revoked records are closed in this transaction (C4 by record, C2 for every grant of the candidate; see [Contact reads and revocation](#contact-reads-and-revocation)); a later grant may open only a new record-bound grant, never reopen an old one. C5 readers and importers must check the current ledger and fail closed; an outbox message alone does not authorize access or prove that an external system deleted data. ### Consent usecase @@ -922,7 +922,7 @@ Decisions: - The lapse of `looking` comes from the versioned policy and only narrows. The 30 days are `search_status.searching_confirmation_interval_days` of the effective `product` policy version (demo version 1: 30), so the owner changes them by publishing a new policy version, not by a constant or configuration. A confirmation fixes `lapses_at` and stores `policy_version_id`, so a later policy change moves no stored time and every row names the policy it was made under, as the policy section requires. The lapse itself is computed (`SearchStatus.Effective(now)` is `looking` only while `now` is before `lapses_at`) and never written: no process, job, or clock skew can turn an expired status into anything more public, the stored row keeps what the candidate said, and the read model shows `value` `not_looking` with `lapsed` true. The candidate confirms again with `looking`, which replaces `confirmed_at`. A reminder before the lapse is a planned notification, not part of this task. - Versions. Each setting has its own `version` (0 is the absence of a row), checked in the statement like the profile: `UpdateCandidatePublication` and `UpdateCandidateSearchStatus` change a row only when the stored version equals the one the caller read, and no row returns for a stale one (412 `version_conflict`). The domain order is the contract's: a version above the current one is a conflict, an unchanged effective setting is a success even over a stale version, any other change over a stale version is a conflict, and a publication needs an active C2. Because the settings are independent, a change of one never makes another stale. - Hidden organizations belong to the candidate and are safe against enumeration. The record is the candidate's: no organization-visible query selects it, and an organization cannot tell a hidden candidate from an unpublished one. Hiding by identifier must not become a way to ask whether an organization exists. The foreign key refuses an unknown organization (SQLSTATE 23503), and the usecase must answer that exactly like an organization the candidate cannot see: the same 404 `not_found` with the same body, without a different timing or code. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned, an open question), so a hiding reveals nothing the candidate could not already read. Lifting a hiding is a DELETE that answers 204 for any well-formed identifier, so it reveals nothing at all, and its history event is written only when a row was deleted. The identifiers are random UUIDv7 values, and the general rate limit covers the probing that remains. -- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke the grant with the reason `visibility_closed` in the same transaction as the change (the invitation contract fixes the reason). That belongs to the usecases that do not exist yet; this task stores the settings and defines the contract. The search status never closes a grant. +- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke the grant with the reason `visibility_closed` in the same transaction as the change (the invitation contract fixes the reason). The closing is implemented; see [Contact reads and revocation](#contact-reads-and-revocation). The search status never closes a grant. - History instead of a field scope. The C2 record proves the consent to the publication text, and `candidate_privacy_events` keeps what the consent ledger note asked for: the published field set and its changes with their times and the C2 record behind each. A revocation of C2 and a lapse are computed, not events. Whether C2 needs its own field scope as a consent under article 10.1 of 152-FZ is still a legal question (see the consent ledger). - Privacy. The tables hold identifiers, card field codes, and times; no profile value, name, contact, or file (a test lists the columns). `Publication`, `SearchStatus`, `HiddenOrganization`, and `PrivacyEvent` log only identifiers, versions, and kinds. No query selects another account's row: every statement is scoped by `user_id`. The adapter must report only the SQLSTATE and the constraint name, as the others do. @@ -962,11 +962,11 @@ Decisions: - Update. The body replaces the fields it sets, and `terms` is always replaced as a whole. The order is the one of the contract: a body that changes nothing returns the current invitation with 200 even when the version is stale, then the version (412 `version_conflict`), then the state (409 `state_conflict`, only a draft changes), then the rules (400 with a pointer). A change of the terms appends the next terms version; a change of the period or the need keeps it. A new period is checked against the policy in force and records its version. - Response period. The options and the default come from the `invitations` section of the effective product policy (3, 7, 14; default 7), and the draft stores the version it used. - Locks. A create and an update both take the exclusive organization lock first (`CompanyQuotaRepository.LockOrganization`), like a card read and a search, and only then the share lock of the membership check, the cohort locks of a create, or the invitation row lock of an update, so commands of one organization queue instead of deadlocking on a lock upgrade, and a later command that also charges the organization, such as sending, keeps the same order. An update locks the invitation row with a statement of its own (`LockInvitation`) and reads it afterwards: a locking read joined to the terms table would, after waiting for a concurrent commit, pair the new `terms_version` with the terms row it fetched before the wait and find nothing. A create repeats a bounded number of times when the visible cohort changed while it was locked. -- The indicator. `salary_fit` is always `not_available` and `contact_access` is `not_granted` with no fields. The indicator needs the candidate's minimum, and computing it before the limit of three settings a day and the seven-day withholding exist would let an organization probe the minimum by editing a draft, so neither is computed or enforced yet. +- The indicator. `salary_fit` is always `not_available`; `contact_access` is derived from the grant ([Contact reads and revocation](#contact-reads-and-revocation)). The indicator needs the candidate's minimum, and computing it before the limit of three settings a day and the seven-day withholding exist would let an organization probe the minimum by editing a draft, so neither is computed or enforced yet. How the later operations plug in: the pair rules read the index on the organization and the candidate. The contact grant arrives with the acceptance ([Candidate acceptance](#candidate-acceptance)). The C4 columns of the consent ledger still have no foreign keys to `organizations` and `invitations`; that is a follow-up. -Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the limit of pending invitations per need, the raise, the withdrawal, the candidate side beyond the list of invitations, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned. +Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the raise, the withdrawal, the candidate side beyond the list of invitations, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned. Tests: `domain/salary_range_test.go` and `domain/invitation_test.go` (exact width at 10% and 40%, steps, caps, terms rules with pointers, versions, immutability of earlier values, redaction), `usecase/invitation/service_test.go` (owner policy, handle refusals, order of checks, replay, rollback, versions), `adapter/primary/http/v1/invitation_test.go` (mapping, no candidate field, failure statuses, cursor), and the integration tests `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations`, and `TestInvitationMigrationRollbackKeepsStoredInvitations` against a real PostgreSQL. @@ -984,7 +984,7 @@ Implemented: `SendOrganizationInvitation` and the candidate's list of invitation - Access. Owner only, as for drafts: `ownerCompanyOperations` at the HTTP boundary and the same check in the transaction; no other role may send. The candidate's list requires a verified candidate account, and an employer gets 403. - Order of checks after the boundary: the owner, the key (422 or a replay), the invitation (404), a completed send (200), the version (412), the state and the visibility (409), then the quota (429). -Not implemented: the pending limit per need and the pause after a decline or a no deal (both planned in the contract), the acceptance and the cancellation (the read, the view, and the decline are in [Candidate view and decline](#candidate-view-and-decline)), the expiry at the deadline, the sending of notification email, the shared E0 pool of a holding in the quota port, and the role and assignment matrix beyond the owner. +Not implemented: the pause after a no deal (no operation produces the `no_deal` state yet), the cancellation (the view, the decline, and the acceptance are in [Candidate view and decline](#candidate-view-and-decline) and [Candidate acceptance](#candidate-acceptance)), the sending of notification email, the shared E0 pool of a holding in the quota port, and the role and assignment matrix beyond the owner. The pending limit and the pause after a decline are in [Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry). Tests: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`, `usecase/notification/inbox_test.go` (the invitation notice), `adapter/primary/http/v1/invitation_test.go` (statuses, `Retry-After`, the candidate cursor), and the integration tests `TestOrganizationInvitationSendOverHTTP` (the inbox before any email, repeats with one row of each kind and one charge, a 3-day deadline with the mail stopped and its job retried, visibility, a stale version, owner only, the quota, paging) and `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage`. @@ -992,20 +992,20 @@ Tests: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`, Implemented: `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). Code: `domain/invitation_answer.go`, `usecase/invitation/view.go` and `decline.go`, the HTTP handler `adapter/primary/http/v1/invitation_candidate.go`, the adapter `adapter/secondary/postgres/invitation_answer.go` with `db/queries/invitation_answers.sql`, and migration `00039_answer_invitations.sql`. -- Read without a side effect. `GetMyInvitation` reads a delivered invitation by the candidate of the session and the invitation, with the current terms and the current name of the sending organization; it records nothing. The view is the explicit command `ViewMyInvitation`, as the contract requires, so a prefetch, a retry, or a cache refresh never changes what the organization sees. A draft, an invitation of another candidate, and an unknown identifier answer the same 404; an employer account answers 403. -- View. In `delivered` before the deadline the command moves the invitation to `viewed` with one conditional UPDATE (`state`, `version` plus one, `viewed_at`, `updated_at`), keeps `response_deadline_at`, and appends the audit event `viewed`. In every other state, and at the deadline or later, it changes nothing and answers 200 with the invitation as it is. It takes neither a key nor a version; concurrent views queue on the row lock, and the first one wins. +- Read without a side effect. `GetMyInvitation` reads a delivered invitation by the candidate of the session and the invitation, with the current terms and the current name of the sending organization, and it records no view. The one change a read can cause is the expiry: a read at the deadline or later first moves the invitation to `expired` ([Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry)). The view is the explicit command `ViewMyInvitation`, as the contract requires, so a prefetch, a retry, or a cache refresh never changes what the organization sees. A draft, an invitation of another candidate, and an unknown identifier answer the same 404; an employer account answers 403. +- View. In `delivered` before the deadline the command moves the invitation to `viewed` with one conditional UPDATE (`state`, `version` plus one, `viewed_at`, `updated_at`), keeps `response_deadline_at`, and appends the audit event `viewed`. At the deadline or later the due expiry is applied first, and the 200 answer shows `expired` with no view recorded; in every other state the command changes nothing and answers 200 with the invitation as it is. It takes neither a key nor a version; concurrent views queue on the row lock, and the first one wins. - Decline. Allowed from `delivered`, `viewed`, and the planned `counter` before the deadline. One transaction moves the invitation to the terminal `declined` (`responded_at`, `version` plus one), stores the reason and the optional comment in `invitation_declines`, appends the audit event `declined`, and keeps the outcome under the key. It writes no consent, no contact grant, and no outbox event. The comment follows the schema rule with the Unicode notion of white space and refuses control characters other than a line break or a tab, because PostgreSQL text cannot hold NUL (400 at `/comment`). - Responsiveness. The `declined` event (`kind`, `version`, the candidate as `actor_id`, `occurred_at`) is the candidate's answer that the planned responsiveness metrics of the organization count. It is always in time, since a late decline is refused, and it is never a consent or a hire. It holds neither the reason nor the comment. - Privacy of the decline. The organization reads only `declined` and `responded_at`: none of its operations reads `invitation_declines`, and the audit event names no reason. The comment is never logged, notified, or copied into the stored outcome; the candidate reads both back in `decline`. - Order of checks after the boundary: the candidate (403), the key (422 or a replay), the invitation (404, stored), the same decline of a declined invitation (200 with a new key or an older version), another reason or comment on a declined invitation, any other terminal state, or a passed deadline (409 whatever the version, stored), the version (412, not stored), then a state without an open answer (409, stored). `invitation_decline_results` keeps only the outcome and the invitation: a declined invitation and its decline never change, so a replay rebuilds the same answer and the comment is stored once. -- Deadline. Expiry is not implemented yet, so no read or command applies the transition to `expired`. A view at the deadline or later changes nothing, and a decline at the deadline or later answers 409 `state_conflict`, as the contract requires for a late command; the invitation stays `delivered` or `viewed` with its passed deadline until the expiry arrives. The conditional UPDATEs repeat the deadline, so a command cannot cross it between the check and the write. +- Deadline. A command at the deadline or later first applies the due expiry: the invitation moves to `expired` with the reason `invitation_timeout`, and only then are the state and the version checked. A decline at the deadline or later answers 409 `state_conflict`, as the contract requires for a late command. The conditional UPDATEs repeat the deadline, so a command cannot cross it between the check and the write. The lock order and the expiry rules are in [Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry). - Consent and grant. A decline creates neither a consent nor a grant, so `contact_consent` and `contact_grant` are null after it. The acceptance is described in [Candidate acceptance](#candidate-acceptance). - Hiding. The candidate's read shows the sending organization even after the candidate hid the profile from it: the hiding keeps the organization from seeing the candidate, while the candidate must know who sent the offer to answer it. The pushed content follows the hiding instead: the inbox notice of the invitation loses its content (`ResolveInvitationNotice`). -- Locks. A candidate command locks only the invitation row (`LockCandidateInvitation`) after the candidate's own idempotency record, never the organization. An organization command takes the organization lock first and the invitation row afterwards, so the two orders never cross: a candidate command does not wait for an organization lock while it holds the row. +- Locks. A candidate command locks the invitation row (`LockCandidateInvitation`) after the candidate's own idempotency record. A decline also takes the organization lock before the row, because it changes the pause of the pair; it never takes that lock after the row. An organization command takes the organization lock first and the invitation row afterwards, so the orders never cross. A view and an acceptance do not lock the organization. - Database rules of migration 00039: the event kinds `viewed` and `declined` without changed fields; `invitations_answer_matches_state` (a delivered invitation has no view or answer, a viewed one has its view, a declined one its answer, and neither precedes the delivery); the trigger `invitations_guard_answer`, which refuses to move or undo a view or an answer and to leave `declined`; `invitation_declines` with the known reasons, the comment bound, a trigger that ties the row to a declined invitation answered at the same moment, and a refusal of UPDATE and DELETE; and the deferred constraint trigger `invitations_require_decline`, so a declined invitation without its decline cannot commit. The down migration refuses while a view, a decline, or a stored outcome exists. - Notification. The contract has no notification kind for an answer, so the organization gets no inbox entry for a view or a decline yet; it sees the state in its invitation list. A notice of the answer is planned as a contract change. -Not implemented: the expiry at the deadline and its application on a read, the cancellation, the counter offer that would produce `counter`, the decline aggregates with a minimum group size, the responsiveness metrics, the 30-day pause after a decline, and a notification of the organization about an answer. +Not implemented: the cancellation, the counter offer that would produce `counter`, the decline aggregates with a minimum group size, the responsiveness metrics, and a notification of the organization about an answer. Tests: `domain/invitation_answer_test.go` (the view only from `delivered` before the deadline, the decline from `delivered`, `viewed`, and `counter`, the refusal of terminal and late invitations, the comment rules, the stored answer rules, redaction), `usecase/invitation/answer_test.go` (no side effect of a read, the deadline kept, repeats, order of checks, foreign callers, invalid comments), `adapter/primary/http/v1/invitation_candidate_test.go` (statuses and a response without candidate data), and the integration tests `TestCandidateInvitationViewAndDeclineOverHTTP` (the read and the view with the same deadline, concurrent views with one event, a decline with `other` and no comment without a C4 consent, the stored answer event, replays and conflicts, the comment kept from the organization and the audit, foreign candidates and employers, CSRF and Origin, the hiding, a stale version, a late command) and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback`. @@ -1018,15 +1018,55 @@ Implemented: `AcceptMyInvitation` ([contract](../../api/README.en.md#invitations - Repeats. An accepted invitation whose grant has the same terms version and the same set of fields answers 200 with the same invitation, under the same key or a new one and with an older `expected_version`, and records nothing. Another terms version or set of fields answers 409 `state_conflict`, stored under the key. The outcomes under a key are `accepted`, `not_found`, and `state_conflict`; a stale version and a consent refusal are not stored. - The grant. `contact_grants` holds the organization, the candidate, the source invitation (one grant per invitation), the consent record (one per grant), the canonical field set, the terms version, the consent text version, the grant time, and the revocation stamp (`revoked_at` and `revocation_reason`). This change never sets the stamp; the revocation is a later operation. Composite foreign keys tie the grant to its invitation of the same organization and candidate, and to its C4 record of the same subject, organization, invitation, and terms version. A trigger checks that the fields, the text version, and the grant time equal those of the record; a second trigger refuses DELETE and every change other than the one stamp. A deferred constraint trigger refuses to commit an accepted invitation without its grant. The grant holds kinds only, never contact values. - The candidate's view. While an acceptance is possible, `contact_consent` holds the rendered C4 text and the kinds that the profile holds, in the order of the contract, with nothing preselected; it is null when the profile holds no confirmed kind. After the acceptance, `contact_grant` holds the selected kinds, the status, the terms version, the consent text version, and `readable`. `readable` is true only while the organization may read the profile: the publication is effective and the candidate has not hidden the organization. Otherwise `blocked_by` is `visibility`. A declined invitation keeps both fields null. -- Visibility decision. The acceptance is allowed while the profile is hidden from the organization or not published, as the contract's example of a blocked grant shows. It never publishes the profile, never changes the publication, and never lifts or adds a hiding. The grant stays stored and becomes readable when the candidate publishes the profile or unhides the organization; `readable` is recomputed on every read, so the grant itself never changes. The contact read through the grant is a later operation, so the organization still sees `contact_access` as not granted. +- Visibility decision. The acceptance is allowed while the profile is hidden from the organization or not published, as the contract's example of a blocked grant shows. It never publishes the profile, never changes the publication, and never lifts or adds a hiding. The grant stays stored and becomes readable when the candidate publishes the profile or unhides the organization; `readable` is recomputed on every read, so the grant itself never changes. The organization sees `contact_access` as `closed` while the grant is blocked, and as `available` once it becomes readable (see [Contact reads and revocation](#contact-reads-and-revocation)). - Concurrency. The candidate command never takes the organization lock. Two concurrent acceptances of one version make one transition: the second waits for the row and then answers as a repeat, which is 200 with the same answer for identical terms and fields and 409 for another field set. - Clocks. The answer time comes from the invitation service and the grant time from the consent service. In production both read the process clock, so they can differ by microseconds; the grant keeps the consent time. A replay of a stored acceptance rebuilds the response from the invitation and the grant. The outcome table keeps no copy of the response, so a later state change would show in a replay, as it would for a decline. - Ledger keys. The C4 columns of the consent ledger still have no foreign keys to `organizations` and `invitations`: the ledger tests write C4 records with synthetic identifiers. The composite keys of the grant keep an acceptance consistent without that change; the ledger keys need fixtures with real invitations and are a follow-up. -Not implemented: the contact read through a grant, the revocation of a grant (after the publication is closed, after the hiding, after the consent is revoked, or after the participation is cancelled), the counter offer, the expiry at the deadline, and the cancellation. +Not implemented: the counter offer and the cancellation, including the revocation of a grant after the participation is cancelled (the other revocations are in [Contact reads and revocation](#contact-reads-and-revocation)). Tests: `domain/contact_grant_test.go` (the grant from its record, the scope and revocation rules, the visibility view, the offer rendering, and `Accept`), `usecase/invitation/accept_test.go` (the order of checks, repeats, stale terms, late commands, consent pointers, visibility without a change of the publication), `adapter/primary/http/v1/invitation_candidate_test.go` (failure statuses), and the integration tests `TestCandidateInvitationAcceptOverHTTP` (an email-only grant, repeats and conflicts, a stale terms version and the raised terms, concurrent acceptances, a hidden profile, a late acceptance, consent and kind checks, the server log) and `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` against a real PostgreSQL. +### Pending limit, cooldown, and expiry + +Implemented: the limit of invitations that wait for an answer per need, the pause of the organization and candidate pair after a decline, and the expiry of an invitation at its response deadline. Code: `usecase/invitation/pending_limit.go` (the send checks), `usecase/invitation/expire.go` (the handler of the job `invitation.response_deadline`, the shared expiry function, and the scheduling at delivery), `domain/invitation_expiry.go` (`Expire` and `ExpiryEvent`), `usecase/invitation/send.go`, `decline.go`, `accept.go`, and `view.go` (the expiry before a candidate answer), the adapter `adapter/secondary/postgres/invitation_expiry.go` with `db/queries/invitation_pending.sql`, `invitation_cooldowns.sql`, and `invitation_expiry.sql`, the registration in `jobHandlers()` (`bootstrap/jobs.go`), and migration `00043_expire_invitations.sql`. + +- Limit. A send counts the invitations of the need that wait for an answer (`delivered`, `viewed`, `counter`) and answers 409 `state_conflict` when there are already `max_pending_per_need` of them in the effective policy (20 in the demo policy). The count is exact: the send takes the organization lock before anything else, and only a send can move an invitation into the waiting states. An invitation without a need has no need limit; the quota bounds it. Leaving the waiting states (a decline, an expiry, an acceptance) frees the place but never returns the weekly quota: the quota is charged at the send and does not change. +- Pause. A send answers 409 `state_conflict` until `repeat_after_decline_days` (30 days) have passed since the latest decline of the candidate by this organization. The pause belongs to the pair of the organization and the candidate, not to a need and not to a member: another need or another owner of the same organization gets the same refusal. The pause after a no deal does not apply yet: no operation produces the `no_deal` state. +- Lock order. A candidate's decline takes the organization lock before the invitation row, like every command that can change the pause of a pair. The decline and a send of the same pair are therefore ordered: a send never misses a decline that committed before its check. The order is the same as in [sending](#sending-invitations): the organization, then the invitation rows. +- Deadline. A send schedules the job `invitation.response_deadline` in the same transaction as the delivery: the key is the invitation identifier, the due time is `response_deadline_at`, and the payload holds only the identifier. The handler `ResponseDeadlineJob` runs in a transaction that locks the invitation row. If the invitation still waits for an answer, it moves to `expired` with the reason `invitation_timeout`; otherwise the handler changes nothing. A repeat of the job is safe: a second run finds no invitation that waits for an answer. +- Candidate commands at or after the deadline. The view, the decline, and the acceptance lock the row and read the time while they hold the lock; the read (`GetMyInvitation`) locks the row only when the deadline has passed. In both cases, when the deadline has passed, the expiry is applied first with the same conditional UPDATE and the same audit event. The read and the view then answer with the invitation in the state `expired`, with no view recorded; the decline and the acceptance answer 409 `state_conflict` and keep the outcome under the key. The list of the candidate's inbox and the organization's reads do not apply the expiry: they show the stored state until the job or the next candidate command applies it. +- What the expiry writes. The transition writes only the audit event `expired` with its version, no field, and no actor (`actor_id` is empty, because the server made the change). No consent C4, contact grant, decline record, or quota change is created or changed. The deadline and the terms are kept. The constraint `invitation_events_system_actor` allows an empty actor only for `expired`, the trigger `invitations_guard_expiry` allows the transition only from `delivered` or `viewed` and not before the deadline, and `invitations_expiry_reason` requires the reason. +- Race with the acceptance. An acceptance at or after the deadline always refuses: the acceptance and the job both decide by a time that is known while the row is held. Whichever path takes the row first, the outcome is one: an `expired` invitation with no grant. An acceptance before the deadline that commits before the job leaves the job without effect. The tests `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres` (the race) and `TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres` (the job first) check it. +- Clock. The deadline and the limits are decided by the application clock, injected into the usecases and into the job handler; the database clock decides nothing. A handler whose clock has not reached the deadline returns an error, so the job is retried with backoff instead of completing without the expiry. +- Running. The worker that runs the job is the one enabled by `JOBS_ENABLED`; without it the job waits in the database. The candidate commands apply the expiry without the worker, so the candidate's answer stays correct. +- Migration 00043. The new event kind `expired`; the constraints `invitation_events_expiry_changes_no_field` and `invitation_events_system_actor`; the trigger `invitations_guard_expiry`; the partial indexes `invitations_pending_need_idx` (the waiting invitations of a need) and `invitations_declined_pair_idx` (the declines of a pair); and the backfill of the expiry jobs for invitations delivered before the migration, keyed by the identifier with `ON CONFLICT DO NOTHING`. The rollback refuses while expired invitations exist and removes the jobs of this kind. + +Not implemented: the pause after a no deal (it needs an operation that moves an invitation to `no_deal` and sets the end of the pause), the expiry of the `counter` state (no operation produces it yet), the reason `negotiation_timeout`, and a limit for invitations without a need, should one be introduced. + +Tests: `domain/invitation_expiry_test.go` (the expiry of a waiting invitation only after its deadline, the kept deadline and terms, and the event without an actor); `usecase/invitation/pending_limit_test.go` (the limit at 20 waiting and the 21st, two concurrent sends at 19, the freed place without a quota return, the pause at day 29 and day 30 for another owner and another need, and no pause for another candidate or an expired invitation); `usecase/invitation/expire_test.go` (the expiry by a read, a view, an acceptance, and a decline at the deadline, the job and its repeat, and the job refusal of a payload that names no invitation); the integration tests `TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres`, `TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres`, `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres`, `TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres`, and `TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries` in `integration_test/invitation_expiry_test.go`. + +### Contact reads and revocation + +Implemented: `GetOrganizationInvitationContacts` ([contract](../../api/README.en.md#invitations-and-contact-grants)) in `usecase/invitation/contacts.go` and `adapter/primary/http/v1/contacts.go`; the disclosure type in `domain/contact_disclosure.go`; the grant lock `ContactGrantRepository.LockForRead` in `adapter/secondary/postgres/invitation_accept.go`; the closings in `consent_revocation.go` (`ConsentRevocationEffects.Apply`), `privacy_view.go` (`CloseForVisibility`), and `contact_grant_closure.go`; the queries in `db/queries/contact_grants.sql`; and migration `00042_index_contact_grants_by_candidate.sql`, which adds the candidate-wide index that the candidate-wide closings use. The organization's `contact_access` is derived in `usecase/invitation/contact_access.go`, through the same `readableContactGrant` check that the read uses (`usecase/invitation/contacts.go`). + +- Access. The company middleware checks the session, the active owner membership, and the path before the handler. A non-owner member answers 403, an account without a membership answers 404, and a candidate account answers 403. The usecase repeats the owner check inside its transaction. In the MVP no other role reads contacts. +- Lock order. The read takes, in this order: the organization and the membership (`LockActiveMembership`, share locks), the candidate account, the newest active C2 record, the publication with its C2 record (which also applies the organization's hiding), the C4 record of the grant, and the grant itself. The unlocked grant read before the locks only names the candidate, which a grant never changes. A C4 revocation locks the record and then the grant in the same order, so the two cannot wait for each other in opposite orders. The visibility locks come first, so a hiding or a C2 revocation that commits first is seen, and one that waits runs after the read commits. +- Decision. The read answers 200 only when the grant is active, its C4 record is unrevoked, and the organization may read the publication now. Every other case answers 404 `not_found` and does not say which one applies: no grant of this invitation for this organization, a revoked grant or C4 record, or a profile that is closed or hidden from the organization. A kind returns its value only when the profile holds it as a confirmed claim; any other kind is null, and a suggestion that nobody confirmed is never disclosed. The response has `Cache-Control: no-store`. +- Closings. Each closing runs in the transaction of the change, stamps the revocation time and its reason, and never reopens a grant: + - Revoking C4 for an organization (`consent_revoked`) closes the grants that name the revoked records. The grants of other organizations and of other invitations stay open. + - Revoking C2 (`visibility_closed`) closes every active grant of the candidate, including when the candidate has no publication row to close. + - Closing the publication (`visibility_closed`) closes every active grant of the candidate. + - Hiding an organization (`visibility_closed`) closes the active grants of that organization, including on a repeated hide. Unhiding and publishing again close nothing and reopen nothing: a closed grant keeps its first stamp, which the guard trigger allows once. + - A grant stored while the profile is not readable is not closed by that state. It stays active and blocked by visibility, becomes readable when the candidate publishes or unhides, and the next closing event closes it. + - Withdrawing an invitation by the organization changes no grant. Cancellation of the participation by the candidate (`participation_cancelled`) is not implemented. A C1 revocation closes no grant, because the contract names no reason for it. +- Organization view. Each organization response that carries `contact_access` derives it from the grant of the invitation, in the transaction of the request: `GetOrganizationInvitation`, `ListOrganizationInvitations`, and the responses of the draft create, update, and send. No grant answers `not_granted`, and a revoked grant answers `closed`. An active grant runs the read's visibility locks and checks, then its C4 record and the grant, so the view says `available` exactly when a read would succeed at that moment, and `closed` otherwise. The view lists the granted kinds only while it is `available`; `closed` carries no reason, and no contact value is ever part of the view. The derivation reads the grant of every state, so a withdrawn invitation keeps the state of its grant, as the contract requires. A declined or expired invitation has no grant and answers `not_granted`. The idempotent replays of a create and of a send return the stored original response, so their `contact_access` is the state at the first answer. The derivation costs one grant lookup per invitation, and it takes the share locks only for an invitation with a grant. +- Quota and audit. A successful read writes one `contact_read` row to `candidate_card_access_events` in the same transaction, with the granted kinds and never a value. It does not consume the card-view quota, because the contract does not count contact reads against it. The candidate's own history read stays a contract-only operation. +- Not implemented: the candidate's cancellation, and the organization's withdrawal. `CurrentContactFields` in `usecase/candidateview` stays closed, because the card-handle read has no contract operation. + +Tests: `domain/contact_disclosure_test.go` (confirmed values only, refused revoked grants, redacted formatting), `usecase/invitation/contacts_test.go` (owner and role checks, visibility, revoked grant and C4 record, unknown invitations), `usecase/invitation/contact_access_test.go` (the organization's states, their agreement with the read in each closing state, a blocked grant that opens once it is visible, and a revoked grant that never reopens), and the integration test `TestOrganizationContactReadsAndRevocationOverHTTP` over the real router and PostgreSQL. It covers the email-only read, the repeated read, the refusals of another organization, a recruiter, and a candidate, C4 revocation with an independent organization, hiding and unhiding without reopening, C2 revocation with republication, closing the publication, and the index. It also checks `contact_access` of the single read and of the list after each change, a declined invitation, and an expired one, which runs last because it moves the clock. + + ## 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/COMPANY_QUOTAS.md b/docs/en/COMPANY_QUOTAS.md index a330bf8..4565424 100644 --- a/docs/en/COMPANY_QUOTAS.md +++ b/docs/en/COMPANY_QUOTAS.md @@ -1,6 +1,6 @@ # Company quotas -Company quota reservations are implemented in the domain, `companyquota` usecase, and PostgreSQL adapter. They provide a transaction-bound storage port for invitation and candidate-card usage. The product invitation and delivery workflow is still pending; these reservations do not mean that an invitation has been sent. +Company quota reservations are implemented in the domain, `companyquota` usecase, and PostgreSQL adapter. They provide a transaction-bound storage port for invitation and candidate-card usage. An invitation spends one place of the weekly quota when it is sent (`SendOrganizationInvitation`): a draft spends nothing, and a repeat of the send of the same invitation does not spend a second place. An invitation that leaves the waiting state (a decline, an expiry, an acceptance) frees its place in the per-need pending limit, but never returns the weekly quota; see [Pending limit, cooldown, and expiry](ARCHITECTURE.md#pending-limit-cooldown-and-expiry). ## Policy and trusted organization level diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 7749868..de8cd35 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -174,7 +174,7 @@ Offsets и партиции. Каждый обработчик - один уча ### Задания по сроку -Реализовано: устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. В `jobHandlers()` (`backend/internal/bootstrap/jobs.go`) зарегистрирован один продуктовый обработчик: `assessment.signal_review`, который считает [полосу проверки оценки](#серверные-сигналы-оценки-и-полоса-проверки). Тесты используют и вид задания, который есть только в тестах. Первый запланированный вид по сроку - срок ответа на приглашение. Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку). +Реализовано: устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. В `jobHandlers()` (`backend/internal/bootstrap/jobs.go`) зарегистрированы два продуктовых обработчика: `assessment.signal_review`, который считает [полосу проверки оценки](#серверные-сигналы-оценки-и-полоса-проверки), и `invitation.response_deadline`, который переводит приглашение в `expired` при истечении срока ответа ([Предел ожидающих, пауза и истечение](#предел-ожидающих-пауза-и-истечение)). Тесты используют и вид задания, который есть только в тестах. Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку). Планирование. Usecase вызывает `unit.ScheduledJobs().Schedule(ctx, job)` в своей бизнес-транзакции, поэтому задание существует ровно тогда, когда зафиксировано изменение, которому оно нужно; `Cancel(ctx, kind, key)` останавливает незавершенное задание. У задания есть вид (имя обработчика, строчное имя с точками), ключ логического задания внутри вида (например, ID агрегата), срок по часам приложения, необязательный лимит попыток и payload: плоский JSON-объект из идентификаторов не больше 2 КиБ. Ни ключ, ни payload не должны содержать персональные данные; остальное обработчик читает из исходных таблиц в момент выполнения. Пара `(kind, key)` уникальна, и побеждает первое планирование: повтор ничего не вставляет (`INSERT ... ON CONFLICT DO NOTHING`) и возвращает `false`, в том числе после выполнения или отмены задания. Это намеренно insert-or-ignore, а не upsert: повторная команда не может сдвинуть срок, который нельзя сбрасывать, а устаревший писатель не может оживить завершенное задание. Для нового повторения нужен новый ключ, например `:`. @@ -184,7 +184,7 @@ Offsets и партиции. Каждый обработчик - один уча Выполнение и завершение. Каждое задание выполняется в собственной транзакции READ COMMITTED: она ставит `statement_timeout` и `idle_in_transaction_session_timeout` равными длительности lease, блокирует строку задания с проверкой `status = running`, владельца lease и номера попытки, вызывает обработчик с `outbound.UnitOfWork` той же транзакции, отмечает задание `done` с той же проверкой и фиксирует транзакцию. Эффект обработчика и завершение фиксируются вместе: для эффекта, который остается в PostgreSQL, задание применяется ровно один раз, даже когда workers конкурируют, перезапускаются или lease истекает. Пока обработчик работает, строка заблокирована, поэтому захват другого worker пропускает ее даже после истечения lease по часам; если проверка не прошла, потому что задание отменили или захватили заново, обработчик не вызывается и ничего не фиксируется (`lease_lost`). Обработчик может отменить собственное задание через unit, например истечение, которое заодно отменяет задание срока, которое оно представляет: тогда завершение находит задание `cancelled` в своей же транзакции, считает его выполненным и фиксирует эффект, а задание остается `cancelled`. Любое другое изменение собственного задания обработчиком откатывается и переводит задание в `dead` с классом `completion_conflict`, потому что оно повторялось бы на каждой попытке. Обработчик, эффект которого выходит за пределы базы данных, например вызов другого сервиса, может повториться после сбоя между этим вызовом и фиксацией и должен быть идемпотентным сам. Context обработчика заканчивается вместе с продленным lease. Обработчик принимает решение по `job.DueAt`, то есть по сроку, который задание представляет и который повтор сохраняет, а не по моменту, когда оно случайно выполнилось. -Порядок блокировок. Обработчик держит блокировку строки задания и затем может блокировать продуктовые строки. Бизнес-транзакция, которая отменяет задание, например принятие приглашения в момент срока, должна вызывать `Cancel` до блокировки этих продуктовых строк. `Cancel` ждет транзакцию обработчика, если она идет: после ее фиксации задание уже `done`, и `Cancel` возвращает `false`, поэтому вызывающий видит истечение; иначе задание отменяется, а worker обнаруживает, что его lease больше не действует. Обратный порядок может привести к deadlock, который PostgreSQL разрешает, прерывая одну сторону с `ErrTransactionConflict`; сторона задания засчитывает неудачную попытку и повторяет ее. +Порядок блокировок. Обработчик держит блокировку строки задания и затем может блокировать продуктовые строки. Бизнес-транзакция, которая отменяет задание, должна вызывать `Cancel` до блокировки этих продуктовых строк. Ответ кандидата задание срока ответа не отменяет: выполнение находит ответивший приглашение и ничего не меняет ([Предел ожидающих, пауза и истечение](#предел-ожидающих-пауза-и-истечение)). `Cancel` ждет транзакцию обработчика, если она идет: после ее фиксации задание уже `done`, и `Cancel` возвращает `false`, поэтому вызывающий видит результат выполнения; иначе задание отменяется, а worker обнаруживает, что его lease больше не действует. Обратный порядок может привести к deadlock, который PostgreSQL разрешает, прерывая одну сторону с `ErrTransactionConflict`; сторона задания засчитывает неудачную попытку и повторяет ее. Сбои. Неудачная попытка откатывает свой эффект; второй оператор с той же проверкой записывает ее. Ошибка обработчика, истечение lease, deadlock или serialization failure (`conflict`) и фиксация, которую отверг PostgreSQL (`effect_rejected`, для обработчика, который проигнорировал упавший оператор, или для отложенного ограничения), переводят задание в `failed` с `available_at = now + backoff`, где backoff - общая задержка `worker/retry`: от `JOBS_BACKOFF_INITIAL`, удваивается до `JOBS_BACKOFF_MAX`, со случайным разбросом. `inbound.ErrJobRejected`, panic обработчика и `completion_conflict` финальны, в том числе во время остановки. После последней разрешенной попытки (собственный лимит задания или `JOBS_MAX_ATTEMPTS`) задание становится `dead`: это пишется в журнал на уровне error и считается как `dead`, такому заданию нужен оператор. `last_error_class` хранит только ограниченный класс; очищенная причина есть только в журнале. Сбой базы данных вне обработчика - не вина задания: worker освобождает незавершенные задания без учета попытки и ждет backoff перед следующим захватом, поэтому сбой не создает горячего цикла. Если не удалось записать сам сбой, задание сохраняет начатый lease; следующий захват учтет его как `lease_expired`, а на последней попытке это делает задание dead. @@ -798,7 +798,7 @@ contact_grant относится к паре кандидат-компания - `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` выдает журнал субъекта страницами от новых к старым, при необходимости по состоянию. -- `ConsentRevocationEffects.Apply` выполняется в той же транзакции `UnitOfWork`, что и отзыв в журнале. Он закрывает эффективный доступ C2 только когда текущая публикация ссылается на одну из отозванных записей, один раз добавляет событие истории приватности и записывает ограниченные по размеру outbox-intents на основе точных отозванных записей. Будущий адаптер выдачи для C2/C4 должен привязывать grant к ID исходной записи согласия и синхронно закрывать старый grant в этой транзакции; новая выдача может создать только новый grant, но не открыть старый. Читатели и импортеры C5 должны проверять актуальный журнал и отказывать по умолчанию; outbox-сообщение само по себе не дает доступ и не доказывает удаление данных во внешней системе. +- `ConsentRevocationEffects.Apply` выполняется в той же транзакции `UnitOfWork`, что и отзыв в журнале. Он закрывает эффективный доступ C2 только когда текущая публикация ссылается на одну из отозванных записей, один раз добавляет событие истории приватности и записывает ограниченные по размеру outbox-intents на основе точных отозванных записей. Разрешения, которые дали отозванные записи, закрываются в этой транзакции (C4 по записи, C2 для всех разрешений кандидата; см. [Чтение контактов и отзыв](#чтение-контактов-и-отзыв)); новая выдача может создать только новый grant, но не открыть старый. Читатели и импортеры C5 должны проверять актуальный журнал и отказывать по умолчанию; outbox-сообщение само по себе не дает доступ и не доказывает удаление данных во внешней системе. ### Usecase согласий @@ -922,7 +922,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - Истечение `looking` берется из версионированной политики и только сужает видимость. 30 дней - это `search_status.searching_confirmation_interval_days` действующей версии политики `product` (демо-версия 1: 30), поэтому владелец меняет срок публикацией новой версии политики, а не константой или конфигурацией. Подтверждение фиксирует `lapses_at` и сохраняет `policy_version_id`, поэтому последующее изменение политики не сдвигает сохраненные времена, а каждая строка называет политику, по которой создана, как требует раздел политик. Само истечение вычисляется (`SearchStatus.Effective(now)` дает `looking`, только пока `now` раньше `lapses_at`) и нигде не записывается: ни процесс, ни задача, ни расхождение часов не превратит истекший статус во что-то более публичное, сохраненная строка хранит слова кандидата, а ответ показывает `value` `not_looking` и `lapsed` true. Кандидат подтверждает снова значением `looking`, которое заменяет `confirmed_at`. Напоминание до истечения - запланированное уведомление, не часть этой задачи. - Версии. У каждой настройки своя `version` (0 - отсутствие строки), она проверяется в самом операторе, как у профиля: `UpdateCandidatePublication` и `UpdateCandidateSearchStatus` меняют строку только если сохраненная версия равна прочитанной вызывающим, а для устаревшей строка не возвращается (412 `version_conflict`). Порядок в домене совпадает с контрактом: версия выше текущей - конфликт, неизмененная действующая настройка - успех даже при устаревшей версии, любое другое изменение по устаревшей версии - конфликт, а публикации нужна действующая C2. Поскольку настройки независимы, изменение одной никогда не делает устаревшей другую. - Скрытые организации принадлежат кандидату и защищены от перебора. Запись принадлежит кандидату: ни один запрос стороны организации ее не выбирает, а организация не отличает скрывшего кандидата от неопубликованного. Скрытие по идентификатору не должно стать способом спросить, существует ли организация. Внешний ключ отклоняет неизвестную организацию (SQLSTATE 23503), а юзкейс обязан ответить на это так же, как на организацию, которую кандидат не видит: тот же 404 `not_found` с тем же телом, без другого времени ответа или кода. Кандидат видит организацию, приславшую ему приглашение, и организации, которые покажет поиск организаций для кандидата (запланирован, открытый вопрос), поэтому скрытие не раскрывает того, что кандидат не мог прочитать раньше. Снятие скрытия - DELETE, который отвечает 204 на любой корректный идентификатор и потому ничего не раскрывает; событие истории пишется, только если строка была удалена. Идентификаторы - случайные UUIDv7, а оставшийся перебор покрывает общий лимит запросов. -- Контактные разрешения. Закрытие публикации и скрытие организации, у которой есть активное контактное разрешение, отзывают его с причиной `visibility_closed` в той же транзакции, что и изменение (причину задает контракт приглашений). Это относится к юзкейсам, которых еще нет; эта задача хранит настройки и задает контракт. Статус поиска разрешение никогда не закрывает. +- Контактные разрешения. Закрытие публикации и скрытие организации, у которой есть активное контактное разрешение, отзывают его с причиной `visibility_closed` в той же транзакции, что и изменение (причину задает контракт приглашений). Закрытие реализовано, см. [Чтение контактов и отзыв](#чтение-контактов-и-отзыв). Статус поиска разрешение никогда не закрывает. - История вместо области полей. Запись C2 доказывает согласие с текстом публикации, а `candidate_privacy_events` хранит то, о чем просила заметка журнала согласий: набор опубликованных полей и его изменения с временами и записью C2 за каждым. Отзыв C2 и истечение статуса вычисляются и не являются событиями. Нужна ли C2 собственная область полей как согласию по статье 10.1 152-ФЗ - по-прежнему юридический вопрос (см. журнал согласий). - Приватность. Таблицы хранят идентификаторы, коды полей карточки и времена; значений профиля, имен, контактов и файлов нет (тест перечисляет столбцы). `Publication`, `SearchStatus`, `HiddenOrganization` и `PrivacyEvent` пишут в журналы только идентификаторы, версии и виды. Ни один запрос не выбирает строку чужого аккаунта: каждый оператор ограничен `user_id`. Адаптер должен сообщать только SQLSTATE и имя ограничения, как остальные. @@ -962,11 +962,11 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - Изменение. Тело заменяет заданные поля, а `terms` всегда заменяются целиком. Порядок как в контракте: тело, которое ничего не меняет, возвращает текущее приглашение с 200 даже при устаревшей версии, затем версия (412 `version_conflict`), затем состояние (409 `state_conflict`, меняется только черновик), затем правила (400 с pointer). Изменение условий добавляет следующую версию условий, изменение срока или потребности ее сохраняет. Новый срок проверяется по действующей политике и записывает ее версию. - Срок ответа. Варианты и значение по умолчанию берутся из раздела `invitations` действующей продуктовой политики (3, 7, 14; по умолчанию 7), а черновик хранит версию, которой воспользовался. - Блокировки. Создание и изменение сначала берут исключительную блокировку организации (`CompanyQuotaRepository.LockOrganization`), как чтение карточки и поиск, и только потом разделяемую блокировку проверки членства, блокировки когорты при создании или блокировку строки приглашения при изменении. Поэтому команды одной организации встают в очередь, а не блокируют друг друга при повышении блокировки, и следующая команда, которая тоже списывает ресурсы организации, например отправка, сохраняет тот же порядок. Изменение блокирует строку приглашения отдельным запросом (`LockInvitation`) и читает ее после: блокирующее чтение с соединением таблицы условий после ожидания чужой фиксации сопоставило бы новый `terms_version` со строкой условий, взятой до ожидания, и ничего не нашло бы. Создание повторяется ограниченное число раз, если видимая когорта изменилась во время блокировки. -- Индикатор. `salary_fit` всегда `not_available`, а `contact_access` - `not_granted` без полей. Индикатору нужен минимум кандидата, а его вычисление до появления лимита из трех установок в день и семидневного отключения позволило бы организации подбирать минимум правками черновика, поэтому пока не считается и не применяется ни то ни другое. +- Индикатор. `salary_fit` всегда `not_available`; `contact_access` выводится из разрешения ([Чтение контактов и отзыв](#чтение-контактов-и-отзыв)). Индикатору нужен минимум кандидата, а его вычисление до появления лимита из трех установок в день и семидневного отключения позволило бы организации подбирать минимум правками черновика, поэтому пока не считается и не применяется ни то ни другое. Как подключаются следующие операции: правила пары читают индекс по организации и кандидату. Контактное разрешение появляется с принятием ([Принятие кандидатом](#принятие-кандидатом)). Колонки C4 журнала согласий пока не имеют внешних ключей на `organizations` и `invitations`; это последующая задача. -Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, предел ожидающих приглашений на потребность, повышение, отзыв, сторона кандидата сверх списка приглашений, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована. +Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, повышение, отзыв, сторона кандидата сверх списка приглашений, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована. Тесты: `domain/salary_range_test.go` и `domain/invitation_test.go` (точная ширина на 10% и 40%, шаг, пределы, правила условий с pointer, версии, неизменность прежних значений, скрытие при печати), `usecase/invitation/service_test.go` (политика владельца, отказы по handle, порядок проверок, повтор, откат, версии), `adapter/primary/http/v1/invitation_test.go` (преобразование, отсутствие полей кандидата, статусы отказов, курсор) и интеграционные `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations` и `TestInvitationMigrationRollbackKeepsStoredInvitations` на настоящем PostgreSQL. @@ -984,7 +984,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - Доступ. Только владелец, как для черновиков: `ownerCompanyOperations` на HTTP-границе и та же проверка в транзакции; другие роли отправлять не могут. Список кандидата требует подтвержденный аккаунт кандидата, работодатель получает 403. - Порядок проверок после границы: владелец, ключ (422 или повтор), приглашение (404), завершенная отправка (200), версия (412), состояние и видимость (409), затем квота (429). -Не реализовано: предел ожидающих приглашений на потребность и пауза после отказа или "сделки нет" (оба запланированы в контракте), принятие и отмена участия (чтение, просмотр и отказ описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата)), истечение по сроку, отправка писем-уведомлений, общий пул E0 холдинга в порте квоты и матрица ролей и назначений сверх владельца. +Не реализовано: пауза после "сделки нет" (состояние `no_deal` пока не создает ни одна операция), отмена участия (чтение, просмотр, отказ и принятие описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата) и [Принятии кандидатом](#принятие-кандидатом)), отправка писем-уведомлений, общий пул E0 холдинга в порте квоты и матрица ролей и назначений сверх владельца. Предел ожидающих и паузу после отказа см. в [Пределе ожидающих, паузе и истечении](#предел-ожидающих-пауза-и-истечение). Тесты: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`, `usecase/notification/inbox_test.go` (уведомление о приглашении), `adapter/primary/http/v1/invitation_test.go` (статусы, `Retry-After`, курсор кандидата) и интеграционные `TestOrganizationInvitationSendOverHTTP` (входящие до любого письма, повторы с одной строкой каждого вида и одним списанием, срок 3 дня при остановленной почте и повторе ее задания, видимость, устаревшая версия, только владелец, квота, страницы) и `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage`. @@ -992,20 +992,20 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове Реализовано: `GetMyInvitation`, `ViewMyInvitation` и `DeclineMyInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Код: `domain/invitation_answer.go`, `usecase/invitation/view.go` и `decline.go`, HTTP-обработчик `adapter/primary/http/v1/invitation_candidate.go`, адаптер `adapter/secondary/postgres/invitation_answer.go` с `db/queries/invitation_answers.sql` и миграция `00039_answer_invitations.sql`. -- Чтение без побочного эффекта. `GetMyInvitation` читает доставленное приглашение по кандидату из сессии и приглашению, с текущими условиями и текущим названием организации-отправителя, и ничего не записывает. Просмотр - явная команда `ViewMyInvitation`, как требует контракт, поэтому предзагрузка, повтор или обновление кэша не меняют то, что видит организация. Черновик, приглашение другого кандидата и неизвестный идентификатор дают одинаковый 404; аккаунт работодателя получает 403. -- Просмотр. В `delivered` до срока команда переводит приглашение в `viewed` одним условным UPDATE (`state`, `version` плюс один, `viewed_at`, `updated_at`), сохраняет `response_deadline_at` и добавляет событие аудита `viewed`. В любом другом состоянии, а также в момент срока и позже, она ничего не меняет и отвечает 200 с приглашением как есть. Ключа и версии она не принимает; одновременные просмотры встают в очередь на блокировке строки, побеждает первый. +- Чтение без побочного эффекта. `GetMyInvitation` читает доставленное приглашение по кандидату из сессии и приглашению, с текущими условиями и текущим названием организации-отправителя, и не записывает просмотр. Единственное, что чтение может изменить, - истечение срока: чтение в срок или позже сначала переводит приглашение в `expired` ([Предел ожидающих, пауза и истечение](#предел-ожидающих-пауза-и-истечение)). Просмотр - явная команда `ViewMyInvitation`, как требует контракт, поэтому предзагрузка, повтор или обновление кэша не меняют то, что видит организация. Черновик, приглашение другого кандидата и неизвестный идентификатор дают одинаковый 404; аккаунт работодателя получает 403. +- Просмотр. В `delivered` до срока команда переводит приглашение в `viewed` одним условным UPDATE (`state`, `version` плюс один, `viewed_at`, `updated_at`), сохраняет `response_deadline_at` и добавляет событие аудита `viewed`. В момент срока и позже сначала применяется истечение, и ответ 200 показывает `expired` без записи просмотра; в любом другом состоянии команда ничего не меняет и отвечает 200 с приглашением как есть. Ключа и версии она не принимает; одновременные просмотры встают в очередь на блокировке строки, побеждает первый. - Отказ. Разрешен из `delivered`, `viewed` и запланированного `counter` до срока. Одна транзакция переводит приглашение в терминальное `declined` (`responded_at`, `version` плюс один), сохраняет причину и необязательный комментарий в `invitation_declines`, добавляет событие аудита `declined` и хранит исход под ключом. Согласия, контактного разрешения и события outbox она не пишет. Комментарий проверяется по правилу схемы с юникодным понятием пробела и не принимает управляющие символы, кроме перевода строки и табуляции, потому что текст PostgreSQL не хранит NUL (400 по `/comment`). - Отзывчивость. Событие `declined` (`kind`, `version`, кандидат в `actor_id`, `occurred_at`) - ответ кандидата, который будут считать запланированные метрики отзывчивости организации. Оно всегда своевременно, потому что опоздавший отказ отклоняется, и никогда не означает согласие или найм. Ни причины, ни комментария в нем нет. - Приватность отказа. Организация читает только `declined` и `responded_at`: ни одна ее операция не читает `invitation_declines`, а событие аудита не называет причину. Комментарий не логируется, не попадает в уведомления и не копируется в сохраненный исход; кандидат читает причину и комментарий обратно в `decline`. - Порядок проверок после границы: кандидат (403), ключ (422 или повтор), приглашение (404, сохраняется), тот же отказ на отклоненном приглашении (200 с новым ключом или старой версией), другая причина или комментарий на отклоненном приглашении, иное терминальное состояние или прошедший срок (409 при любой версии, сохраняется), версия (412, не сохраняется), затем состояние без открытого ответа (409, сохраняется). `invitation_decline_results` хранит только исход и приглашение: отклоненное приглашение и его отказ не меняются, поэтому повтор собирает тот же ответ, а комментарий хранится в одном месте. -- Срок. Истечение пока не реализовано, поэтому ни чтение, ни команда не выполняют переход в `expired`. Просмотр в момент срока и позже ничего не меняет, а отказ в момент срока и позже отвечает 409 `state_conflict`, как контракт требует для опоздавшей команды; приглашение остается `delivered` или `viewed` с прошедшим сроком, пока не появится истечение. Условные UPDATE повторяют проверку срока, поэтому команда не пересечет его между проверкой и записью. +- Срок. Команда в срок или позже сначала применяет истечение: приглашение переходит в `expired` с причиной `invitation_timeout`, и только после этого проверяются состояние и версия. Отказ в момент срока и позже отвечает 409 `state_conflict`, как контракт требует для опоздавшей команды. Условные UPDATE повторяют проверку срока, поэтому команда не пересечет его между проверкой и записью. Порядок блокировок и правила истечения описаны в [Пределе ожидающих, паузе и истечении](#предел-ожидающих-пауза-и-истечение). - Согласие и разрешение. Отказ не создает ни согласия, ни разрешения, поэтому после отказа `contact_consent` и `contact_grant` равны null. Принятие описано в [Принятии кандидатом](#принятие-кандидатом). - Скрытие. Чтение кандидата показывает организацию-отправителя и после того, как кандидат скрыл от нее профиль: скрытие не дает организации видеть кандидата, а кандидату нужно знать, кто прислал предложение, чтобы ответить. Исходящее содержимое, наоборот, следует скрытию: уведомление о приглашении во входящих теряет содержимое (`ResolveInvitationNotice`). -- Блокировки. Команда кандидата блокирует только строку приглашения (`LockCandidateInvitation`) после собственной записи идемпотентности кандидата и никогда не блокирует организацию. Команда организации берет сначала блокировку организации, а потом строку приглашения, поэтому порядки не пересекаются: команда кандидата не ждет блокировку организации, удерживая строку. +- Блокировки. Команда кандидата блокирует строку приглашения (`LockCandidateInvitation`) после собственной записи идемпотентности кандидата. Отказ дополнительно берет блокировку организации до строки, потому что меняет паузу пары; он никогда не берет ее после строки. Команда организации берет сначала блокировку организации, а потом строку приглашения, поэтому порядки не пересекаются. Просмотр и принятие организацию не блокируют. - Правила базы миграции 00039: виды событий `viewed` и `declined` без измененных полей; `invitations_answer_matches_state` (у доставленного приглашения нет просмотра и ответа, у просмотренного есть просмотр, у отклоненного есть ответ, и ни то ни другое не раньше доставки); триггер `invitations_guard_answer`, который не дает сдвинуть или отменить просмотр или ответ и выйти из `declined`; `invitation_declines` с известными причинами, границей комментария, триггером, который привязывает строку к отклоненному приглашению с тем же моментом ответа, и запретом UPDATE и DELETE; отложенный ограничивающий триггер `invitations_require_decline`, чтобы отклоненное приглашение без записи отказа не зафиксировалось. Откат миграции отказывает, пока есть просмотр, отказ или сохраненный исход. - Уведомление. В контракте нет вида уведомления об ответе, поэтому организация пока не получает записи во входящих о просмотре или отказе; состояние она видит в своем списке приглашений. Уведомление об ответе запланировано как изменение контракта. -Не реализовано: истечение по сроку и его применение при чтении, отмена участия, встречное предложение, которое дало бы `counter`, агрегаты причин отказа с минимальным размером группы, метрики отзывчивости, 30-дневная пауза после отказа и уведомление организации об ответе. +Не реализовано: отмена участия, встречное предложение, которое дало бы `counter`, агрегаты причин отказа с минимальным размером группы, метрики отзывчивости и уведомление организации об ответе. Тесты: `domain/invitation_answer_test.go` (просмотр только из `delivered` до срока, отказ из `delivered`, `viewed` и `counter`, отклонение терминальных и опоздавших приглашений, правила комментария, правила сохраненного ответа, маскирование), `usecase/invitation/answer_test.go` (чтение без побочного эффекта, сохранение срока, повторы, порядок проверок, чужие вызывающие, неверные комментарии), `adapter/primary/http/v1/invitation_candidate_test.go` (статусы и ответ без данных кандидата) и интеграционные `TestCandidateInvitationViewAndDeclineOverHTTP` (чтение и просмотр с тем же сроком, одновременные просмотры с одним событием, отказ с `other` без комментария и без согласия C4, сохраненное событие ответа, повторы и конфликты, комментарий скрыт от организации и аудита, чужие кандидаты и работодатели, CSRF и Origin, скрытие, устаревшая версия, опоздавшая команда) и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback`. @@ -1018,15 +1018,55 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - Повторы. Принятое приглашение, у которого разрешение имеет ту же версию условий и тот же набор полей, отвечает 200 тем же приглашением под тем же или новым ключом и при более старом `expected_version`, и ничего не записывает. Другая версия условий или другой набор полей отвечают 409 `state_conflict` и сохраняются под ключом. Исходы под ключом: `accepted`, `not_found`, `state_conflict`; устаревшая версия и отказ по согласию не сохраняются. - Разрешение. `contact_grants` хранит организацию, кандидата, исходное приглашение (одно разрешение на приглашение), запись согласия (одну на разрешение), канонический набор полей, версию условий, версию текста согласия, время выдачи и отметку отзыва (`revoked_at` и `revocation_reason`). Эта задача отметку не ставит; отзыв - отдельная операция. Составные внешние ключи связывают разрешение с приглашением той же организации и того же кандидата и с записью C4 того же субъекта, организации, приглашения и версии условий. Триггер проверяет, что поля, версия текста и время выдачи совпадают с записью; второй триггер запрещает DELETE и любое изменение, кроме одной отметки отзыва. Отложенный триггер ограничения не дает зафиксировать принятое приглашение без разрешения. Разрешение хранит виды контактов, но не их значения. - Вид кандидата. Пока принятие возможно, `contact_consent` содержит отрисованный текст C4 и виды, которые есть в профиле, в порядке контракта; ничего не выбрано заранее. Поле равно null, если в профиле нет подтвержденного вида. После принятия `contact_grant` содержит выбранные виды, статус, версию условий, версию текста согласия и `readable`. `readable` истинно только тогда, когда организация может читать профиль сейчас: публикация действует и кандидат не скрыл организацию. Иначе `blocked_by` равно `visibility`. У отказанного приглашения оба поля равны null. -- Решение о видимости. Принятие разрешено, пока профиль скрыт от организации или не опубликован, как показывает пример контракта с заблокированным разрешением. Принятие не публикует профиль, не меняет публикацию и не снимает и не добавляет скрытие. Разрешение остается сохраненным и станет читаемым, когда кандидат опубликует профиль или уберет скрытие организации: `readable` пересчитывается при каждом чтении, поэтому само разрешение не меняется. Чтение контактов через разрешение - отдельная операция; организация по-прежнему видит `contact_access` как не выданный. +- Решение о видимости. Принятие разрешено, пока профиль скрыт от организации или не опубликован, как показывает пример контракта с заблокированным разрешением. Принятие не публикует профиль, не меняет публикацию и не снимает и не добавляет скрытие. Разрешение остается сохраненным и станет читаемым, когда кандидат опубликует профиль или уберет скрытие организации: `readable` пересчитывается при каждом чтении, поэтому само разрешение не меняется. Организация видит `contact_access` как `closed`, пока разрешение заблокировано, и как `available`, когда оно становится читаемым (см. [Чтение контактов и отзыв](#чтение-контактов-и-отзыв)). - Конкурентность. Командой кандидата блокировка организации не берется. Два конкурентных принятия одной версии дают один переход: второе ждет строку и затем отвечает как повтор - 200 тем же ответом при тех же условиях и полях и 409 при другом наборе полей. - Часы. Время ответа берется у сервиса приглашений, время выдачи разрешения - у сервиса согласий. В продакшене оба читают часы процесса, поэтому могут расходиться на микросекунды; разрешение сохраняет время согласия. Повтор сохраненного принятия восстанавливает ответ из приглашения и разрешения. Таблица исходов не хранит копию ответа, поэтому позднее изменение состояния было бы видно в повторе, как и для отказа. - Ключи журнала. Колонки C4 в журнале согласий пока не имеют внешних ключей на `organizations` и `invitations`: тесты журнала пишут записи C4 с синтетическими идентификаторами. Составные ключи разрешения сохраняют согласованность принятия без этой правки; ключи журнала требуют фикстур с настоящими приглашениями и остаются последующей задачей. -Не реализовано: чтение контактов через разрешение, отзыв разрешения (после закрытия публикации, скрытия, отзыва согласия или отмены участия), встречное предложение, истечение по сроку и отмена участия. +Не реализовано: встречное предложение, отмена участия, включая отзыв разрешения при отмене участия (остальные отзывы описаны в [Чтение контактов и отзыв](#чтение-контактов-и-отзыв)). Тесты: `domain/contact_grant_test.go` (разрешение из записи согласия, правила области и отзыва, вид видимости, отрисовка предложения и `Accept`), `usecase/invitation/accept_test.go` (порядок проверок, повторы, устаревшие условия, поздние команды, указатели согласия, видимость без изменения публикации), `adapter/primary/http/v1/invitation_candidate_test.go` (коды отказов) и интеграционные `TestCandidateInvitationAcceptOverHTTP` (разрешение только на email, повторы и конфликты, устаревшие и поднятые условия, конкурентные принятия, скрытый профиль, поздний ответ, проверки согласия и видов, журнал сервера) и `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` на настоящем PostgreSQL. +### Предел ожидающих, пауза и истечение + +Реализовано: предел ожидающих приглашений на потребность, пауза пары организации и кандидата после отказа и истечение приглашения в срок ответа. Код: `usecase/invitation/pending_limit.go` (проверки отправки), `usecase/invitation/expire.go` (обработчик задания `invitation.response_deadline`, общая функция истечения и постановка задания при доставке), `domain/invitation_expiry.go` (`Expire` и `ExpiryEvent`), `usecase/invitation/send.go`, `decline.go`, `accept.go` и `view.go` (истечение перед ответом кандидата), адаптер `adapter/secondary/postgres/invitation_expiry.go` с `db/queries/invitation_pending.sql`, `invitation_cooldowns.sql` и `invitation_expiry.sql`, регистрация в `jobHandlers()` (`bootstrap/jobs.go`) и миграция `00043_expire_invitations.sql`. + +- Предел. Отправка считает приглашения потребности, которые ждут ответа (`delivered`, `viewed`, `counter`), и отказывает с 409 `state_conflict`, когда их уже `max_pending_per_need` из эффективной политики (20 в демо-политике). Счет точный: отправка берет блокировку организации раньше всего, а перевести приглашение в ожидание может только отправка. Приглашение без потребности предела не имеет, его ограничивает квота. Уход из ожидания (отказ, истечение, принятие) освобождает место, но не возвращает недельную квоту: квота списана при отправке и не меняется. +- Пауза. Отправка отказывает с 409 `state_conflict`, пока с последнего отказа кандидата этой организации не прошло `repeat_after_decline_days` (30 дней). Пауза относится к паре организации и кандидата, а не к потребности и не к сотруднику: другая потребность или другой владелец той же организации получает тот же отказ. Пауза после "сделки нет" пока не действует: состояние `no_deal` ни одна операция не создает. +- Порядок блокировок. Отказ кандидата берет блокировку организации до строки приглашения, как все команды, которые могут менять паузу пары. Так отказ и отправка одной пары упорядочены: отправка не пропускает отказ, закоммиченный раньше ее проверки. Порядок тот же, что в [отправке](#отправка-приглашений): организация, затем строки приглашений. +- Срок. Отправка ставит задание `invitation.response_deadline` в той же транзакции, что и доставка: ключ - идентификатор приглашения, срок исполнения - `response_deadline_at`, payload - только идентификатор. Обработчик `ResponseDeadlineJob` выполняется в транзакции, которая блокирует строку приглашения. Если приглашение все еще ждет ответа, оно переходит в `expired` с причиной `invitation_timeout`; иначе обработчик ничего не меняет. Повтор задания безопасен: второе выполнение не находит приглашения, которое ждет ответа. +- Команды кандидата в срок или позже. Просмотр, отказ и принятие блокируют строку и читают время уже при удерживаемой блокировке; чтение (`GetMyInvitation`) блокирует строку, только если срок прошел. В обоих случаях при прошедшем сроке сначала применяется истечение тем же условным UPDATE и той же записью аудита. Чтение и просмотр затем отвечают приглашением в состоянии `expired` без записи просмотра; отказ и принятие отвечают 409 `state_conflict` и сохраняют исход под ключом. Список входящих и чтение организации истечение не применяют: они показывают сохраненное состояние, пока задание или следующая команда кандидата его не применили. +- Что создает истечение. Переход пишет только событие аудита `expired` с версией, без полей и без актора (`actor_id` пуст, потому что переход сделал сервер). Согласие C4, контактное разрешение, запись отказа и квота не создаются и не меняются. Срок и условия сохраняются. Ограничение `invitation_events_system_actor` допускает пустого актора только у `expired`, триггер `invitations_guard_expiry` разрешает переход только из `delivered` или `viewed` и не раньше срока, а `invitations_expiry_reason` требует причину. +- Гонка с принятием. Принятие в срок или позже всегда отказывает: и принятие, и задание решают по времени, известному при удерживаемой строке. Из двух путей, которые берут строку первыми, итог один: приглашение `expired` без гранта. Принятие до срока, закоммиченное раньше задания, оставляет задание без действия. Проверяют `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres` (гонка) и `TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres` (задание первым). +- Часы. Срок и лимиты решаются по часам приложения, которые внедряются в usecase и в обработчик задания; часы базы не решают. Обработчик, которому часы еще не показали срок, возвращает ошибку, и задание повторяется по backoff, а не завершается без истечения. +- Запуск. Истечение по заданию выполняет воркер, который включает `JOBS_ENABLED`; без него задание ждет в базе. Команды кандидата применяют истечение и без воркера, поэтому ответ кандидата остается верным. +- Миграция 00043. Новый вид события `expired`; ограничения `invitation_events_expiry_changes_no_field` и `invitation_events_system_actor`; триггер `invitations_guard_expiry`; частичные индексы `invitations_pending_need_idx` (ожидающие приглашения потребности) и `invitations_declined_pair_idx` (отказы пары); перенос заданий истечения для приглашений, доставленных до миграции, с ключом по идентификатору и `ON CONFLICT DO NOTHING`. Откат отказывает, пока есть истекшие приглашения, и удаляет задания этого вида. + +Не реализовано: пауза после "сделки нет" (нужна операция, которая переводит приглашение в `no_deal` и задает время выхода из паузы), истечение состояния `counter` (его пока не создает ни одна операция), причина `negotiation_timeout` и предел для приглашений без потребности, если его решат ввести. + +Тесты: `domain/invitation_expiry_test.go` (истечение только ожидающего приглашения после срока, сохранение срока и условий, событие без актора); `usecase/invitation/pending_limit_test.go` (предел при 20 ожидающих и 21-м, два конкурентных отправления при 19, освобождение места без возврата квоты, пауза на 29 и 30 день для другого владельца и другой потребности, пауза не действует на другого кандидата и на истекшее приглашение); `usecase/invitation/expire_test.go` (истечение чтением, просмотром, принятием и отказом в срок, задание и его повтор, отказ задания с неверным payload); интеграционные `TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres`, `TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres`, `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres`, `TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres` и `TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries` в `integration_test/invitation_expiry_test.go`. + +### Чтение контактов и отзыв + +Реализовано: `GetOrganizationInvitationContacts` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)) в `usecase/invitation/contacts.go` и `adapter/primary/http/v1/contacts.go`; тип раскрытия в `domain/contact_disclosure.go`; блокировка разрешения `ContactGrantRepository.LockForRead` в `adapter/secondary/postgres/invitation_accept.go`; закрытия в `consent_revocation.go` (`ConsentRevocationEffects.Apply`), `privacy_view.go` (`CloseForVisibility`) и `contact_grant_closure.go`; запросы в `db/queries/contact_grants.sql`; миграция `00042_index_contact_grants_by_candidate.sql`, которая добавляет индекс по кандидату для закрытий на уровне всего кандидата. `contact_access` организации выводится в `usecase/invitation/contact_access.go` той же проверкой `readableContactGrant`, которой пользуется чтение (`usecase/invitation/contacts.go`). + +- Доступ. Middleware компании до обработчика проверяет сессию, активное членство владельца и путь. Участник без роли владельца получает 403, аккаунт без членства получает 404, а аккаунт кандидата получает 403. Юзкейс повторяет проверку владельца внутри своей транзакции. В MVP контакты не читает никакая другая роль. +- Порядок блокировок. Чтение берет по порядку: организацию и членство (`LockActiveMembership`, общие блокировки), аккаунт кандидата, самую новую действующую запись C2, публикацию вместе с записью C2 (это же применяет скрытие организации), запись C4 разрешения и само разрешение. Непроверенное чтение разрешения до блокировок только называет кандидата, который у разрешения не меняется. Отзыв C4 блокирует запись, затем разрешение в том же порядке, поэтому две операции не ждут друг друга в обратном порядке. Блокировки видимости идут первыми: скрытие или отзыв C2, зафиксированные раньше, видны чтению, а те, что ждут, выполняются после фиксации чтения. +- Решение. Чтение отвечает 200, только если разрешение активно, его запись C4 не отозвана и организация сейчас может читать публикацию. Любой другой случай отвечает 404 `not_found` и не говорит, какой именно: нет разрешения этого приглашения для этой организации, разрешение или запись C4 отозваны, профиль закрыт или скрыт от организации. Вид возвращает значение, только если профиль держит его как подтвержденное утверждение; любой другой вид равен null, а предложение, которое никто не подтвердил, не раскрывается. Ответ имеет `Cache-Control: no-store`. +- Закрытия. Каждое закрытие выполняется в транзакции изменения, ставит время отзыва и его причину и никогда не открывает разрешение заново: + - Отзыв C4 для организации (`consent_revoked`) закрывает разрешения, которые ссылаются на отозванные записи. Разрешения других организаций и других приглашений остаются открытыми. + - Отзыв C2 (`visibility_closed`) закрывает все действующие разрешения кандидата, даже если строки публикации, которую надо закрыть, нет. + - Закрытие публикации (`visibility_closed`) закрывает все действующие разрешения кандидата. + - Скрытие организации (`visibility_closed`) закрывает действующие разрешения этой организации, в том числе при повторном скрытии. Снятие скрытия и повторная публикация ничего не закрывают и ничего не открывают: закрытое разрешение сохраняет первую отметку, которую охранный триггер допускает один раз. + - Разрешение, сохраненное, пока профиль нельзя читать, этим состоянием не закрывается. Оно остается действующим и заблокированным видимостью, становится читаемым, когда кандидат публикует профиль или снимает скрытие, а закрывает его следующее закрывающее событие. + - Отзыв приглашения организацией не меняет разрешение. Отмена участия кандидатом (`participation_cancelled`) не реализована. Отзыв C1 разрешение не закрывает: контракт не называет для него причины. +- Вид организации. Каждый ответ организации с `contact_access` выводит его из разрешения приглашения в транзакции запроса: `GetOrganizationInvitation`, `ListOrganizationInvitations` и ответы создания черновика, изменения и отправки. Без разрешения ответ `not_granted`, отозванное разрешение дает `closed`. Действующее разрешение проходит те же блокировки видимости и проверки, что и чтение: сначала видимость, затем запись C4 и само разрешение. Поэтому вид говорит `available` именно тогда, когда чтение в этот момент бы прошло, и `closed` в остальных случаях. Вид перечисляет выданные виды только при `available`; `closed` не несет причины, а значение контакта никогда не входит в вид. Вывод читает разрешение любого состояния, поэтому отозванное приглашение сохраняет состояние своего разрешения, как требует контракт. У отклоненного и истекшего приглашения разрешения нет, и они отвечают `not_granted`. Идемпотентные повторы создания и отправки возвращают сохраненный исходный ответ, поэтому их `contact_access` - состояние на момент первого ответа. Вывод делает один поиск разрешения на приглашение, а блокировки общего доступа берет только для приглашения с разрешением. +- Квота и аудит. Успешное чтение записывает одну строку `contact_read` в `candidate_card_access_events` в той же транзакции, с выданными видами и никогда без значения. Чтение не расходует квоту просмотров карточек, потому что контракт не засчитывает чтение контактов в эту квоту. Собственное чтение истории кандидатом остается операцией только контракта. +- Не реализовано: отмена кандидатом и отзыв приглашения организацией. `CurrentContactFields` в `usecase/candidateview` остается закрытым, потому что чтение по дескриптору карточки не имеет операции контракта. + +Тесты: `domain/contact_disclosure_test.go` (значения только подтвержденных видов, отказ для отозванного разрешения, редактирование при выводе), `usecase/invitation/contacts_test.go` (проверки владельца и роли, видимость, отозванное разрешение и запись C4, неизвестные приглашения) `usecase/invitation/contact_access_test.go` (состояния разрешения для организации, их согласие с чтением в каждом закрывающем состоянии, заблокированное разрешение, которое открывается, когда становится видимым, и отозванное разрешение, которое никогда не открывается заново) и интеграционный тест `TestOrganizationContactReadsAndRevocationOverHTTP` через настоящий роутер и PostgreSQL. Он покрывает чтение только email, повторное чтение, отказы для другой организации, участника и кандидата, отзыв C4 при независимой организации, скрытие и снятие скрытия без повторного открытия, отзыв C2 с повторной публикацией, закрытие публикации и индекс. Он также проверяет `contact_access` в одиночном чтении и в списке после каждого изменения, отклоненное приглашение и истекшее; истекшее идет последним, потому что переводит часы. + + ## 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/COMPANY_QUOTAS.md b/docs/ru/COMPANY_QUOTAS.md index 725fa72..7805c0e 100644 --- a/docs/ru/COMPANY_QUOTAS.md +++ b/docs/ru/COMPANY_QUOTAS.md @@ -1,6 +1,6 @@ # Квоты компании -Резервирование квот компании реализовано в домене, usecase `companyquota` и адаптере PostgreSQL. Для резервирования приглашений и просмотров карточек кандидатов используется порт, связанный с транзакцией. Рабочий процесс создания и отправки приглашений пока не реализован; резервирование квоты не означает, что приглашение отправлено. +Резервирование квот компании реализовано в домене, usecase `companyquota` и адаптере PostgreSQL. Для резервирования приглашений и просмотров карточек кандидатов используется порт, связанный с транзакцией. Приглашение тратит одно место недельной квоты при отправке (`SendOrganizationInvitation`): черновик квоту не тратит, а повтор отправки того же приглашения не тратит второе место. Уход приглашения из ожидания ответа (отказ, истечение, принятие) освобождает место в пределе ожидающих приглашений на потребность, но не возвращает недельную квоту; см. [Предел ожидающих, пауза и истечение](ARCHITECTURE.md#предел-ожидающих-пауза-и-истечение). ## Политика и доверенный уровень компании diff --git a/frontend/src/shared/api/endpoints/invitation/invitation.ts b/frontend/src/shared/api/endpoints/invitation/invitation.ts index a5e3339..ce30632 100644 --- a/frontend/src/shared/api/endpoints/invitation/invitation.ts +++ b/frontend/src/shared/api/endpoints/invitation/invitation.ts @@ -518,7 +518,7 @@ export const useUpdateOrganizationInvitation = , * * Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. * - * The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are not checked yet. + * The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced; the pause after a no deal is planned, because no operation produces the state `no_deal` yet. * * Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. *