feat(invitations): check contact grants on every read, cap pending invitations, and expire them at the deadline

This commit is contained in:
shira committed 2026-10-09 19:06:50 +03:00
1 parent 676b3c6e24
commit 12a7213d4a
67 files changed
+4255 -149

No files matched your search

+6 -2
View File
@@ -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.
+6 -2
View File
@@ -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. Такой запрос ожидает эксперта, не назначает грейд и не выдает согласие.
@@ -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;
@@ -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'
)
);
+66
View File
@@ -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;
@@ -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;
+30
View File
@@ -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;
+11
View File
@@ -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');
@@ -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)
}
})
}
@@ -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)
@@ -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 {
@@ -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)
}
}
@@ -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))
@@ -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
@@ -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
@@ -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
@@ -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
}
@@ -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 {
@@ -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),
@@ -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"`
@@ -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
}
@@ -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
}
@@ -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)
}
@@ -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))
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
+8 -3
View File
@@ -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(
+8 -3
View File
@@ -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)
}
}
@@ -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)))
}
@@ -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
}
+2 -1
View File
@@ -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 (
+25 -6
View File
@@ -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 }
@@ -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
}
@@ -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)
}
}
+11 -13
View File
@@ -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
}
@@ -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)
}
@@ -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
+12 -2
View File
@@ -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)
@@ -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))
}
}
@@ -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.
@@ -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
}
@@ -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)
}
}
@@ -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
}
@@ -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)
}
}
+34 -8
View File
@@ -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 {
+5 -5
View File
@@ -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
}
@@ -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
}
@@ -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)
}
})
}
}
@@ -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
}
@@ -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)
}
}
+46 -10
View File
@@ -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
}
+17 -7
View File
@@ -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
}
@@ -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()
+29 -11
View File
@@ -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 {