feat(invitations): accept invitations with C4 consent and contact grants; share the E0 quota across holdings

This commit is contained in:
shira committed 2026-10-09 18:03:35 +03:00
1 parent a5990d3fc6
commit 676b3c6e24
59 files changed
+4926 -194

No files matched your search

+5 -1
View File
@@ -38,6 +38,8 @@ The same `Idempotency-Key` and body replay the original `201` snapshot within 24
`TestOrganizationCreationAndOwnerEditingOverHTTP` checks concurrent replay, rollback on owner insertion failure, cross-account denial, persisted reads after rebuilding the API, and reuse of an expired key against PostgreSQL.
The organization joins the holding of the owner account: `CreateWithOwner` creates the holding (table `holdings`, migration `00041_create_holdings.sql`) in the same transaction when the account creates its first organization. The E0 invitation and card-view limits are shared by all E0 organizations of the holding; the pool and lock rules are described in [Company quotas](../docs/en/COMPANY_QUOTAS.md#holding-pool). `TestHoldings` covers the shared pool, account isolation, concurrent reservations, and concurrent creation, and `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` covers the backfill and the guarded rollback.
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` covers company isolation, candidate denial even with a manually inserted membership, denial for other roles, pagination, and owner revocation with the same cookie. A company in the active-membership directory does not grant owner authority; the server checks the role on every request.
## Organization needs
@@ -66,7 +68,9 @@ 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, and decline 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 `contact_consent` and `contact_grant` stay null until the acceptance exists. 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 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 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.
## Support cases
+5 -1
View File
@@ -38,6 +38,8 @@
`TestOrganizationCreationAndOwnerEditingOverHTTP` проверяет в PostgreSQL параллельный повтор, откат при ошибке вставки владельца, запрет чужого доступа, сохранение данных после пересоздания API и повторное использование истекшего ключа.
Организация сохраняется в холдинге аккаунта-владельца: `CreateWithOwner` создает холдинг (таблица `holdings`, миграция `00041_create_holdings.sql`) в той же транзакции при первой организации аккаунта. E0-лимиты приглашений и просмотров карточек общие для всех E0-организаций холдинга; правила пула и блокировок описаны в [квотах компании](../docs/ru/COMPANY_QUOTAS.md#пул-холдинга). `TestHoldings` проверяет общий пул, изоляцию аккаунтов, конкурентные резервирования и параллельное создание, а `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` - заполнение миграции и защищенный откат.
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяет изоляцию компаний, отказ кандидату даже с вручную добавленным членством, отказ другим ролям, пагинацию и отзыв доступа владельца с той же cookie. Компания в справочнике активных членств не дает права владельца; сервер проверяет роль на каждом запросе.
## Потребности организаций
@@ -66,7 +68,9 @@
Реализована отправка: `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.
Реализованы чтение, просмотр, отказ и принятие кандидата: `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.
## Обращения в поддержку
@@ -0,0 +1,347 @@
-- +goose Up
-- The candidate's acceptance of the current terms with the consent C4. One
-- transaction moves a delivered or viewed invitation to `accepted` before its
-- deadline, records the consent C4 in the consent ledger, stores the contact
-- grant that covers exactly the selected fields, and appends the audit event.
-- The acceptance never changes the publication (C2) and never lifts a hiding:
-- a grant alone does not make the contacts readable, and the read model shows
-- whether the organization may read them now.
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'
)
);
ALTER TABLE invitation_events
DROP CONSTRAINT invitation_events_answer_changes_no_field;
ALTER TABLE invitation_events
ADD CONSTRAINT invitation_events_answer_changes_no_field CHECK (
kind NOT IN ('viewed', 'declined', 'accepted') OR cardinality(changed_fields) = 0
);
-- An accepted invitation records its answer, as a declined one does. The
-- acceptance from `delivered` leaves the view empty.
ALTER TABLE invitations
DROP CONSTRAINT invitations_answer_matches_state;
ALTER TABLE invitations
ADD CONSTRAINT invitations_answer_matches_state CHECK (
(state <> 'delivered' OR (viewed_at IS NULL AND responded_at IS NULL))
AND (state <> 'viewed' OR (viewed_at IS NOT NULL AND responded_at IS NULL))
AND (state NOT IN ('declined', 'accepted') OR responded_at IS NOT NULL)
AND (viewed_at IS NULL OR (delivered_at IS NOT NULL AND viewed_at >= delivered_at))
AND (
responded_at IS NULL
OR (delivered_at IS NOT NULL AND responded_at >= delivered_at)
)
);
-- The contact grant names the invitation together with its candidate, so the
-- grant can only belong to the candidate the invitation was addressed to.
ALTER TABLE invitations
ADD CONSTRAINT invitations_organization_id_id_candidate_id_key UNIQUE (
organization_id, id, candidate_id
);
-- A grant names exactly the C4 record of its acceptance: the same subject,
-- organization, invitation, and terms version. The record stays a ledger row
-- of its own and does not reference the invitation tables, which the ledger
-- migration leaves to a later change.
ALTER TABLE consent_records
ADD CONSTRAINT consent_records_contact_scope_key UNIQUE (
id, subject_id, organization_id, invitation_id, invitation_terms_version
);
-- The contact grant of one accepted invitation. It holds kinds only, never
-- contact values. The grant is created by the acceptance next to its C4 record
-- and the accepted state. Its revocation stamp is reserved for the revocation
-- procedure of a later change, and this migration never sets it.
CREATE TABLE contact_grants (
id uuid NOT NULL,
organization_id uuid NOT NULL,
candidate_id uuid NOT NULL,
source_invitation_id uuid NOT NULL,
consent_record_id uuid NOT NULL,
terms_version bigint NOT NULL,
fields text [] NOT NULL,
consent_text_version text NOT NULL,
granted_at timestamptz NOT NULL,
revoked_at timestamptz,
revocation_reason text,
CONSTRAINT contact_grants_pkey PRIMARY KEY (id),
-- One grant per accepted invitation, and one per consent record.
CONSTRAINT contact_grants_source_invitation_key UNIQUE (source_invitation_id),
CONSTRAINT contact_grants_consent_record_key UNIQUE (consent_record_id),
CONSTRAINT contact_grants_candidate_fkey FOREIGN KEY (candidate_id)
REFERENCES users (id) ON DELETE RESTRICT,
CONSTRAINT contact_grants_invitation_fkey FOREIGN KEY (
organization_id, source_invitation_id, candidate_id
) REFERENCES invitations (organization_id, id, candidate_id) ON DELETE RESTRICT,
CONSTRAINT contact_grants_terms_fkey FOREIGN KEY (
source_invitation_id, terms_version
) REFERENCES invitation_terms_versions (invitation_id, version) ON DELETE RESTRICT,
CONSTRAINT contact_grants_consent_fkey FOREIGN KEY (
consent_record_id,
candidate_id,
organization_id,
source_invitation_id,
terms_version
) REFERENCES consent_records (
id,
subject_id,
organization_id,
invitation_id,
invitation_terms_version
) ON DELETE RESTRICT,
CONSTRAINT contact_grants_terms_version_positive CHECK (terms_version > 0),
CONSTRAINT contact_grants_fields_canonical CHECK (
consent_field_set_is_canonical(fields)
),
CONSTRAINT contact_grants_consent_text_version_format CHECK (
consent_text_version ~ '^[A-Za-z0-9._-]{1,64}$'
),
CONSTRAINT contact_grants_revocation_stamp CHECK (
(revoked_at IS NULL) = (revocation_reason IS NULL)
AND (
revocation_reason IS NULL
OR revocation_reason IN (
'consent_revoked', 'participation_cancelled', 'visibility_closed'
)
)
AND (revoked_at IS NULL OR revoked_at >= granted_at)
)
);
-- The grant of an organization's invitations is read for one candidate while
-- the grant is active.
CREATE INDEX contact_grants_organization_candidate_active_idx
ON contact_grants (organization_id, candidate_id)
WHERE revoked_at IS NULL;
-- Outcome of an idempotent acceptance, kept beside the generic idempotency
-- record and removed with it after the 24-hour replay window. An accepted
-- invitation keeps its answer and its grant, so a replay rebuilds the response
-- from them and the outcome holds only the invitation and the result.
CREATE TABLE invitation_accept_results (
scope_hash bytea NOT NULL,
invitation_id uuid NOT NULL,
outcome text NOT NULL,
CONSTRAINT invitation_accept_results_pkey PRIMARY KEY (scope_hash),
CONSTRAINT invitation_accept_results_idempotency_fkey FOREIGN KEY (
scope_hash
) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
CONSTRAINT invitation_accept_results_scope_hash_sha256 CHECK (
octet_length(scope_hash) = 32
),
CONSTRAINT invitation_accept_results_outcome CHECK (
outcome IN ('accepted', 'not_found', 'state_conflict')
)
);
-- A view, an answer, and an acceptance are never undone, and a declined or
-- accepted invitation never returns to an earlier state.
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION invitations_guard_answer() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF (OLD.viewed_at IS NOT NULL AND NEW.viewed_at IS DISTINCT FROM OLD.viewed_at)
OR (OLD.responded_at IS NOT NULL AND NEW.responded_at IS DISTINCT FROM OLD.responded_at)
OR (OLD.state = 'declined' AND NEW.state <> 'declined')
OR (OLD.state = 'accepted' AND NEW.state IN ('draft', 'delivered', 'viewed', 'counter', 'declined')) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitations_answer_immutable',
TABLE = 'invitations',
MESSAGE = 'a view, an answer, a decline, and an acceptance are never undone';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
-- The grant must agree with its C4 record: the fields, the text version, and
-- the grant time are the record's own, so a grant cannot cover a field its
-- consent did not name.
-- +goose StatementBegin
CREATE FUNCTION contact_grants_match_consent() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS (
SELECT 1
FROM consent_records AS record
WHERE
record.id = NEW.consent_record_id
AND record.purpose = 'c4'
AND record.field_set = NEW.fields
AND record.text_version = NEW.consent_text_version
AND record.granted_at = NEW.granted_at
) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'contact_grants_match_consent',
TABLE = 'contact_grants',
MESSAGE = 'a contact grant agrees with its consent C4 record';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER contact_grants_match_consent
BEFORE INSERT ON contact_grants
FOR EACH ROW EXECUTE FUNCTION contact_grants_match_consent();
-- A grant changes only by its one revocation stamp, which is set once. Every
-- other change, and every delete, is refused.
-- +goose StatementBegin
CREATE FUNCTION contact_grants_guard_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF OLD.revoked_at IS NOT NULL
OR NEW.revoked_at IS NULL
OR (
NEW.id, NEW.organization_id, NEW.candidate_id, NEW.source_invitation_id,
NEW.consent_record_id, NEW.terms_version, NEW.fields,
NEW.consent_text_version, NEW.granted_at
) IS DISTINCT FROM (
OLD.id, OLD.organization_id, OLD.candidate_id, OLD.source_invitation_id,
OLD.consent_record_id, OLD.terms_version, OLD.fields,
OLD.consent_text_version, OLD.granted_at
) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'contact_grants_immutable',
TABLE = 'contact_grants',
MESSAGE = 'contact grants are append-only: only an active grant can be revoked, once';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER contact_grants_guard_change
BEFORE UPDATE ON contact_grants
FOR EACH ROW EXECUTE FUNCTION contact_grants_guard_change();
CREATE TRIGGER contact_grants_refuse_delete
BEFORE DELETE ON contact_grants
FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change();
-- An accepted invitation has its contact grant by the end of the transaction
-- that accepted it.
-- +goose StatementBegin
CREATE FUNCTION invitations_require_contact_grant() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS (
SELECT 1
FROM contact_grants
WHERE
contact_grants.organization_id = NEW.organization_id
AND contact_grants.source_invitation_id = NEW.id
) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitations_acceptance_recorded',
TABLE = 'invitations',
MESSAGE = 'an accepted invitation records its contact grant';
END IF;
RETURN NULL;
END;
$$;
-- +goose StatementEnd
CREATE CONSTRAINT TRIGGER invitations_require_contact_grant
AFTER UPDATE ON invitations
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW
WHEN (new.state = 'accepted' AND old.state <> 'accepted')
EXECUTE FUNCTION invitations_require_contact_grant();
-- +goose Down
-- A rollback must not silently remove an acceptance, its consent, or its grant.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM invitation_events WHERE kind = 'accepted')
OR EXISTS (SELECT 1 FROM invitations WHERE state = 'accepted')
OR EXISTS (SELECT 1 FROM contact_grants)
OR EXISTS (SELECT 1 FROM consent_records WHERE purpose = 'c4')
OR EXISTS (SELECT 1 FROM invitation_accept_results) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitation_acceptances_retained',
TABLE = 'invitation_events',
MESSAGE = 'accepted invitations and their consents must be resolved before rollback';
END IF;
END;
$$;
-- +goose StatementEnd
DROP TRIGGER invitations_require_contact_grant ON invitations;
DROP FUNCTION invitations_require_contact_grant();
DROP TABLE invitation_accept_results;
DROP TABLE contact_grants;
DROP FUNCTION contact_grants_guard_change();
DROP FUNCTION contact_grants_match_consent();
ALTER TABLE consent_records
DROP CONSTRAINT consent_records_contact_scope_key;
ALTER TABLE invitations
DROP CONSTRAINT invitations_organization_id_id_candidate_id_key;
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION invitations_guard_answer() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF (OLD.viewed_at IS NOT NULL AND NEW.viewed_at IS DISTINCT FROM OLD.viewed_at)
OR (OLD.responded_at IS NOT NULL AND NEW.responded_at IS DISTINCT FROM OLD.responded_at)
OR (OLD.state = 'declined' AND NEW.state <> 'declined') THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitations_answer_immutable',
TABLE = 'invitations',
MESSAGE = 'a view, an answer, and a decline are never undone';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
ALTER TABLE invitations
DROP CONSTRAINT invitations_answer_matches_state;
ALTER TABLE invitations
ADD CONSTRAINT invitations_answer_matches_state CHECK (
(state <> 'delivered' OR (viewed_at IS NULL AND responded_at IS NULL))
AND (state <> 'viewed' OR (viewed_at IS NOT NULL AND responded_at IS NULL))
AND (state <> 'declined' OR responded_at IS NOT NULL)
AND (viewed_at IS NULL OR (delivered_at IS NOT NULL AND viewed_at >= delivered_at))
AND (
responded_at IS NULL
OR (delivered_at IS NOT NULL AND responded_at >= delivered_at)
)
);
ALTER TABLE invitation_events
DROP CONSTRAINT invitation_events_answer_changes_no_field;
ALTER TABLE invitation_events
ADD CONSTRAINT invitation_events_answer_changes_no_field CHECK (
kind NOT IN ('viewed', 'declined') OR cardinality(changed_fields) = 0
);
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')
);
@@ -0,0 +1,134 @@
-- +goose Up
-- Holdings group the organizations that one account founded, the way the
-- divisions of one company belong to one parent. A holding has no profile and
-- grants no right. It only names the scope of the E0 quota pool: the E0
-- organizations of one holding share one pool, so creating more organizations
-- does not multiply the unverified allowance. An organization at E1 or above
-- keeps its own pool and does not use its holding for quotas.
--
-- A holding belongs to its founder account, the account that created its first
-- organization. Every organization belongs to exactly one holding. Holdings of
-- different founders are never merged.
CREATE TABLE holdings (
-- Internal identifier, never shown by the API. The application creates it
-- as UUIDv7; the backfill below uses a random UUID.
id uuid NOT NULL,
founder_account_id uuid NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT holdings_pkey PRIMARY KEY (id),
-- One holding per founder. A second creation of the same account that
-- races the first waits on this key and then reads the stored holding.
CONSTRAINT holdings_founder_account_id_key UNIQUE (founder_account_id),
CONSTRAINT holdings_founder_account_id_fkey FOREIGN KEY (
founder_account_id
) REFERENCES users (id) ON DELETE RESTRICT
);
-- The backfill and the NOT NULL constraint must see every organization and
-- membership. Writers of both tables wait until this migration commits.
LOCK TABLE organizations, memberships IN SHARE ROW EXCLUSIVE MODE;
-- Refuses an organization without any membership, because its founder cannot
-- be found. Creation stores the owner membership in the same transaction as
-- the organization, and no statement deletes memberships, so an existing
-- database should never reach this check.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM organizations AS organization
WHERE NOT EXISTS (
SELECT 1
FROM memberships AS membership
WHERE membership.organization_id = organization.id
)
) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'organizations_founder_required',
TABLE = 'organizations',
MESSAGE = 'an organization without a membership has no founder for its holding';
END IF;
END;
$$;
-- +goose StatementEnd
ALTER TABLE organizations ADD COLUMN holding_id uuid;
-- The founder of an organization is the account of its earliest membership.
-- Creation inserts the organization and its owner membership in one
-- transaction, and a membership cannot exist before its organization, so the
-- earliest membership is the creator's. Ties are broken by identifier. A holding
-- is dated by the earliest creation of its founder.
WITH founders AS (
SELECT DISTINCT ON (membership.organization_id)
membership.organization_id,
membership.user_id
FROM memberships AS membership
ORDER BY membership.organization_id, membership.created_at, membership.id
)
INSERT INTO holdings (id, founder_account_id, created_at)
SELECT
gen_random_uuid(),
founders.user_id,
min(organization.created_at)
FROM founders
INNER JOIN organizations AS organization ON organization.id = founders.organization_id
GROUP BY founders.user_id;
WITH founders AS (
SELECT DISTINCT ON (membership.organization_id)
membership.organization_id,
membership.user_id
FROM memberships AS membership
ORDER BY membership.organization_id, membership.created_at, membership.id
)
UPDATE organizations AS organization
SET holding_id = holding.id
FROM founders
INNER JOIN holdings AS holding ON holding.founder_account_id = founders.user_id
WHERE founders.organization_id = organization.id;
ALTER TABLE organizations ALTER COLUMN holding_id SET NOT NULL;
ALTER TABLE organizations
ADD CONSTRAINT organizations_holding_id_fkey FOREIGN KEY (holding_id)
REFERENCES holdings (id) ON DELETE RESTRICT;
-- Serves the pool of an E0 organization, which reads the organizations of its
-- holding, and the foreign key.
CREATE INDEX organizations_holding_id_idx ON organizations (holding_id);
-- +goose Down
-- A rollback removes the grouping of organizations into holdings. It refuses
-- while a holding groups several organizations, because the schema without
-- holdings would count their E0 quotas separately and could not keep the pool
-- they share. The lock stops a concurrent creation from joining a holding
-- between the check and the removal.
LOCK TABLE organizations IN SHARE ROW EXCLUSIVE MODE;
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM organizations
GROUP BY holding_id
HAVING count(*) > 1
) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'organizations_holding_grouped',
TABLE = 'organizations',
MESSAGE = 'holdings with several organizations must be resolved before rollback';
END IF;
END;
$$;
-- +goose StatementEnd
ALTER TABLE organizations DROP COLUMN holding_id;
DROP TABLE holdings;
+54 -6
View File
@@ -1,6 +1,8 @@
-- Writers lock the organization first, then invitation/card-view state, and
-- finally usage rows. The organization lock serializes quota decisions for
-- the tenant and makes the subsequent count and insert atomic.
-- Writers lock the organization first, then, for an E0 organization, the holding
-- whose pool it shares, then invitation/card-view state, and finally usage rows.
-- The organization lock serializes quota decisions for the tenant, the holding
-- lock serializes the E0 pool across the organizations of one holding, and
-- together they make the subsequent count and insert atomic.
-- Takes the organization lock ahead of every share lock of a reader that will
-- reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR
@@ -9,9 +11,13 @@
-- FOR KEY SHARE that a foreign key takes, such as the hidden-organization
-- insert of a candidate, which holds the candidate's row and then needs this
-- one. The reservation itself still takes FOR UPDATE inside the same
-- transaction.
-- transaction. The result carries the holding, whose pool an E0 organization
-- shares; the caller locks that holding right after this lock.
-- name: LockCompanyQuotaOrganizationFirst :one
SELECT id
SELECT
id,
verification_level,
holding_id
FROM organizations
WHERE id = sqlc.arg(organization_id)
FOR NO KEY UPDATE;
@@ -21,11 +27,24 @@ SELECT
id,
verification_level,
verification_basis,
verification_changed_at
verification_changed_at,
holding_id
FROM organizations
WHERE id = sqlc.arg(organization_id)
FOR UPDATE;
-- Takes the pool lock of an E0 holding. It follows the organization lock, so
-- every writer locks an organization first and its holding second. Two
-- reservations of one holding queue here, and the second one counts the
-- usage that the first one committed. The lock does not conflict with the
-- FOR KEY SHARE that organizations.holding_id takes when an organization joins
-- the holding.
-- name: LockCompanyQuotaHolding :one
SELECT id
FROM holdings
WHERE id = sqlc.arg(holding_id)
FOR NO KEY UPDATE;
-- name: FindCompanyInvitationQuotaUsage :one
SELECT invitation_id
FROM company_invitation_quota_usage
@@ -43,6 +62,20 @@ WHERE
organization_id = sqlc.arg(organization_id)
AND reserved_at > sqlc.arg(window_start);
-- Counts the invitation usage of the E0 pool of a holding: the usage of every
-- organization of the holding whose trust level is E0 when the count runs. Each
-- row stays attributed to the organization that consumed it.
-- name: CountCompanyInvitationQuotaHoldingWindow :one
SELECT
count(*)::bigint AS usage_count,
min(usage.reserved_at) AS earliest_at
FROM company_invitation_quota_usage AS usage
INNER JOIN organizations AS organization ON organization.id = usage.organization_id
WHERE
organization.holding_id = sqlc.arg(holding_id)
AND organization.verification_level = 'e0'
AND usage.reserved_at > sqlc.arg(window_start);
-- name: InsertCompanyInvitationQuotaUsage :exec
INSERT INTO company_invitation_quota_usage (
organization_id,
@@ -95,6 +128,21 @@ WHERE
organization_id = sqlc.arg(organization_id)
AND last_seen_at > sqlc.arg(window_start);
-- Counts the distinct-card usage of the E0 pool of a holding, with the same
-- rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted
-- per organization: the same candidate seen by two organizations of one
-- holding is two charges.
-- name: CountCompanyCardViewQuotaHoldingWindow :one
SELECT
count(*)::bigint AS usage_count,
min(usage.last_seen_at) AS earliest_at
FROM company_card_view_quota_usage AS usage
INNER JOIN organizations AS organization ON organization.id = usage.organization_id
WHERE
organization.holding_id = sqlc.arg(holding_id)
AND organization.verification_level = 'e0'
AND usage.last_seen_at > sqlc.arg(window_start);
-- name: SaveCompanyCardViewQuotaUsage :exec
INSERT INTO company_card_view_quota_usage (
organization_id,
+45
View File
@@ -0,0 +1,45 @@
-- Store the contact grant of an acceptance. The row is inserted in the same
-- transaction as its C4 consent record and the accepted state; the database
-- checks that the record, the invitation, and the candidate agree.
-- name: InsertContactGrant :exec
INSERT INTO contact_grants (
id,
organization_id,
candidate_id,
source_invitation_id,
consent_record_id,
terms_version,
fields,
consent_text_version,
granted_at
) VALUES (
sqlc.arg(id),
sqlc.arg(organization_id),
sqlc.arg(candidate_id),
sqlc.arg(source_invitation_id),
sqlc.arg(consent_record_id),
sqlc.arg(terms_version),
sqlc.arg(fields)::text [],
sqlc.arg(consent_text_version),
sqlc.arg(granted_at)
);
-- Read the grant of one invitation of one organization. An invitation of
-- another organization finds nothing.
-- name: GetContactGrantByInvitation :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
organization_id = sqlc.arg(organization_id)
AND source_invitation_id = sqlc.arg(invitation_id);
+20
View File
@@ -0,0 +1,20 @@
-- Stores the holding of a founder account unless the account already has one.
-- A concurrent creation of the same account waits on the founder key until the
-- other transaction ends; then this insert does nothing, and the caller reads
-- the stored holding with GetHoldingIDByFounder.
-- name: InsertHoldingIfAbsent :exec
INSERT INTO holdings (
id,
founder_account_id,
created_at
) VALUES (
sqlc.arg(id),
sqlc.arg(founder_account_id),
sqlc.arg(created_at)
)
ON CONFLICT (founder_account_id) DO NOTHING;
-- name: GetHoldingIDByFounder :one
SELECT id
FROM holdings
WHERE founder_account_id = sqlc.arg(founder_account_id);
+39
View File
@@ -127,3 +127,42 @@ SELECT
outcome
FROM invitation_decline_results
WHERE scope_hash = sqlc.arg(scope_hash);
-- The compare-and-swap of an acceptance: it applies only to a delivered or
-- viewed invitation at the version and the terms version that the candidate
-- read, and before its deadline. The answer is the acceptance time, and the
-- deadline is kept.
-- name: AcceptInvitation :one
UPDATE invitations
SET
state = 'accepted',
version = sqlc.arg(next_version),
responded_at = sqlc.arg(accepted_at),
updated_at = sqlc.arg(accepted_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 terms_version = sqlc.arg(terms_version)
AND response_deadline_at > sqlc.arg(accepted_at)
AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1
RETURNING id;
-- name: InsertInvitationAcceptResult :exec
INSERT INTO invitation_accept_results (
scope_hash,
invitation_id,
outcome
) VALUES (
sqlc.arg(scope_hash),
sqlc.arg(invitation_id),
sqlc.arg(outcome)
);
-- name: GetInvitationAcceptResult :one
SELECT
invitation_id,
outcome
FROM invitation_accept_results
WHERE scope_hash = sqlc.arg(scope_hash);
+7 -5
View File
@@ -1,7 +1,7 @@
-- Stores a new organization with the verification level that the domain
-- gave it. The deferred constraint organizations_owner_required fails the
-- transaction at commit unless an active owner membership was inserted in
-- it too.
-- gave it and the holding of its creator. The deferred constraint
-- organizations_owner_required fails the transaction at commit unless an
-- active owner membership was inserted in it too.
-- name: InsertOrganization :exec
INSERT INTO organizations (
id,
@@ -17,7 +17,8 @@ INSERT INTO organizations (
verification_changed_at,
version,
created_at,
updated_at
updated_at,
holding_id
) VALUES (
sqlc.arg(id),
sqlc.arg(name),
@@ -32,7 +33,8 @@ INSERT INTO organizations (
sqlc.arg(verification_changed_at),
sqlc.arg(version),
sqlc.arg(created_at),
sqlc.arg(updated_at)
sqlc.arg(updated_at),
sqlc.arg(holding_id)
);
-- Stores one representative at its position in the list. The adapter calls it
@@ -25,8 +25,8 @@ func TestCandidateCardAccessMigrationDownRetainsHistory(t *testing.T) {
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
rollBackToCandidateCardAccessVersion(ctx, t, migrator)
// The organization is created while the latest schema is in place: its creation
// needs the holdings table, which the rollback below removes.
now := time.Now().UTC().Truncate(time.Microsecond)
identity := identityFixture{
ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now,
@@ -38,6 +38,8 @@ func TestCandidateCardAccessMigrationDownRetainsHistory(t *testing.T) {
}
owner := organizationFixture.employer(t, "owner@example.com")
organization := organizationFixture.create(t, owner, organizationFixture.completeProfile(t, "Example Company"), now)
rollBackToCandidateCardAccessVersion(ctx, t, migrator)
if _, err := pool.Exec(ctx, `INSERT INTO candidate_card_access_events (
id, candidate_id, organization_id, actor_id, kind, field_codes, occurred_at
) VALUES ($1, $2, $3, $4, 'card_viewed', ARRAY['stack']::text[], $5)`,
@@ -416,8 +416,13 @@ func TestCandidatePrivacyStorage(t *testing.T) {
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, `
INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at)
SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1 FROM generate_series(1, $2::int) AS n`, now, limit+1); err != nil {
INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, $2)`, employer.ID, now); err != nil {
t.Fatalf("create holding: %v", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id)
SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1, (SELECT id FROM holdings WHERE founder_account_id = $3)
FROM generate_series(1, $2::int) AS n`, now, limit+1, employer.ID); err != nil {
t.Fatalf("create organizations: %v", err)
}
if _, err := tx.Exec(ctx, `
@@ -696,8 +701,13 @@ func TestCandidatePrivacyStorage(t *testing.T) {
t.Fatalf("begin: %v", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at)
SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1 FROM generate_series(1, $2::int) AS n`, now, limit-1+parallel); err != nil {
INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, $2)`, employer.ID, now); err != nil {
t.Fatalf("create holding: %v", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id)
SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1, (SELECT id FROM holdings WHERE founder_account_id = $3)
FROM generate_series(1, $2::int) AS n`, now, limit-1+parallel, employer.ID); err != nil {
t.Fatalf("create organizations: %v", err)
}
if _, err := tx.Exec(ctx, `
+26 -7
View File
@@ -38,11 +38,10 @@ type companyQuotaFixture struct {
invitationCandidate uuid.UUID
}
func TestCompanyQuota(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
// newCompanyQuotaFixture migrates the isolated database, publishes the demo
// product policy, and returns the fixture the quota tests share.
func newCompanyQuotaFixture(ctx context.Context, t *testing.T, databaseURL string) companyQuotaFixture {
t.Helper()
applyMigrations(ctx, t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
@@ -60,13 +59,20 @@ func TestCompanyQuota(t *testing.T) {
if err != nil {
t.Fatalf("GetEffective(product) error = %v", err)
}
fixture := companyQuotaFixture{
return companyQuotaFixture{
ctx: ctx, pool: pool, clock: clock, transactor: transactor,
service: companyquota.NewService(clock.Now), organizations: organizationFixture,
policies: policyStore.Policies(), version: version,
invitationAuthor: organizationFixture.employer(t, "quota-invitation-author@example.test").ID,
invitationCandidate: identity.createUser(t, "quota-invitation-candidate@example.test", domain.ScenarioCandidate, clock.Now().Add(-time.Hour)).ID,
}
}
func TestCompanyQuota(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout)
defer cancel()
fixture := newCompanyQuotaFixture(ctx, t, env.createIsolatedDatabase(ctx, t))
t.Run("E0 shares limits across requests and concurrent final reservations", func(t *testing.T) {
organization, _ := fixture.newOrganization(t, "e0-boundary", domain.OrganizationVerificationE0)
@@ -381,6 +387,19 @@ func (fixture companyQuotaFixture) newOrganization(
) (domain.Organization, domain.User) {
t.Helper()
owner := fixture.organizations.employer(t, fmt.Sprintf("quota-%s-%s@example.test", name, uuid.NewString()))
return fixture.organizationOf(t, owner, name, level), owner
}
// organizationOf stores an organization of owner at the given verification
// level and returns it as read back from storage. Several organizations of one
// owner belong to one holding.
func (fixture companyQuotaFixture) organizationOf(
t *testing.T,
owner domain.User,
name string,
level domain.OrganizationVerificationLevel,
) domain.Organization {
t.Helper()
organization := fixture.organizations.create(t, owner, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Quota " + name}), fixture.clock.Now().Add(-time.Minute))
if level != domain.OrganizationVerificationE0 {
basis := domain.OrganizationBasisCorporateDomain
@@ -401,7 +420,7 @@ func (fixture companyQuotaFixture) newOrganization(
if err != nil {
t.Fatalf("read %s organization: %v", level, err)
}
return stored, owner
return stored
}
// newInvitationID stores a draft of the organization and returns its
@@ -0,0 +1,193 @@
//go:build integration
package integration_test
import (
"context"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
)
// holdingsMigrationVersion creates the holdings table and organizations.holding_id.
const holdingsMigrationVersion = 41
// legacyMembership is a membership row written without the application.
type legacyMembership struct {
userID uuid.UUID
role string
createdAt time.Time
}
// TestHoldingsMigrationBackfillsFoundersAndGuardsRollback runs the migration on
// organizations that were created before holdings existed. The backfill must
// give one holding per founder, and the rollback must refuse while a holding
// groups several organizations.
func TestHoldingsMigrationBackfillsFoundersAndGuardsRollback(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)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
// The schema before holdings: the organizations are written without them.
rollBackAboveMigration(ctx, t, migrator, holdingsMigrationVersion-1)
now := time.Now().UTC().Truncate(time.Microsecond).Add(-24 * time.Hour)
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
founderA := identity.createUser(t, "holding-backfill-first@example.test", domain.ScenarioEmployer, now.Add(-time.Hour))
founderB := identity.createUser(t, "holding-backfill-other@example.test", domain.ScenarioEmployer, now.Add(-time.Hour))
cofounder := identity.createUser(t, "holding-backfill-cofounder@example.test", domain.ScenarioEmployer, now.Add(-time.Hour))
first := insertLegacyOrganization(ctx, t, pool, "Legacy first", now,
legacyMembership{userID: founderA.ID, role: "owner", createdAt: now})
second := insertLegacyOrganization(ctx, t, pool, "Legacy second", now.Add(time.Hour),
legacyMembership{userID: founderA.ID, role: "owner", createdAt: now.Add(time.Hour)},
// A later owner does not change the founder: the earliest membership does.
legacyMembership{userID: cofounder.ID, role: "owner", createdAt: now.Add(2 * time.Hour)})
other := insertLegacyOrganization(ctx, t, pool, "Legacy other", now.Add(30*time.Minute),
legacyMembership{userID: founderB.ID, role: "owner", createdAt: now.Add(30 * time.Minute)})
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() with the holdings migration error = %v", err)
}
t.Run("backfill gives each founder one holding dated by its first organization", func(t *testing.T) {
firstHolding := legacyHolding(ctx, t, pool, first)
if got := legacyHolding(ctx, t, pool, second); got != firstHolding {
t.Fatalf("holding of the second organization = %s, want the founder's holding %s", got, firstHolding)
}
if got := legacyHolding(ctx, t, pool, other); got == firstHolding {
t.Fatal("two founders share one holding")
}
assertLegacyHoldingFounder(ctx, t, pool, firstHolding, founderA.ID, now)
assertLegacyHoldingFounder(ctx, t, pool, legacyHolding(ctx, t, pool, other), founderB.ID, now.Add(30*time.Minute))
var count int64
if err := pool.QueryRow(ctx, `SELECT count(*) FROM holdings`).Scan(&count); err != nil {
t.Fatalf("count holdings: %v", err)
}
if count != 2 {
t.Fatalf("holdings = %d, want one per founder (2)", count)
}
})
t.Run("rollback refuses while a holding groups several organizations", func(t *testing.T) {
_, err := migrator.DownOne(ctx)
assertPgError(t, "DownOne() with a grouped holding", err, privacyIntegrityViolation, "organizations_holding_grouped")
if got := legacyHolding(ctx, t, pool, first); got != legacyHolding(ctx, t, pool, second) {
t.Fatal("refused rollback changed the grouping")
}
})
t.Run("rollback succeeds once every holding has one organization", func(t *testing.T) {
split := uuid.Must(uuid.NewV7())
if _, err := pool.Exec(ctx, `
INSERT INTO holdings (id, founder_account_id, created_at) VALUES ($1, $2, $3)`,
split, cofounder.ID, now); err != nil {
t.Fatalf("insert the holding of the split organization: %v", err)
}
if _, err := pool.Exec(ctx, `UPDATE organizations SET holding_id = $2 WHERE id = $1`, second, split); err != nil {
t.Fatalf("move the second organization to its own holding: %v", err)
}
if _, err := migrator.DownOne(ctx); err != nil {
t.Fatalf("DownOne() with single-organization holdings error = %v", err)
}
var holdingsGone, columnGone bool
var organizations int64
if err := pool.QueryRow(ctx, `
SELECT
to_regclass('public.holdings') IS NULL,
NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'organizations' AND column_name = 'holding_id'),
(SELECT count(*) FROM organizations)`).Scan(&holdingsGone, &columnGone, &organizations); err != nil {
t.Fatalf("read the rolled-back schema: %v", err)
}
if !holdingsGone || !columnGone {
t.Fatalf("rollback left holdings table gone = %t, holding_id column gone = %t", holdingsGone, columnGone)
}
if organizations != 3 {
t.Fatalf("organizations after rollback = %d, want the 3 that were created", organizations)
}
// Applying the migration again backfills the same grouping from the
// memberships, so the founders get one holding each.
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() after the rollback error = %v", err)
}
if got := legacyHolding(ctx, t, pool, second); got != legacyHolding(ctx, t, pool, first) {
t.Fatal("reapplied backfill does not group the founder's organizations")
}
})
}
// insertLegacyOrganization stores an organization and its memberships in one
// transaction, as creation did before holdings. The owner membership keeps the
// deferred constraint satisfied at commit.
func insertLegacyOrganization(
ctx context.Context,
t *testing.T,
pool *pgxpool.Pool,
name string,
createdAt time.Time,
memberships ...legacyMembership,
) uuid.UUID {
t.Helper()
organizationID := uuid.Must(uuid.NewV7())
tx, err := pool.Begin(ctx)
if err != nil {
t.Fatalf("begin legacy organization transaction: %v", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, `
INSERT INTO organizations (
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at
) VALUES ($1, $2, 'e0', 'confirmed_email', $3, 1, $3, $3)`, organizationID, name, createdAt); err != nil {
t.Fatalf("insert legacy organization: %v", err)
}
for _, membership := range memberships {
if _, err := tx.Exec(ctx, `
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
VALUES ($1, $2, $3, $4, 'active', $5, $5)`,
uuid.Must(uuid.NewV7()), organizationID, membership.userID, membership.role, membership.createdAt); err != nil {
t.Fatalf("insert legacy membership: %v", err)
}
}
if err := tx.Commit(ctx); err != nil {
t.Fatalf("commit legacy organization: %v", err)
}
return organizationID
}
func legacyHolding(ctx context.Context, t *testing.T, pool *pgxpool.Pool, organizationID uuid.UUID) uuid.UUID {
t.Helper()
var holdingID uuid.UUID
if err := pool.QueryRow(ctx, `SELECT holding_id FROM organizations WHERE id = $1`, organizationID).Scan(&holdingID); err != nil {
t.Fatalf("read holding of organization: %v", err)
}
return holdingID
}
func assertLegacyHoldingFounder(ctx context.Context, t *testing.T, pool *pgxpool.Pool, holdingID, founderID uuid.UUID, createdAt time.Time) {
t.Helper()
var gotFounder uuid.UUID
var gotCreatedAt time.Time
if err := pool.QueryRow(ctx, `
SELECT founder_account_id, created_at FROM holdings WHERE id = $1`, holdingID).Scan(&gotFounder, &gotCreatedAt); err != nil {
t.Fatalf("read holding: %v", err)
}
if gotFounder != founderID {
t.Fatalf("holding founder = %s, want %s", gotFounder, founderID)
}
if !gotCreatedAt.Equal(createdAt) {
t.Fatalf("holding created_at = %s, want %s", gotCreatedAt, createdAt)
}
}
+418
View File
@@ -0,0 +1,418 @@
//go:build integration
package integration_test
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// holdingConcurrentConns sizes the pool of the concurrency subtests, so that
// every goroutine of one subtest holds a connection at the same time.
const holdingConcurrentConns = 8
// TestHoldings covers the E0 quota pools that the organizations of one holding
// share, the isolation of accounts, and the creation of holdings.
func TestHoldings(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
fixture := newCompanyQuotaFixture(ctx, t, databaseURL)
t.Run("organizations of one account share the E0 pools and keep the E1 pools apart", func(t *testing.T) {
owner := fixture.organizations.employer(t, uniqueHoldingEmail("shared-owner"))
first := fixture.organizationOf(t, owner, "shared-first", domain.OrganizationVerificationE0)
second := fixture.organizationOf(t, owner, "shared-second", domain.OrganizationVerificationE0)
verified := fixture.organizationOf(t, owner, "shared-verified", domain.OrganizationVerificationE1)
fixture.assertSameHolding(t, owner.ID, first.ID(), second.ID(), verified.ID())
// The verified organization draws on its own pool, and its usage does
// not count toward the E0 pool that follows.
for range 3 {
fixture.reserveInvitationAllowed(t, verified, fixture.newInvitationID(t, verified))
fixture.reserveCardViewAllowed(t, verified, fixture.newCandidateID(t))
}
for range 6 {
fixture.reserveInvitationAllowed(t, first, fixture.newInvitationID(t, first))
}
for range 4 {
fixture.reserveInvitationAllowed(t, second, fixture.newInvitationID(t, second))
}
fixture.assertInvitationDenied(t, first, fixture.clock.Now().Add(7*24*time.Hour))
fixture.assertInvitationDenied(t, second, fixture.clock.Now().Add(7*24*time.Hour))
fixture.assertQuotaRowCounts(t, first.ID(), 6, 0)
fixture.assertQuotaRowCounts(t, second.ID(), 4, 0)
fixture.assertQuotaRowCounts(t, verified.ID(), 3, 3)
for range 30 {
fixture.reserveCardViewAllowed(t, first, fixture.newCandidateID(t))
}
for range 20 {
fixture.reserveCardViewAllowed(t, second, fixture.newCandidateID(t))
}
fixture.assertCardViewDenied(t, first, fixture.clock.Now().Add(24*time.Hour))
fixture.assertCardViewDenied(t, second, fixture.clock.Now().Add(24*time.Hour))
fixture.assertQuotaRowCounts(t, first.ID(), 6, 30)
fixture.assertQuotaRowCounts(t, second.ID(), 4, 20)
// The verified organization keeps its own pool: it still has room.
fixture.reserveInvitationAllowed(t, verified, fixture.newInvitationID(t, verified))
fixture.reserveCardViewAllowed(t, verified, fixture.newCandidateID(t))
})
t.Run("a second account forms its own holding and pool", func(t *testing.T) {
owner := fixture.organizations.employer(t, uniqueHoldingEmail("other-owner"))
other := fixture.organizationOf(t, owner, "other-first", domain.OrganizationVerificationE0)
for range 10 {
fixture.reserveInvitationAllowed(t, other, fixture.newInvitationID(t, other))
}
fixture.assertInvitationDenied(t, other, fixture.clock.Now().Add(7*24*time.Hour))
neighbour := fixture.organizations.employer(t, uniqueHoldingEmail("neighbour-owner"))
separate := fixture.organizationOf(t, neighbour, "neighbour-first", domain.OrganizationVerificationE0)
if fixture.holdingOf(t, separate.ID()) == fixture.holdingOf(t, other.ID()) {
t.Fatal("organizations of two accounts share one holding")
}
fixture.reserveInvitationAllowed(t, separate, fixture.newInvitationID(t, separate))
fixture.reserveCardViewAllowed(t, separate, fixture.newCandidateID(t))
})
t.Run("usage leaves the E0 pool with its organization", func(t *testing.T) {
owner := fixture.organizations.employer(t, uniqueHoldingEmail("leave-owner"))
raised := fixture.organizationOf(t, owner, "leave-raised", domain.OrganizationVerificationE0)
sibling := fixture.organizationOf(t, owner, "leave-sibling", domain.OrganizationVerificationE0)
for range 6 {
fixture.reserveInvitationAllowed(t, raised, fixture.newInvitationID(t, raised))
}
if _, err := fixture.pool.Exec(fixture.ctx, `
UPDATE organizations
SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2
WHERE id = $1`, raised.ID(), fixture.clock.Now().Add(-30*time.Second)); err != nil {
t.Fatalf("raise organization to E1: %v", err)
}
raisedNow, _, err := fixture.organizations.read(owner.ID, raised.ID())
if err != nil {
t.Fatalf("read raised organization: %v", err)
}
// The six invitations stay stored, but they no longer count toward the
// E0 pool, which the sibling can use in full.
for range 10 {
fixture.reserveInvitationAllowed(t, sibling, fixture.newInvitationID(t, sibling))
}
fixture.assertInvitationDenied(t, sibling, fixture.clock.Now().Add(7*24*time.Hour))
fixture.assertQuotaRowCounts(t, raised.ID(), 6, 0)
fixture.reserveInvitationAllowed(t, raisedNow, fixture.newInvitationID(t, raisedNow))
})
t.Run("concurrent reservations of one E0 pool never exceed its limits", func(t *testing.T) {
owner := fixture.organizations.employer(t, uniqueHoldingEmail("race-owner"))
first := fixture.organizationOf(t, owner, "race-first", domain.OrganizationVerificationE0)
second := fixture.organizationOf(t, owner, "race-second", domain.OrganizationVerificationE0)
concurrent := newConcurrentTransactor(ctx, t, databaseURL)
for range 5 {
fixture.reserveInvitationAllowed(t, first, fixture.newInvitationID(t, first))
}
for range 4 {
fixture.reserveInvitationAllowed(t, second, fixture.newInvitationID(t, second))
}
// Nine of the ten invitations are used. Four reservations race for the
// last place, two from each organization.
racers := []domain.Organization{first, second, first, second}
invitationIDs := make([]uuid.UUID, len(racers))
for index, organization := range racers {
invitationIDs[index] = fixture.newInvitationID(t, organization)
}
decisions := make([]outbound.CompanyQuotaDecision, len(racers))
runConcurrently(t, len(racers), func(index int) error {
decision, err := fixture.reserveInvitationLocked(concurrent, racers[index], invitationIDs[index])
decisions[index] = decision
return err
})
fixture.assertOneAllowed(t, decisions, fixture.clock.Now().Add(7*24*time.Hour))
fixture.assertInvitationRowsOf(t, 10, first.ID(), second.ID())
viewCandidates := make([]uuid.UUID, 0, 49)
for range 49 {
viewCandidates = append(viewCandidates, fixture.newCandidateID(t))
}
for index, candidateID := range viewCandidates {
organization := first
if index%2 == 1 {
organization = second
}
fixture.reserveCardViewAllowed(t, organization, candidateID)
}
viewRacers := make([]uuid.UUID, len(racers))
for index := range racers {
viewRacers[index] = fixture.newCandidateID(t)
}
viewDecisions := make([]outbound.CompanyQuotaDecision, len(racers))
runConcurrently(t, len(racers), func(index int) error {
decision, err := fixture.reserveCardViewLocked(concurrent, racers[index], viewRacers[index])
viewDecisions[index] = decision
return err
})
fixture.assertOneAllowed(t, viewDecisions, fixture.clock.Now().Add(24*time.Hour))
fixture.assertCardViewRowsOf(t, 50, first.ID(), second.ID())
})
t.Run("concurrent creations by one account end in one holding", func(t *testing.T) {
owner := fixture.organizations.employer(t, uniqueHoldingEmail("create-owner"))
concurrent := newConcurrentTransactor(ctx, t, databaseURL)
const creations = holdingConcurrentConns
at := fixture.clock.Now().Add(-time.Minute)
organizationIDs := make([]uuid.UUID, creations)
runConcurrently(t, creations, func(index int) error {
profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{Name: fmt.Sprintf("Concurrent company %d", index)})
if err != nil {
return fmt.Errorf("profile: %w", err)
}
company, err := domain.NewOrganization(profile, at)
if err != nil {
return fmt.Errorf("organization: %w", err)
}
membership, err := domain.NewOwnerMembership(company.ID(), owner.ID, at)
if err != nil {
return fmt.Errorf("owner membership: %w", err)
}
organizationIDs[index] = company.ID()
return concurrent.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Organizations().CreateWithOwner(ctx, company, membership)
})
})
fixture.assertSameHolding(t, owner.ID, organizationIDs...)
if got := fixture.holdingCount(t, owner.ID); got != 1 {
t.Fatalf("holdings of the founder = %d, want 1", got)
}
})
t.Run("an unknown founder stores no holding", func(t *testing.T) {
before := fixture.totalHoldings(t)
unknown := uuid.New()
profile := mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Orphan company"})
company, err := domain.NewOrganization(profile, fixture.clock.Now().Add(-time.Minute))
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
membership, err := domain.NewOwnerMembership(company.ID(), unknown, company.CreatedAt())
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Organizations().CreateWithOwner(ctx, company, membership)
})
if !errors.Is(err, outbound.ErrUserNotFound) {
t.Fatalf("CreateWithOwner(unknown founder) error = %v, want ErrUserNotFound", err)
}
if after := fixture.totalHoldings(t); after != before {
t.Fatalf("holdings = %d after the refused creation, want %d", after, before)
}
})
}
// uniqueHoldingEmail returns a fresh address so that every subtest creates its
// own account and therefore its own holding.
func uniqueHoldingEmail(prefix string) string {
return fmt.Sprintf("holding-%s-%s@example.test", prefix, uuid.NewString())
}
// newConcurrentTransactor opens a pool of the isolated database that lets every
// goroutine of a subtest run its transaction at the same time.
func newConcurrentTransactor(ctx context.Context, t *testing.T, databaseURL string) *postgresadapter.Transactor {
t.Helper()
poolConfig, err := pgxpool.ParseConfig(databaseURL)
if err != nil {
t.Fatalf("parse isolated database URL: %v", err)
}
poolConfig.MaxConns = holdingConcurrentConns
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
t.Fatalf("create concurrent PostgreSQL pool: %v", err)
}
t.Cleanup(pool.Close)
return postgresadapter.NewTransactor(pool)
}
// runConcurrently calls work for every index at once, after all goroutines
// have started, and fails the test on the first error. work must not call
// testing methods that stop the test goroutine.
func runConcurrently(t *testing.T, count int, work func(index int) error) {
t.Helper()
errs := make([]error, count)
start := make(chan struct{})
done := make(chan struct{}, count)
for index := range count {
go func() {
defer func() { done <- struct{}{} }()
<-start
errs[index] = work(index)
}()
}
close(start)
for range count {
<-done
}
for index, err := range errs {
if err != nil {
t.Fatalf("concurrent call %d error = %v", index, err)
}
}
}
// reserveInvitationLocked reserves one invitation the way the production
// callers do: the organization lock first, then the reservation, in one
// transaction.
func (fixture companyQuotaFixture) reserveInvitationLocked(
transactor *postgresadapter.Transactor,
organization domain.Organization,
invitationID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
var decision outbound.CompanyQuotaDecision
err := transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.CompanyQuotas().LockOrganization(ctx, organization.ID()); err != nil {
return err
}
var err error
decision, err = fixture.service.ReserveInvitation(ctx, unit, organization, invitationID)
return err
})
return decision, err
}
// reserveCardViewLocked is reserveInvitationLocked for a distinct card view.
func (fixture companyQuotaFixture) reserveCardViewLocked(
transactor *postgresadapter.Transactor,
organization domain.Organization,
candidateID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
var decision outbound.CompanyQuotaDecision
err := transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.CompanyQuotas().LockOrganization(ctx, organization.ID()); err != nil {
return err
}
var err error
decision, err = fixture.service.ReserveCardView(ctx, unit, organization, candidateID)
return err
})
return decision, err
}
// assertSameHolding checks that every organization is in the holding of the
// owner and that the owner has exactly one holding.
func (fixture companyQuotaFixture) assertSameHolding(t *testing.T, founderID uuid.UUID, organizationIDs ...uuid.UUID) {
t.Helper()
if got := fixture.holdingCount(t, founderID); got != 1 {
t.Fatalf("holdings of the founder = %d, want 1", got)
}
want := fixture.holdingOf(t, organizationIDs[0])
for _, organizationID := range organizationIDs {
if got := fixture.holdingOf(t, organizationID); got != want {
t.Fatalf("organization %s is in holding %s, want %s", organizationID, got, want)
}
}
}
func (fixture companyQuotaFixture) holdingOf(t *testing.T, organizationID uuid.UUID) uuid.UUID {
t.Helper()
var holdingID uuid.UUID
if err := fixture.pool.QueryRow(fixture.ctx, `SELECT holding_id FROM organizations WHERE id = $1`, organizationID).Scan(&holdingID); err != nil {
t.Fatalf("read holding of organization: %v", err)
}
return holdingID
}
func (fixture companyQuotaFixture) holdingCount(t *testing.T, founderID uuid.UUID) int64 {
t.Helper()
var count int64
if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM holdings WHERE founder_account_id = $1`, founderID).Scan(&count); err != nil {
t.Fatalf("count holdings of founder: %v", err)
}
return count
}
func (fixture companyQuotaFixture) totalHoldings(t *testing.T) int64 {
t.Helper()
var count int64
if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM holdings`).Scan(&count); err != nil {
t.Fatalf("count holdings: %v", err)
}
return count
}
// assertInvitationDenied checks that the organization cannot reserve a new
// invitation and that the denial retries at retryAt.
func (fixture companyQuotaFixture) assertInvitationDenied(t *testing.T, organization domain.Organization, retryAt time.Time) {
t.Helper()
decision, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization))
if err != nil || decision.Allowed || !decision.RetryAt.Equal(retryAt) {
t.Fatalf("ReserveInvitation() = %+v, %v; want a denial that retries at %s", decision, err, retryAt)
}
}
// assertCardViewDenied is assertInvitationDenied for a distinct card view.
func (fixture companyQuotaFixture) assertCardViewDenied(t *testing.T, organization domain.Organization, retryAt time.Time) {
t.Helper()
decision, err := fixture.reserveCardView(organization, fixture.newCandidateID(t))
if err != nil || decision.Allowed || !decision.RetryAt.Equal(retryAt) {
t.Fatalf("ReserveCardView() = %+v, %v; want a denial that retries at %s", decision, err, retryAt)
}
}
// assertOneAllowed checks that exactly one of the decisions was allowed and
// that the others were denied with the given retry time.
func (fixture companyQuotaFixture) assertOneAllowed(t *testing.T, decisions []outbound.CompanyQuotaDecision, retryAt time.Time) {
t.Helper()
allowed := 0
for _, decision := range decisions {
switch {
case decision.Allowed && decision.RetryAt.IsZero() && !decision.Reused:
allowed++
case !decision.Allowed && decision.RetryAt.Equal(retryAt):
default:
t.Fatalf("unexpected concurrent decision %+v, want retry at %s", decision, retryAt)
}
}
if allowed != 1 {
t.Fatalf("allowed concurrent reservations = %d, want exactly 1 of %d", allowed, len(decisions))
}
}
// assertInvitationRowsOf checks the invitation usage stored for the given
// organizations together, which is the count of the shared pool.
func (fixture companyQuotaFixture) assertInvitationRowsOf(t *testing.T, want int64, organizationIDs ...uuid.UUID) {
t.Helper()
var got int64
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = ANY($1)`, organizationIDs).Scan(&got); err != nil {
t.Fatalf("count invitation usage rows: %v", err)
}
if got != want {
t.Fatalf("invitation usage rows of the pool = %d, want %d", got, want)
}
}
// assertCardViewRowsOf is assertInvitationRowsOf for distinct card views.
func (fixture companyQuotaFixture) assertCardViewRowsOf(t *testing.T, want int64, organizationIDs ...uuid.UUID) {
t.Helper()
var got int64
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = ANY($1)`, organizationIDs).Scan(&got); err != nil {
t.Fatalf("count card-view usage rows: %v", err)
}
if got != want {
t.Fatalf("card-view usage rows of the pool = %d, want %d", got, want)
}
}
@@ -0,0 +1,579 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"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/port/outbound"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/policy"
)
const (
// invitationAcceptMigrationVersion adds the acceptance: its audit event, the
// contact grant, and the outcomes kept under the keys.
invitationAcceptMigrationVersion = 40
invitationAcceptancesRetained = "invitation_acceptances_retained"
acceptTextVersion = "c4-2026-10-01"
)
// candidateContactGrantHTTP is the contact grant as the candidate reads it.
type candidateContactGrantHTTP struct {
ID uuid.UUID `json:"id"`
Fields []string `json:"fields"`
Status string `json:"status"`
Readable bool `json:"readable"`
BlockedBy *string `json:"blocked_by"`
TermsVersion int64 `json:"terms_version"`
ConsentTextVersion string `json:"consent_text_version"`
GrantedAt string `json:"granted_at"`
RevokedAt *string `json:"revoked_at"`
RevocationReason *string `json:"revocation_reason"`
}
func decodeContactGrantHTTP(t *testing.T, body candidateInvitationHTTPBody) candidateContactGrantHTTP {
t.Helper()
var grant candidateContactGrantHTTP
if err := json.Unmarshal(body.ContactGrant, &grant); err != nil {
t.Fatalf("decode contact grant %s: %v", body.ContactGrant, err)
}
return grant
}
// invitationAcceptCounts are the rows that acceptances write for one
// invitation, the C4 consents of its candidate, and the outcomes kept under
// the keys.
type invitationAcceptCounts struct {
acceptedEvents, grants, c4Consents, outcomes int
}
func readInvitationAcceptCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationAcceptCounts {
t.Helper()
var counts invitationAcceptCounts
if err := harness.pool.QueryRow(ctx, `
SELECT
(SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'accepted'),
(SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1),
(SELECT count(*) FROM consent_records WHERE subject_id = $2 AND purpose = 'c4'),
(SELECT count(*) FROM invitation_accept_results WHERE invitation_id = $1)`,
invitationID, candidateID).Scan(&counts.acceptedEvents, &counts.grants, &counts.c4Consents, &counts.outcomes); err != nil {
t.Fatalf("count the rows of an acceptance: %v", err)
}
return counts
}
// parallelAcceptRequests sends every acceptance at once, each under its own
// key, and returns the responses in the order of the bodies.
func parallelAcceptRequests(
t *testing.T,
harness *invitationHTTPHarness,
path, origin string,
session organizationHTTPSession,
bodies, keys []string,
) []*httptest.ResponseRecorder {
t.Helper()
responses := make([]*httptest.ResponseRecorder, len(bodies))
var group sync.WaitGroup
start := make(chan struct{})
for index := range bodies {
group.Go(func() {
<-start
responses[index] = organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, path, bodies[index], origin, session, keys[index])
})
}
close(start)
group.Wait()
return responses
}
// firstAcceptance is the acceptance that later cases of the test repeat.
type firstAcceptance struct {
candidate domain.User
invitation invitationHTTPBody
key string
body string
}
func TestCandidateInvitationAcceptOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout)
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)
}
owner := account("accept-owner@example.test", domain.ScenarioEmployer)
sessionOwner := loginOrganizationHTTP(t, harness.sessionHTTPHarness, owner.Email.Address())
orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwner, "accept-company")
var nameA string
if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, orgA).Scan(&nameA); err != nil {
t.Fatalf("read organization name: %v", err)
}
identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now}
privacy := candidatePrivacyFixture{
ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture,
organizations: organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture, transactor: postgresadapter.NewTransactor(harness.pool), now: now},
ledger: postgresadapter.NewConsentStore(harness.pool), now: now,
}
profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: privacy.queries, identity: identityFixture, now: now}
// Every candidate publishes the card and holds a name, an email, and a phone
// number. Telegram is held by none of them.
publishCandidate := func(candidate domain.User) {
consent := privacy.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now)
privacy.publish(t, candidate.ID, consent.ID(), 0,
domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience,
domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility)
profiles.save(t, candidate.ID, domain.CandidateProfileInput{
FullName: confirmedDecision(invitationCandidateName), Email: confirmedDecision(invitationCandidateContact),
Phone: confirmedDecision("+70000000000"),
Stack: privacyCohortConfirmedItems("go"),
Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}),
Experience: privacyCohortConfirmedItems(domain.ProfileExperience{
EmployerName: invitationCandidateMarker, Specialization: domain.SpecializationBackend,
StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private summary",
}),
SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 777_000, TaxBasis: domain.ProfileTaxNet}),
}, 0)
if _, err := privacy.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{
UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now),
}); err != nil {
t.Fatalf("InsertCandidateQuestionnaire() error = %v", err)
}
}
// Seven published candidates form the visible cohort. Each case uses its own
// candidate, so the cases do not share the state of an invitation.
var candidates []domain.User
for index := range 7 {
candidate := account(fmt.Sprintf("accept-candidate-%d@example.test", index), domain.ScenarioCandidate)
candidates = append(candidates, candidate)
publishCandidate(candidate)
}
login := func(candidate domain.User) organizationHTTPSession {
return loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address())
}
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)
}
var keySequence int
nextKey := func() string {
keySequence++
return fmt.Sprintf("invitation-accept-key-%d", keySequence)
}
deliver := func(candidate domain.User) invitationHTTPBody {
t.Helper()
handle, err := harness.key.ForOrganization(orgA, candidate.ID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
draft := decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", orgA),
invitationCreateJSON(t, handle, nil), sessionOwner, nextKey()), http.StatusCreated)
return decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/send", orgA, draft.ID),
fmt.Sprintf(`{"expected_version":%d}`, draft.Version), sessionOwner, nextKey()), http.StatusOK)
}
myPath := func(invitationID uuid.UUID) string { return "/api/v1/me/invitations/" + invitationID.String() }
acceptBody := func(version, terms int64, text string, fields ...string) string {
encoded, err := json.Marshal(map[string]any{
"expected_version": version, "terms_version": terms,
"consent_c4": map[string]any{"text_version": text, "accepted": true, "fields": fields},
})
if err != nil {
t.Fatalf("marshal acceptance: %v", err)
}
return string(encoded)
}
accept := func(candidate domain.User, invitationID uuid.UUID, body, key string) *httptest.ResponseRecorder {
t.Helper()
return request(http.MethodPost, myPath(invitationID)+"/accept", body, login(candidate), key)
}
// raiseTerms stores the next terms version the way a later raise does, with
// a higher salary, and advances the invitation version by one.
raiseTerms := func(invitationID uuid.UUID) int64 {
t.Helper()
if _, err := harness.pool.Exec(ctx, `
INSERT INTO invitation_terms_versions (invitation_id, organization_id, version, terms, salary_from, salary_to,
salary_currency, salary_period, salary_tax_basis, created_at)
SELECT invitation_id, organization_id, 2,
jsonb_set(jsonb_set(terms, '{salary,salary_from}', '120000'::jsonb), '{salary,salary_to}', '160000'::jsonb),
120000, 160000, salary_currency, salary_period, salary_tax_basis, $2
FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, invitationID, harness.clock.Now()); err != nil {
t.Fatalf("store the raised terms: %v", err)
}
var version int64
if err := harness.pool.QueryRow(ctx, `
UPDATE invitations SET terms_version = 2, version = version + 1, updated_at = $2
WHERE id = $1 RETURNING version`, invitationID, harness.clock.Now()).Scan(&version); err != nil {
t.Fatalf("raise the invitation: %v", err)
}
return version
}
candidateMarkers := []string{invitationCandidateName, invitationCandidateContact, invitationCandidateMarker}
for _, candidate := range candidates {
candidateMarkers = append(candidateMarkers, candidate.ID.String(), candidate.Email.Address())
}
requireNoCandidateData := func(label, text string) {
t.Helper()
for _, marker := range candidateMarkers {
if strings.Contains(text, marker) {
t.Errorf("%s contains the private marker %q: %s", label, marker, text)
}
}
for _, field := range []string{"candidate_id", "candidate_handle", "salary_fit", "salary_minimum", "full_name", "telegram", "email", "phone"} {
if strings.Contains(text, `"`+field+`":`) {
t.Errorf("%s contains the key %q: %s", label, field, text)
}
}
}
var first firstAcceptance
t.Run("an email-only acceptance stores one grant of that field and one consent", func(t *testing.T) {
candidate := candidates[0]
sent := deliver(candidate)
key := nextKey()
body := acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email")
response := accept(candidate, sent.ID, body, key)
accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK)
requireNoCandidateData("accept response", response.Body.String())
grant := decodeContactGrantHTTP(t, accepted)
if accepted.State != "accepted" || accepted.Version != sent.Version+1 || accepted.TermsVersion != sent.TermsVersion ||
accepted.RespondedAt == nil || accepted.Decline != nil || string(accepted.ContactConsent) != "null" ||
accepted.ResponseDeadlineAt != *sent.ResponseDeadlineAt || accepted.Organization.Name != nameA {
t.Fatalf("accepted = %+v, want the accepted invitation with its deadline and no offer", accepted)
}
if !slices.Equal(grant.Fields, []string{"email"}) || grant.Status != "active" || grant.ConsentTextVersion != acceptTextVersion ||
grant.TermsVersion != sent.TermsVersion || grant.RevokedAt != nil || grant.RevocationReason != nil {
t.Fatalf("grant = %+v, want the email only, active, under the current text", grant)
}
// The published profile is not hidden, so the grant is readable now.
if !grant.Readable || grant.BlockedBy != nil {
t.Fatalf("grant = %+v, want readable while the organization may read the profile", grant)
}
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 1}) {
t.Fatalf("acceptance stored %+v, want one event, one grant, one C4 consent, and one outcome", counts)
}
// The grant names the one selected kind, although the profile holds the
// phone number too, and the consent names the same kind.
var fields, consentFields []string
if err := harness.pool.QueryRow(ctx, `
SELECT grant_row.fields, record.field_set
FROM contact_grants AS grant_row
JOIN consent_records AS record ON record.id = grant_row.consent_record_id
WHERE grant_row.source_invitation_id = $1`, sent.ID).Scan(&fields, &consentFields); err != nil {
t.Fatalf("read the grant and its consent: %v", err)
}
if !slices.Equal(fields, []string{"email"}) || !slices.Equal(consentFields, []string{"email"}) {
t.Fatalf("stored grant fields = %v and consent fields = %v, want the email only", fields, consentFields)
}
reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK)
if decodeContactGrantHTTP(t, reread).ID != grant.ID || reread.Version != accepted.Version {
t.Fatalf("reread = %+v, want the same grant and version", reread)
}
first = firstAcceptance{candidate: candidate, invitation: sent, key: key, body: body}
})
t.Run("repeats replay the answer and a different choice is a state conflict", func(t *testing.T) {
if first.invitation.ID == uuid.Nil {
t.Fatal("the first acceptance did not run")
}
original := accept(first.candidate, first.invitation.ID, first.body, first.key)
if original.Code != http.StatusOK {
t.Fatalf("replay = %d %s, want the original 200", original.Code, original.Body.String())
}
// The same request under a new key, with the older expected version,
// answers the accepted invitation without a second grant or event.
again := accept(first.candidate, first.invitation.ID, first.body, nextKey())
if again.Code != http.StatusOK || again.Body.String() != original.Body.String() {
t.Fatalf("repeat = %d %s, want the same answer %s", again.Code, again.Body.String(), original.Body.String())
}
// Another field set is a different acceptance that the grant refuses.
requireSessionProblem(t, accept(first.candidate, first.invitation.ID,
acceptBody(first.invitation.Version, first.invitation.TermsVersion, acceptTextVersion, "email", "phone"), nextKey()),
http.StatusConflict, "state_conflict")
// A reused key with another body is refused and stores nothing.
requireSessionProblem(t, accept(first.candidate, first.invitation.ID,
acceptBody(first.invitation.Version, first.invitation.TermsVersion, acceptTextVersion, "phone"), first.key),
http.StatusUnprocessableEntity, "idempotency_key_reused")
// Three outcomes: the first acceptance, the repeat, and the refused field set.
if counts := readInvitationAcceptCounts(ctx, t, harness, first.invitation.ID, first.candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 3}) {
t.Fatalf("repeats stored %+v, want the first acceptance, its repeat, and the refusal", counts)
}
})
t.Run("a stale terms version is refused and nothing is stored, and the raised terms are accepted", func(t *testing.T) {
candidate := candidates[1]
sent := deliver(candidate)
raisedVersion := raiseTerms(sent.ID)
// The candidate read the terms of version 1: 412, nothing stored.
requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(raisedVersion, sent.TermsVersion, acceptTextVersion, "email"), nextKey()),
http.StatusPreconditionFailed, "version_conflict")
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{}) {
t.Fatalf("a stale terms version stored %+v", counts)
}
read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK)
if read.TermsVersion != 2 || read.Version != raisedVersion || read.State != "delivered" {
t.Fatalf("read after the raise = %+v, want the new terms and the delivered state", read)
}
accepted := decodeCandidateInvitationHTTP(t, accept(candidate, sent.ID, acceptBody(raisedVersion, 2, acceptTextVersion, "email"), nextKey()), http.StatusOK)
if accepted.State != "accepted" || accepted.TermsVersion != 2 || decodeContactGrantHTTP(t, accepted).TermsVersion != 2 {
t.Fatalf("accepted = %+v, want the raised terms version accepted", accepted)
}
// The old terms version is a different acceptance once the grant exists.
requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(raisedVersion, sent.TermsVersion, acceptTextVersion, "email"), nextKey()),
http.StatusConflict, "state_conflict")
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 2}) {
t.Fatalf("raised acceptance stored %+v, want one acceptance, one grant, one consent, and the refusal", counts)
}
})
t.Run("concurrent acceptances make one transition and one grant", func(t *testing.T) {
candidate := candidates[2]
sent := deliver(candidate)
session := login(candidate)
path := myPath(sent.ID) + "/accept"
body := acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email")
responses := parallelAcceptRequests(t, harness, path, origin, session,
[]string{body, body, body}, []string{nextKey(), nextKey(), nextKey()})
var answers []string
for _, response := range responses {
accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK)
if accepted.State != "accepted" {
t.Fatalf("concurrent answer = %+v, want accepted", accepted)
}
answers = append(answers, response.Body.String())
}
if !slices.Equal(answers[1:], answers[:len(answers)-1]) {
t.Fatalf("concurrent answers differ: %v", answers)
}
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 3}) {
t.Fatalf("concurrent acceptances stored %+v, want one transition, one grant, one consent", counts)
}
// Two different field sets race: one transition, the other a conflict.
other := candidates[3]
raced := deliver(other)
responses = parallelAcceptRequests(t, harness, myPath(raced.ID)+"/accept", origin, login(other),
[]string{
acceptBody(raced.Version, raced.TermsVersion, acceptTextVersion, "email"),
acceptBody(raced.Version, raced.TermsVersion, acceptTextVersion, "phone"),
}, []string{nextKey(), nextKey()})
statuses := []int{responses[0].Code, responses[1].Code}
slices.Sort(statuses)
if !slices.Equal(statuses, []int{http.StatusOK, http.StatusConflict}) {
t.Fatalf("raced acceptances = %v, want one 200 and one 409 state_conflict", statuses)
}
if counts := readInvitationAcceptCounts(ctx, t, harness, raced.ID, other.ID); counts.acceptedEvents != 1 || counts.grants != 1 || counts.c4Consents != 1 {
t.Fatalf("raced acceptances stored %+v, want one transition, one grant, one consent", counts)
}
})
t.Run("a hidden organization accepts without changing the publication or the hiding", func(t *testing.T) {
candidate := candidates[4]
sent := deliver(candidate)
privacy.hide(t, candidate.ID, orgA, harness.clock.Now())
publication := privacy.rawPublication(t, candidate.ID)
hidden := privacy.rawHidden(t, candidate.ID)
response := accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email"), nextKey())
accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK)
grant := decodeContactGrantHTTP(t, accepted)
if grant.Readable || grant.BlockedBy == nil || *grant.BlockedBy != "visibility" || len(grant.Fields) != 1 {
t.Fatalf("grant while hidden = %+v, want stored and blocked by visibility", grant)
}
if after := privacy.rawPublication(t, candidate.ID); after != publication {
t.Fatalf("the acceptance changed the publication: %s became %s", publication, after)
}
if after := privacy.rawHidden(t, candidate.ID); after != hidden {
t.Fatalf("the acceptance changed the hiding: %s became %s", hidden, after)
}
// The candidate removes the hiding; the same grant becomes readable.
if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1 AND organization_id = $2`,
candidate.ID, orgA); err != nil {
t.Fatalf("unhide the organization: %v", err)
}
reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK)
if grantRead := decodeContactGrantHTTP(t, reread); grantRead.ID != grant.ID || !grantRead.Readable || grantRead.BlockedBy != nil {
t.Fatalf("grant after unhiding = %+v, want the same grant readable", grantRead)
}
})
t.Run("a late acceptance is refused under its key whatever the version", func(t *testing.T) {
candidate := candidates[5]
sent := deliver(candidate)
var deadline time.Time
if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, sent.ID).Scan(&deadline); err != nil {
t.Fatalf("read the deadline: %v", err)
}
harness.clock.Set(deadline.UTC())
key := nextKey()
for range 2 {
requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(sent.Version+5, sent.TermsVersion, acceptTextVersion, "email"), key),
http.StatusConflict, "state_conflict")
}
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{outcomes: 1}) {
t.Fatalf("late acceptances stored %+v, want one state_conflict outcome and nothing else", counts)
}
})
t.Run("the consent text and the held kinds are checked before anything is stored", func(t *testing.T) {
// The late case moved the clock to a deadline, which ends the owner session.
sessionOwner = loginOrganizationHTTP(t, harness.sessionHTTPHarness, owner.Email.Address())
candidate := candidates[6]
sent := deliver(candidate)
requireInvitationValidation(t, accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, "c4-2025-01-01", "email"), nextKey()),
"/consent_c4/text_version", "")
requireInvitationValidation(t, accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email", "telegram"), nextKey()),
"/consent_c4/fields/1", "")
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{}) {
t.Fatalf("refused consent stored %+v", counts)
}
read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK)
if read.State != "delivered" || string(read.ContactGrant) != "null" {
t.Fatalf("read after the refusals = %+v, want the delivered invitation without a grant", read)
}
})
t.Run("the acceptance answers stay out of the server log", func(t *testing.T) {
requireNoCandidateData("server log", harness.logs.String())
})
}
func TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback(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)
}
// The fixture creates an organization with the schema of the current head.
fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL)
// Migrations added after this one are not part of this guard: the test
// rolls them back, so that this migration is the one rolled back below.
rollBackAboveVersion(ctx, t, migrator, invitationAcceptMigrationVersion)
store := func(t *testing.T, work func(context.Context, outbound.UnitOfWork) error) error {
t.Helper()
return fixture.transactor.WithinTransaction(ctx, work)
}
deliverDraft := func(t *testing.T) domain.Invitation {
t.Helper()
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 := store(t, 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)
}
return delivered
}
delivered := deliverDraft(t)
acceptedAt := delivered.UpdatedAt().Add(time.Minute)
accepted, err := delivered.Accept(delivered.TermsVersion(), acceptedAt)
if err != nil {
t.Fatalf("Accept() error = %v", err)
}
acceptEvent, err := accepted.AnswerEvent(fixture.candidate.ID)
if err != nil {
t.Fatalf("AnswerEvent() error = %v", err)
}
fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail)
if err != nil {
t.Fatalf("NewContactFieldSet() error = %v", err)
}
consents := consent.NewService(fixture.transactor, func() time.Time { return acceptedAt })
if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.Invitations().Accept(ctx, delivered.Version(), accepted, acceptEvent); err != nil {
return err
}
granted, err := consents.GrantContact(ctx, unit, consent.ContactGrantInput{
SubjectID: fixture.candidate.ID, OrganizationID: fixture.organization.ID(), OrganizationName: fixture.organization.Profile().Name(),
Fields: fields, InvitationID: delivered.ID(), InvitationTermsVersion: delivered.TermsVersion(), TextVersion: acceptTextVersion,
})
if err != nil {
return err
}
grant, err := domain.NewContactGrant(granted.Record, accepted)
if err != nil {
return err
}
return unit.ContactGrants().Create(ctx, grant)
}); err != nil {
t.Fatalf("accept through the repositories error = %v", err)
}
// The database guards the acceptance and its grant against other writers.
_, err = pool.Exec(ctx, `UPDATE invitations SET state = 'delivered', responded_at = NULL, version = version + 1 WHERE id = $1`, delivered.ID())
assertPgError(t, "leave the acceptance", err, privacyIntegrityViolation, "invitations_answer_immutable")
_, err = pool.Exec(ctx, `UPDATE contact_grants SET fields = '{phone}' WHERE source_invitation_id = $1`, delivered.ID())
assertPgError(t, "change the grant", err, privacyIntegrityViolation, "contact_grants_immutable")
_, err = pool.Exec(ctx, `DELETE FROM contact_grants WHERE source_invitation_id = $1`, delivered.ID())
assertPgError(t, "delete the grant", err, privacyIntegrityViolation, "contact_grants_immutable")
_, err = pool.Exec(ctx, `INSERT INTO invitation_events (id, invitation_id, organization_id, version, terms_version, kind, actor_id, changed_fields, occurred_at)
SELECT $1, id, organization_id, version + 1, terms_version, 'accepted', created_by, ARRAY['terms'], now() FROM invitations WHERE id = $2`, uuid.New(), delivered.ID())
assertPgError(t, "accepted event with a field", err, privacyCheckViolation, "invitation_events_answer_changes_no_field")
// An acceptance without its grant cannot commit.
other := deliverDraft(t)
_, err = pool.Exec(ctx, `UPDATE invitations SET state = 'accepted', responded_at = delivered_at + interval '1 minute',
updated_at = delivered_at + interval '1 minute', version = version + 1 WHERE id = $1`, other.ID())
assertPgError(t, "accepted without a grant", err, privacyIntegrityViolation, "invitations_acceptance_recorded")
_, err = migrator.DownOne(ctx)
assertPgError(t, "DownOne() with an accepted invitation", err, privacyIntegrityViolation, invitationAcceptancesRetained)
// The database is isolated to this test: CASCADE also clears the tables that
// refer to the consent ledger, such as the publication history of C2.
if _, err := pool.Exec(ctx, `TRUNCATE consent_records, invitations, invitation_accept_results, invitation_decline_results,
invitation_send_results, invitation_creation_results CASCADE`); err != nil {
t.Fatalf("clear the invitation tables: %v", err)
}
result, err := migrator.DownOne(ctx)
if err != nil || result.Version != invitationAcceptMigrationVersion {
t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationAcceptMigrationVersion)
}
var remaining int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name IN ('contact_grants', 'invitation_accept_results')`).Scan(&remaining); err != nil || remaining != 0 {
t.Fatalf("acceptance tables left after the rollback: %d, %v", remaining, err)
}
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() after the rollback error = %v", err)
}
}
@@ -9,6 +9,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"time"
@@ -254,9 +255,25 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) {
read := request(http.MethodGet, myPath(sent.ID), "", sessionTarget, "")
opened := decodeCandidateInvitationHTTP(t, read, http.StatusOK)
requireNoCandidateData("candidate read", read.Body.String())
// While an acceptance is possible the read offers the consent C4 with
// the kinds that the profile holds, and no grant exists yet.
var offer struct {
Text struct {
TextVersion string `json:"text_version"`
Text string `json:"text"`
} `json:"text"`
AvailableFields []string `json:"available_fields"`
}
if err := json.Unmarshal(opened.ContactConsent, &offer); err != nil {
t.Fatalf("decode contact consent %s: %v", opened.ContactConsent, err)
}
if strings.Contains(offer.Text.Text, "{organization}") || !strings.Contains(offer.Text.Text, nameA) ||
offer.Text.TextVersion != "c4-2026-10-01" || !slices.Equal(offer.AvailableFields, []string{"full_name", "email"}) {
t.Fatalf("contact consent = %+v, want the C4 text for the organization and the held kinds", offer)
}
if opened.State != "delivered" || opened.Version != sent.Version || opened.ViewedAt != nil || opened.Organization.ID != orgA ||
opened.Organization.Name != nameA || opened.ResponseDeadlineAt != *sent.ResponseDeadlineAt || opened.Decline != nil ||
string(opened.ContactConsent) != "null" || string(opened.ContactGrant) != "null" || len(opened.Terms) == 0 {
string(opened.ContactGrant) != "null" || len(opened.Terms) == 0 {
t.Fatalf("read = %+v, want the delivered invitation with its terms and no side effect", opened)
}
// A read records nothing: it is free of side effects by contract.
@@ -30,6 +30,7 @@ import (
"lincodex/backend/internal/usecase/anonymousprofile"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/companyquota"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
invitationusecase "lincodex/backend/internal/usecase/invitation"
@@ -119,7 +120,7 @@ func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnviro
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: notifier, Clock: clock.Now,
Notifier: notifier, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now,
})
if err != nil {
t.Fatalf("invitation.NewService() error = %v", err)
@@ -1078,13 +1078,15 @@ func TestMatchSearchOverHTTP(t *testing.T) {
})
t.Run("the allowance of an organization ends the output and the group limit cuts it, without a total", func(t *testing.T) {
orgC := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization C"), now)
// Organizations of one owner share the E0 pool, so this one gets an owner of its own.
ownerC := client.employer(t, "match-employer-c@example.test")
orgC := organizations.create(t, domain.User{ID: ownerC.id}, organizations.completeProfile(t, "Match organization C"), now)
bounded := func(product *domain.ProductPolicy) {
product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8
}
publishPolicy(bounded)
searchC := func() (matchSearchBody, string) {
result, response := search(employer, orgC.ID(), `{"filters":{}}`)
result, response := search(ownerC, orgC.ID(), `{"filters":{}}`)
if response.Code != http.StatusOK {
t.Fatalf("search of organization C = %d %s", response.Code, response.Body.String())
}
@@ -1119,7 +1121,7 @@ func TestMatchSearchOverHTTP(t *testing.T) {
cardPath := func(handle string) string {
return fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgC.ID(), handle)
}
if got := harness.request(t, http.MethodGet, cardPath(first.Groups.Main[0].CandidateHandle), "", "", employer.cookie, "", client.remote()); got.Code != http.StatusOK ||
if got := harness.request(t, http.MethodGet, cardPath(first.Groups.Main[0].CandidateHandle), "", "", ownerC.cookie, "", client.remote()); got.Code != http.StatusOK ||
revealedBy(orgC.ID()) != 8 {
t.Fatalf("card of a paid candidate = %d, paid %d, want 200 and no new charge", got.Code, revealedBy(orgC.ID()))
}
@@ -1131,7 +1133,7 @@ func TestMatchSearchOverHTTP(t *testing.T) {
}
}
}
if got := harness.request(t, http.MethodGet, cardPath(unpaid), "", "", employer.cookie, "", client.remote()); got.Code != http.StatusTooManyRequests {
if got := harness.request(t, http.MethodGet, cardPath(unpaid), "", "", ownerC.cookie, "", client.remote()); got.Code != http.StatusTooManyRequests {
t.Fatalf("card of an unpaid candidate = %d, want 429 from the same allowance", got.Code)
}
// The organizations pay independently of each other.
@@ -1176,7 +1178,8 @@ func TestMatchSearchOverHTTP(t *testing.T) {
})
t.Run("two concurrent searches of one organization never charge beyond the allowance", func(t *testing.T) {
orgD := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization D"), now)
ownerD := client.employer(t, "match-employer-d@example.test")
orgD := organizations.create(t, domain.User{ID: ownerD.id}, organizations.completeProfile(t, "Match organization D"), now)
publishPolicy(func(product *domain.ProductPolicy) { product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8 })
type outcome struct {
status int
@@ -1193,7 +1196,7 @@ func TestMatchSearchOverHTTP(t *testing.T) {
group.Add(1)
go func() {
defer group.Done()
response := harness.request(t, http.MethodPost, searchPath(orgD.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, employer.cookie, employer.csrf, remote)
response := harness.request(t, http.MethodPost, searchPath(orgD.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, ownerD.cookie, ownerD.csrf, remote)
outcomes <- outcome{status: response.Code, body: response.Body.String()}
}()
}
@@ -1238,7 +1241,8 @@ func TestMatchSearchOverHTTP(t *testing.T) {
})
t.Run("concurrent card reads, evidence reads, and searches of one organization neither deadlock nor overcharge", func(t *testing.T) {
orgF := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization F"), now)
ownerF := client.employer(t, "match-employer-f@example.test")
orgF := organizations.create(t, domain.User{ID: ownerF.id}, organizations.completeProfile(t, "Match organization F"), now)
visible := make([]categoryHTTPCandidate, 0, 17)
for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} {
visible = append(visible, group...)
@@ -1269,14 +1273,14 @@ func TestMatchSearchOverHTTP(t *testing.T) {
remote := client.remote()
path := fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s%s", orgF.ID(), aliasIn(orgF.ID(), member.id), suffix)
return func() outcome {
response := harness.request(t, http.MethodGet, path, "", "", employer.cookie, "", remote)
response := harness.request(t, http.MethodGet, path, "", "", ownerF.cookie, "", remote)
return outcome{what: "card" + suffix, status: response.Code}
}
}
searchJob := func() func() outcome {
remote := client.remote()
return func() outcome {
response := harness.request(t, http.MethodPost, searchPath(orgF.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, employer.cookie, employer.csrf, remote)
response := harness.request(t, http.MethodPost, searchPath(orgF.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, ownerF.cookie, ownerF.csrf, remote)
return outcome{what: "search", status: response.Code}
}
}
+7 -5
View File
@@ -367,9 +367,8 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
t.Fatalf("apply migrations to rollback test database: %v", err)
}
// The preflight belongs to the migration that created the replay table, so
// the migrations added after it are rolled back first. The database holds
// no data yet, which keeps their own guarded rollbacks out of this test.
rollBackAboveMigration(ctx, t, migrator, needCreationResultMigrationVersion)
// the migrations added after it are rolled back first. The one organization
// below has its own holding, so their guarded rollbacks do not refuse.
pool := newPoolFor(ctx, t, databaseURL)
now := time.Now().UTC().Truncate(time.Microsecond)
fixture := organizationFixture{
@@ -377,6 +376,11 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now},
transactor: postgresadapter.NewTransactor(pool), now: now,
}
// The organization is created while the latest schema is in place: its
// creation needs the holdings table, which the rollback below removes.
owner := fixture.employer(t, "need-migration-owner@example.test")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now)
rollBackAboveMigration(ctx, t, migrator, needCreationResultMigrationVersion)
scope := []byte(strings.Repeat("s", outbound.IdempotencyDigestSize))
fingerprint := []byte(strings.Repeat("f", outbound.IdempotencyDigestSize))
if _, err := pool.Exec(ctx, `
@@ -400,8 +404,6 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
now.Add(-outbound.IdempotencyRetention-time.Second), now.Add(-time.Second), scope); err != nil {
t.Fatalf("expire idempotency replay before checking historical bounds: %v", err)
}
owner := fixture.employer(t, "need-migration-owner@example.test")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now)
need := newIntegrationNeed(t, organization.ID(), "Bounded rollback fixture", now.Add(time.Minute))
encoded, err := json.Marshal(need.Snapshot())
if err != nil {
@@ -31,8 +31,8 @@ func TestSyntheticNotificationMigrationAllowlistAndGuardedRollback(t *testing.T)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion)
// The candidate and the organization are created while the latest schema is in
// place: their creation needs the holdings table, which the rollback removes.
now := time.Now().UTC().Truncate(time.Microsecond)
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
candidate := identity.createUser(t, "inbox-migration@example.com", domain.ScenarioCandidate, now.Add(-time.Hour))
@@ -42,6 +42,8 @@ func TestSyntheticNotificationMigrationAllowlistAndGuardedRollback(t *testing.T)
owner := organizations.employer(t, "inbox-migration-owner@example.com")
organization := organizations.create(t, owner, organizations.completeProfile(t, "Example Company"), now)
rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion)
insert := func(eventType, sourceType string, schemaVersion int) error {
_, err := pool.Exec(ctx, `INSERT INTO notification_inbox_events (
recipient_user_id, event_id, organization_id, event_type, schema_version, source_type, source_id, occurred_at
+15 -5
View File
@@ -41,11 +41,13 @@ var (
organizationTables = []pgx.Identifier{
{"candidate_card_access_events"},
{"invitation_creation_results"}, {"invitation_send_results"}, {"invitation_decline_results"}, {"invitation_declines"},
{"invitation_events"}, {"invitation_terms_versions"}, {"invitations"},
{"invitation_events"}, {"invitation_terms_versions"}, {"invitation_accept_results"}, {"contact_grants"}, {"invitations"},
{"organization_need_versions"}, {"organization_needs"},
{"organization_need_creation_results"},
{"company_invitation_quota_usage"}, {"company_card_view_quota_usage"},
organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable,
// holdings reference users and are referenced by organizations.
{"holdings"},
}
candidateQuestionnaireTables = []pgx.Identifier{
{"candidate_questionnaire_specializations"}, {"candidate_questionnaires"},
@@ -260,10 +262,16 @@ func TestOrganizationsAndMemberships(t *testing.T) {
reset(t)
member := fixture.employer(t, "member@example.com")
insertOrganization := func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error {
if _, err := tx.Exec(ctx, `
INSERT INTO holdings (id, founder_account_id, created_at) VALUES ($1, $2, $3)
ON CONFLICT (founder_account_id) DO NOTHING`, uuid.New(), member.ID, now); err != nil {
return err
}
_, err := tx.Exec(ctx, `
INSERT INTO organizations (
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at
) VALUES ($1, 'ООО Без владельца', 'e0', 'confirmed_email', $2, 1, $2, $2)`, id, now)
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id
) VALUES ($1, 'ООО Без владельца', 'e0', 'confirmed_email', $2, 1, $2, $2,
(SELECT id FROM holdings WHERE founder_account_id = $3))`, id, now, member.ID)
return err
}
insertMember := func(ctx context.Context, tx pgx.Tx, organizationID uuid.UUID, role, state string) error {
@@ -692,10 +700,12 @@ func TestOrganizationsAndMemberships(t *testing.T) {
user := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, user, fixture.completeProfile(t, "ООО Пример"), now)
insertOrganization := func(name, verificationLevel, basis string, version int) error {
// The holding of the owner exists, so only the checked columns can fail.
_, err := pool.Exec(ctx, `
INSERT INTO organizations (
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at
) VALUES ($1, $2, $3, $4, $5, $6, $5, $5)`, uuid.New(), name, verificationLevel, basis, now, version)
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id
) VALUES ($1, $2, $3, $4, $5, $6, $5, $5,
(SELECT id FROM holdings WHERE founder_account_id = $7))`, uuid.New(), name, verificationLevel, basis, now, version, user.ID)
return err
}
for _, test := range []struct {
+1 -1
View File
@@ -252,7 +252,7 @@ func TestPolicyVersions(t *testing.T) {
assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks,
assessment_synthetic_category_reviews, candidate_assessment_categories,
skill_evidence_facts, skill_evidence_skills,
invitations, invitation_terms_versions, invitation_events, invitation_declines`},
invitations, invitation_terms_versions, invitation_events, invitation_declines, contact_grants`},
}
for _, statement := range statements {
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
@@ -807,6 +807,18 @@ func TestSkillEvidenceOverHTTP(t *testing.T) {
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE event_id = $1`, targetRun.id); err != nil {
t.Fatalf("hide the fact: %v", err)
}
// The rollback of the holdings migration refuses a holding that groups several
// organizations. The second organization moves to a holding of its own first;
// the evidence rollback under test does not depend on the grouping.
split := client.employer(t, "evidence-holding-split@example.test")
if _, err := harness.pool.Exec(ctx, `
INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, now())`, split.id); err != nil {
t.Fatalf("create the holding of the split organization: %v", err)
}
if _, err := harness.pool.Exec(ctx, `
UPDATE organizations SET holding_id = (SELECT id FROM holdings WHERE founder_account_id = $1) WHERE id = $2`, split.id, organizationB.ID()); err != nil {
t.Fatalf("move the second organization to its own holding: %v", err)
}
// Later migrations may exist; the rollback under test is the evidence one.
rollBackAboveMigration(ctx, t, migrator, skillEvidenceMigrationVersion)
_, err = migrator.DownOne(ctx)
@@ -30,6 +30,7 @@ type InvitationOperations interface {
GetMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error)
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)
}
// InvitationHandler serves the organization side of invitation drafts and
@@ -31,6 +31,66 @@ func (handler *Handler) DeclineMyInvitation(ctx context.Context, request *api.In
return handler.invitation.DeclineMyInvitation(ctx, request, params)
}
func (handler *Handler) AcceptMyInvitation(ctx context.Context, request *api.InvitationAcceptance, params api.AcceptMyInvitationParams) (api.AcceptMyInvitationRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.AcceptMyInvitation(ctx, request, params)
}
return handler.invitation.AcceptMyInvitation(ctx, request, params)
}
// AcceptMyInvitation accepts the current terms of an invitation with the consent
// C4. The fields come from the body as kinds only; the server takes the values
// from the profile, and the request never carries them.
func (handler *InvitationHandler) AcceptMyInvitation(
ctx context.Context,
request *api.InvitationAcceptance,
params api.AcceptMyInvitationParams,
) (api.AcceptMyInvitationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.AcceptMyInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.AcceptMyInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
fields := make([]domain.ContactField, 0, len(request.ConsentC4.Fields))
for _, field := range request.ConsentC4.Fields {
fields = append(fields, domain.ContactField(field))
}
view, err := handler.operations.AcceptMine(ctx, invitationusecase.AcceptCommand{
ActorID: principal.UserID, InvitationID: params.InvitationID, IdempotencyKey: params.IdempotencyKey,
ExpectedVersion: int64(request.ExpectedVersion), TermsVersion: int64(request.TermsVersion),
TextVersion: string(request.ConsentC4.TextVersion), Fields: fields,
})
if err != nil {
return invitationAcceptFailure(ctx, err)
}
return &api.CandidateInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: candidateInvitationResponse(view)}, nil
}
func invitationAcceptFailure(ctx context.Context, err error) (api.AcceptMyInvitationRes, error) {
if errors.Is(err, invitationusecase.ErrAnswerBlocked) {
return (*api.AcceptMyInvitationConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
}
switch classifyInvitationError(err) {
case invitationFailureForbidden:
return (*api.AcceptMyInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case invitationFailureNotFound:
return (*api.AcceptMyInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case invitationFailureKeyReused:
return (*api.AcceptMyInvitationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case invitationFailureBadKey:
return (*api.AcceptMyInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case invitationFailureInvalid:
return (*api.AcceptMyInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil
case invitationFailureVersionConflict:
return (*api.AcceptMyInvitationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case invitationFailureStateConflict, invitationFailureOther:
return nil, err
}
return nil, err
}
func (handler *InvitationHandler) GetMyInvitation(ctx context.Context, params api.GetMyInvitationParams) (api.GetMyInvitationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
@@ -123,10 +183,9 @@ func invitationDeclineFailure(ctx context.Context, err error) (api.DeclineMyInvi
return nil, err
}
// candidateInvitationResponse maps the candidate's view. The consent offer
// and the contact grant belong to the acceptance, which is not served yet,
// so an acceptance is impossible now and both are null, as the contract
// requires when no acceptance can be made.
// candidateInvitationResponse maps the candidate's view. The consent offer is
// set only while an acceptance is possible, and the contact grant only after
// the acceptance; otherwise both are null, as the contract requires.
func candidateInvitationResponse(view domain.CandidateInvitationView) api.CandidateInvitation {
response := api.CandidateInvitation{
ID: view.ID,
@@ -138,7 +197,13 @@ func candidateInvitationResponse(view domain.CandidateInvitationView) api.Candid
RespondedAt: nullableTimestamp(view.RespondedAt), UpdatedAt: api.Timestamp(view.UpdatedAt),
}
response.ContactConsent.SetToNull()
if view.ContactConsent != nil {
response.ContactConsent.SetTo(contactConsentOfferResponse(*view.ContactConsent))
}
response.ContactGrant.SetToNull()
if view.ContactGrant != nil {
response.ContactGrant.SetTo(contactGrantResponse(*view.ContactGrant))
}
if view.Decline == nil {
response.Decline.SetToNull()
return response
@@ -154,3 +219,43 @@ func candidateInvitationResponse(view domain.CandidateInvitationView) api.Candid
response.Decline.SetTo(record)
return response
}
func contactConsentOfferResponse(offer domain.ContactConsentOffer) api.ContactConsentOffer {
fields := make([]api.ContactFieldKind, 0, len(offer.AvailableFields))
for _, field := range offer.AvailableFields {
fields = append(fields, api.ContactFieldKind(field))
}
return api.ContactConsentOffer{
Text: api.ContactConsentText{
TextVersion: api.ConsentTextVersion(offer.Text.TextVersion), Text: offer.Text.Text,
},
AvailableFields: fields,
}
}
// contactGrantResponse maps the grant as the candidate reads it: the kinds, the
// status, and whether the organization can read them now, never a value.
func contactGrantResponse(view domain.ContactGrantView) api.ContactGrant {
fields := make([]api.ContactFieldKind, 0, len(view.Fields))
for _, field := range view.Fields {
fields = append(fields, api.ContactFieldKind(field))
}
response := api.ContactGrant{
ID: view.ID, Fields: fields, Status: api.ContactGrantState(view.Status), Readable: view.Readable,
TermsVersion: api.InvitationTermsVersion(view.TermsVersion),
ConsentTextVersion: api.ConsentTextVersion(view.ConsentTextVersion),
GrantedAt: api.Timestamp(view.GrantedAt),
}
if view.BlockedBy == nil {
response.BlockedBy.SetToNull()
} else {
response.BlockedBy.SetTo(api.ContactAccessBlock(*view.BlockedBy))
}
response.RevokedAt = nullableTimestamp(view.RevokedAt)
if view.RevocationReason == nil {
response.RevocationReason.SetToNull()
} else {
response.RevocationReason.SetTo(api.ContactRevocationReason(*view.RevocationReason))
}
return response
}
@@ -94,3 +94,28 @@ func TestCandidateInvitationResponseCarriesTheDeclineAndNoCandidateData(t *testi
}
}
}
func TestInvitationAcceptFailuresMapToTheContractStatuses(t *testing.T) {
ctx := context.Background()
text := &domain.InvitationFieldError{Pointer: "/consent_c4/text_version", Reason: "x"}
for name, test := range map[string]struct {
err error
want string
}{
"employer": {invitationusecase.ErrForbidden, "*api.AcceptMyInvitationForbidden"},
"unknown": {fmt.Errorf("wrapped: %w", outbound.ErrInvitationNotFound), "*api.AcceptMyInvitationNotFound"},
"reused key": {invitationusecase.ErrIdempotencyKeyReused, "*api.AcceptMyInvitationUnprocessableEntity"},
"bad key": {invitationusecase.ErrInvalidIdempotencyKey, "*api.AcceptMyInvitationBadRequest"},
"consent text": {fmt.Errorf("wrapped: %w", text), "*api.AcceptMyInvitationBadRequest"},
"stale version": {fmt.Errorf("wrapped: %w", domain.ErrInvitationVersionConflict), "*api.AcceptMyInvitationPreconditionFailed"},
"terminal or late": {fmt.Errorf("wrapped: %w", invitationusecase.ErrAnswerBlocked), "*api.AcceptMyInvitationConflict"},
} {
response, unexpected := invitationAcceptFailure(ctx, test.err)
if unexpected != nil || fmt.Sprintf("%T", response) != test.want {
t.Errorf("%s: failure = %T, %v; want %s", name, response, unexpected, test.want)
}
}
if _, unexpected := invitationAcceptFailure(ctx, errors.New("storage failed")); unexpected == nil {
t.Error("an unknown failure produced a public response instead of reaching the responder")
}
}
@@ -8,6 +8,7 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
@@ -26,6 +27,20 @@ type companyQuotaRepository struct {
var _ outbound.CompanyQuotaRepository = companyQuotaRepository{}
// quotaScope names the usage rows that one reservation counts. An organization
// at a tier that shares its holding pool counts the usage of every E0
// organization of the holding; any other tier counts its own usage only.
type quotaScope struct {
organizationID uuid.UUID
// holdingID is the holding of the shared pool, and uuid.Nil when the
// organization keeps its own pool.
holdingID uuid.UUID
}
func (scope quotaScope) sharesHoldingPool() bool {
return scope.holdingID != uuid.Nil
}
func (repository companyQuotaRepository) ReserveInvitation(
ctx context.Context,
quota domain.CompanyQuota,
@@ -38,7 +53,8 @@ func (repository companyQuotaRepository) ReserveInvitation(
if invitationID == uuid.Nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
}
if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil {
scope, err := repository.lockAndCheckSnapshot(ctx, location, quota)
if err != nil {
return outbound.CompanyQuotaDecision{}, err
}
@@ -57,18 +73,15 @@ func (repository companyQuotaRepository) ReserveInvitation(
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read invitation usage: %w", location, mapOrganizationError(err))
}
usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{
OrganizationID: organizationID,
WindowStart: pgTime(quota.InvitationWindowStart()),
})
count, earliestAt, err := repository.countInvitationUsage(ctx, location, scope, quota.InvitationWindowStart())
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err))
return outbound.CompanyQuotaDecision{}, err
}
if usage.UsageCount < 0 {
if count < 0 {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation usage count is negative", location)
}
if usage.UsageCount >= quota.InvitationLimit() {
earliest, err := quotaWindowEarliest(usage.EarliestAt)
if count >= quota.InvitationLimit() {
earliest, err := quotaWindowEarliest(earliestAt)
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest invitation expiry: %w", location, err)
}
@@ -92,7 +105,8 @@ func (repository companyQuotaRepository) ReserveCardView(
if candidateID == uuid.Nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
}
if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil {
scope, err := repository.lockAndCheckSnapshot(ctx, location, quota)
if err != nil {
return outbound.CompanyQuotaDecision{}, err
}
@@ -101,7 +115,7 @@ func (repository companyQuotaRepository) ReserveCardView(
if err != nil || handled {
return decision, err
}
return repository.reserveNewCardView(ctx, location, quota, candidateID, organizationID)
return repository.reserveNewCardView(ctx, location, quota, candidateID, scope)
}
func (repository companyQuotaRepository) reserveExistingCardView(
@@ -166,20 +180,17 @@ func (repository companyQuotaRepository) reserveNewCardView(
location string,
quota domain.CompanyQuota,
candidateID uuid.UUID,
organizationID uuid.UUID,
scope quotaScope,
) (outbound.CompanyQuotaDecision, error) {
usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{
OrganizationID: pgUUID(organizationID),
WindowStart: pgTime(quota.CardViewWindowStart()),
})
count, earliestAt, err := repository.countCardViewUsage(ctx, location, scope, quota.CardViewWindowStart())
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err))
return outbound.CompanyQuotaDecision{}, err
}
if usage.UsageCount < 0 {
if count < 0 {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - card-view usage count is negative", location)
}
if usage.UsageCount >= quota.CardViewLimit() {
earliest, err := quotaWindowEarliest(usage.EarliestAt)
if count >= quota.CardViewLimit() {
earliest, err := quotaWindowEarliest(earliestAt)
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest card-view expiry: %w", location, err)
}
@@ -194,30 +205,119 @@ func (repository companyQuotaRepository) reserveNewCardView(
return outbound.CompanyQuotaDecision{Allowed: true}, nil
}
// countInvitationUsage returns the invitation usage in the window of scope and
// the earliest counted reservation, which sets the retry time of a denial.
func (repository companyQuotaRepository) countInvitationUsage(
ctx context.Context,
location string,
scope quotaScope,
windowStart time.Time,
) (int64, any, error) {
if scope.sharesHoldingPool() {
usage, err := repository.queries.CountCompanyInvitationQuotaHoldingWindow(ctx, sqlc.CountCompanyInvitationQuotaHoldingWindowParams{
HoldingID: pgUUID(scope.holdingID),
WindowStart: pgTime(windowStart),
})
if err != nil {
return 0, nil, fmt.Errorf("%s - count invitation usage of the holding pool: %w", location, mapOrganizationError(err))
}
return usage.UsageCount, usage.EarliestAt, nil
}
usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{
OrganizationID: pgUUID(scope.organizationID),
WindowStart: pgTime(windowStart),
})
if err != nil {
return 0, nil, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err))
}
return usage.UsageCount, usage.EarliestAt, nil
}
// countCardViewUsage is countInvitationUsage for distinct card views.
func (repository companyQuotaRepository) countCardViewUsage(
ctx context.Context,
location string,
scope quotaScope,
windowStart time.Time,
) (int64, any, error) {
if scope.sharesHoldingPool() {
usage, err := repository.queries.CountCompanyCardViewQuotaHoldingWindow(ctx, sqlc.CountCompanyCardViewQuotaHoldingWindowParams{
HoldingID: pgUUID(scope.holdingID),
WindowStart: pgTime(windowStart),
})
if err != nil {
return 0, nil, fmt.Errorf("%s - count card-view usage of the holding pool: %w", location, mapOrganizationError(err))
}
return usage.UsageCount, usage.EarliestAt, nil
}
usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{
OrganizationID: pgUUID(scope.organizationID),
WindowStart: pgTime(windowStart),
})
if err != nil {
return 0, nil, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err))
}
return usage.UsageCount, usage.EarliestAt, nil
}
// LockOrganization takes the organization lock and, for an E0 organization,
// the lock of its holding, in that order. Every caller that reserves usage
// later takes it first, so the pool is serialized before any other lock.
func (repository companyQuotaRepository) LockOrganization(ctx context.Context, organizationID uuid.UUID) error {
const location = "companyQuotaRepository.LockOrganization"
if _, err := repository.queries.LockCompanyQuotaOrganizationFirst(ctx, pgUUID(organizationID)); err != nil {
organization, err := repository.queries.LockCompanyQuotaOrganizationFirst(ctx, pgUUID(organizationID))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - organization was removed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
}
// The level is read under the organization lock, which a trust change
// must also take, so the tier cannot change before the holding is locked.
if tier, ok := domain.OrganizationVerificationLevel(organization.VerificationLevel).QuotaTier(); ok && tier.SharesHoldingPool() {
if _, err := lockQuotaHolding(ctx, repository.queries, location, organization.HoldingID); err != nil {
return err
}
}
return nil
}
// lockAndCheckSnapshot takes the organization lock for the reservation, checks
// the stored trust and effective policy against the snapshot, and returns the
// usage scope. The holding of an E0 organization is locked after the
// organization and before the usage is counted.
func (repository companyQuotaRepository) lockAndCheckSnapshot(
ctx context.Context,
location string,
quota domain.CompanyQuota,
) error {
organizationID := pgUUID(quota.OrganizationID())
organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, organizationID)
) (quotaScope, error) {
organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, pgUUID(quota.OrganizationID()))
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
return quotaScope{}, fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
if err != nil {
return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
return quotaScope{}, fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
}
if err := checkStoredTrust(location, quota, organization); err != nil {
return quotaScope{}, err
}
scope := quotaScope{organizationID: quota.OrganizationID()}
if quota.Tier().SharesHoldingPool() {
scope.holdingID, err = lockQuotaHolding(ctx, repository.queries, location, organization.HoldingID)
if err != nil {
return quotaScope{}, err
}
}
if err := repository.checkEffectivePolicy(ctx, location, quota); err != nil {
return quotaScope{}, err
}
return scope, nil
}
// checkStoredTrust refuses a reservation whose snapshot no longer matches the
// verification of the locked organization.
func checkStoredTrust(location string, quota domain.CompanyQuota, organization sqlc.LockCompanyQuotaOrganizationRow) error {
if !organization.ID.Valid || organization.ID.Bytes != quota.OrganizationID() ||
!organization.VerificationChangedAt.Valid ||
organization.VerificationLevel != string(quota.VerificationLevel()) ||
@@ -225,7 +325,12 @@ func (repository companyQuotaRepository) lockAndCheckSnapshot(
!organization.VerificationChangedAt.Time.Equal(quota.VerificationChangedAt()) {
return fmt.Errorf("%s - stored organization trust changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
return nil
}
// checkEffectivePolicy refuses a reservation whose policy version is no longer
// the effective product policy at the application clock snapshot.
func (repository companyQuotaRepository) checkEffectivePolicy(ctx context.Context, location string, quota domain.CompanyQuota) error {
policy, err := repository.queries.GetEffectivePolicyVersion(ctx, sqlc.GetEffectivePolicyVersionParams{
PolicyKey: string(domain.ProductPolicyKey),
At: pgTime(quota.At()),
@@ -242,6 +347,30 @@ func (repository companyQuotaRepository) lockAndCheckSnapshot(
return nil
}
// lockQuotaHolding takes the pool lock of an E0 holding. The caller must hold
// the lock of the organization that names the holding.
func lockQuotaHolding(
ctx context.Context,
queries *sqlc.Queries,
location string,
holdingID pgtype.UUID,
) (uuid.UUID, error) {
if !holdingID.Valid {
return uuid.Nil, fmt.Errorf("%s - organization has no holding", location)
}
locked, err := queries.LockCompanyQuotaHolding(ctx, holdingID)
if errors.Is(err, pgx.ErrNoRows) {
return uuid.Nil, fmt.Errorf("%s - holding was removed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
if err != nil {
return uuid.Nil, fmt.Errorf("%s - lock holding: %w", location, mapOrganizationError(err))
}
if !locked.Valid {
return uuid.Nil, fmt.Errorf("%s - locked holding has no identifier", location)
}
return uuid.UUID(locked.Bytes), nil
}
func (repository companyQuotaRepository) cleanupExpiredCardViews(
ctx context.Context,
location string,
@@ -0,0 +1,209 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
_ outbound.InvitationAcceptResultRepository = invitationRepository{}
_ outbound.ContactGrantRepository = contactGrantRepository{}
)
func (unit *UnitOfWork) InvitationAcceptResults() outbound.InvitationAcceptResultRepository {
return invitationRepository{queries: unit.queries}
}
func (unit *UnitOfWork) ContactGrants() outbound.ContactGrantRepository {
return contactGrantRepository{queries: unit.queries}
}
type contactGrantRepository struct {
queries *sqlc.Queries
}
// Accept stores the acceptance of an invitation. The compare-and-swap applies
// only to a delivered or viewed invitation at the expected version and terms
// version, before its deadline, so a stale writer loses without changing it.
func (repository invitationRepository) Accept(
ctx context.Context,
expectedVersion int64,
next domain.Invitation,
event domain.InvitationEvent,
) error {
const location = "invitationRepository.Accept"
stored := next.Stored()
if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationAccepted) ||
stored.RespondedAt == nil || event.Kind != domain.InvitationEventAccepted {
return fmt.Errorf("%s - the next version must be the acceptance 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.AcceptInvitation(ctx, sqlc.AcceptInvitationParams{
NextVersion: stored.Version, AcceptedAt: pgTime(*stored.RespondedAt), OrganizationID: pgUUID(stored.OrganizationID),
InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, TermsVersion: stored.TermsVersion,
})
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - accept invitation: %w", location, outbound.ErrInvitationVersionConflict)
}
if err != nil {
return fmt.Errorf("%s - accept invitation: %w", location, mapInvitationError(err))
}
return repository.insertEvent(ctx, location, event)
}
func (repository invitationRepository) SaveAcceptResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
result outbound.InvitationAcceptResult,
) error {
const location = "invitationRepository.SaveAcceptResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
}
if err := validateInvitationAcceptResult(result); err != nil {
return fmt.Errorf("%s - validate outcome: %w", location, err)
}
if err := repository.queries.InsertInvitationAcceptResult(ctx, sqlc.InsertInvitationAcceptResultParams{
ScopeHash: scope[:], InvitationID: pgUUID(result.InvitationID), Outcome: string(result.Outcome),
}); err != nil {
return fmt.Errorf("%s - store outcome: %w", location, mapInvitationAcceptResultError(err))
}
return nil
}
func (repository invitationRepository) GetAcceptResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
) (outbound.InvitationAcceptResult, error) {
const location = "invitationRepository.GetAcceptResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
}
row, err := repository.queries.GetInvitationAcceptResult(ctx, scope[:])
if errors.Is(err, pgx.ErrNoRows) {
return outbound.InvitationAcceptResult{}, outbound.ErrInvitationAcceptResultNotFound
}
if err != nil {
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err))
}
if !row.InvitationID.Valid {
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - stored outcome has no invitation: %w", location, domain.ErrInvalidInvitation)
}
result := outbound.InvitationAcceptResult{
InvitationID: uuid.UUID(row.InvitationID.Bytes), Outcome: outbound.InvitationAcceptOutcome(row.Outcome),
}
if err := validateInvitationAcceptResult(result); err != nil {
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
}
return result, nil
}
func validateInvitationAcceptResult(result outbound.InvitationAcceptResult) error {
const location = "postgres.validateInvitationAcceptResult"
switch result.Outcome {
case outbound.InvitationAcceptAccepted:
if result.InvitationID == uuid.Nil {
return fmt.Errorf("%s - an accepted outcome names the invitation: %w", location, domain.ErrInvalidInvitation)
}
case outbound.InvitationAcceptNotFound, outbound.InvitationAcceptStateConflict:
// A refusal names the identifier of the path, which may name nothing.
default:
return fmt.Errorf("%s - outcome is unknown: %w", location, domain.ErrInvalidInvitation)
}
return nil
}
func mapInvitationAcceptResultError(err error) error {
var pgError *pgconn.PgError
if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_accept_results_idempotency_fkey" {
return fmt.Errorf("postgres.mapInvitationAcceptResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
}
return mapInvitationError(err)
}
// Create stores a grant of an accepted invitation. The row can only be created
// active: a revoked grant is never stored by a new acceptance.
func (repository contactGrantRepository) Create(ctx context.Context, grant domain.ContactGrant) error {
const location = "contactGrantRepository.Create"
if grant.IsZero() || grant.Status() != domain.ContactGrantActive {
return fmt.Errorf("%s - the grant must be built by the domain and active: %w", location, domain.ErrInvalidContactGrant)
}
stored := grant.Stored()
if err := repository.queries.InsertContactGrant(ctx, sqlc.InsertContactGrantParams{
ID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), CandidateID: pgUUID(stored.CandidateID),
SourceInvitationID: pgUUID(stored.InvitationID), ConsentRecordID: pgUUID(stored.ConsentRecordID),
TermsVersion: stored.TermsVersion, Fields: stored.Fields, ConsentTextVersion: stored.ConsentTextVersion,
GrantedAt: pgTime(stored.GrantedAt),
}); err != nil {
return fmt.Errorf("%s - insert contact grant: %w", location, mapInvitationError(err))
}
return nil
}
// GetByInvitation reads the grant of one invitation of one organization. The
// read rebuilds the grant through the domain, so a stored row that breaks a
// rule fails instead of being served.
func (repository contactGrantRepository) GetByInvitation(
ctx context.Context,
organizationID, invitationID uuid.UUID,
) (domain.ContactGrant, error) {
const location = "contactGrantRepository.GetByInvitation"
if organizationID == uuid.Nil || invitationID == uuid.Nil {
return domain.ContactGrant{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidContactGrant)
}
row, err := repository.queries.GetContactGrantByInvitation(ctx, sqlc.GetContactGrantByInvitationParams{
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID),
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.ContactGrant{}, fmt.Errorf("%s - select contact grant: %w", location, outbound.ErrContactGrantNotFound)
}
if err != nil {
return domain.ContactGrant{}, fmt.Errorf("%s - select contact grant: %w", location, mapInvitationError(err))
}
stored, err := storedContactGrantRow(row)
if err != nil {
return domain.ContactGrant{}, fmt.Errorf("%s - read stored grant: %w", location, err)
}
grant, err := domain.RestoreContactGrant(stored)
if err != nil {
return domain.ContactGrant{}, fmt.Errorf("%s - restore contact grant: %w", location, err)
}
if stored.OrganizationID != organizationID || stored.InvitationID != invitationID {
return domain.ContactGrant{}, fmt.Errorf("%s - stored grant has another scope: %w", location, domain.ErrInvalidContactGrant)
}
return grant, nil
}
// storedContactGrantRow maps a grant row to its stored form. A row without an
// identifier or a time is refused before the domain rebuilds the grant.
func storedContactGrantRow(row sqlc.ContactGrant) (domain.StoredContactGrant, error) {
if !row.ID.Valid || !row.OrganizationID.Valid || !row.CandidateID.Valid || !row.SourceInvitationID.Valid ||
!row.ConsentRecordID.Valid || !row.GrantedAt.Valid {
return domain.StoredContactGrant{}, fmt.Errorf("stored grant has missing identifiers: %w", domain.ErrInvalidContactGrant)
}
stored := domain.StoredContactGrant{
ID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes),
CandidateID: uuid.UUID(row.CandidateID.Bytes), InvitationID: uuid.UUID(row.SourceInvitationID.Bytes),
ConsentRecordID: uuid.UUID(row.ConsentRecordID.Bytes), TermsVersion: row.TermsVersion, Fields: row.Fields,
ConsentTextVersion: row.ConsentTextVersion, GrantedAt: row.GrantedAt.Time.UTC(),
}
if row.RevokedAt.Valid {
revokedAt := row.RevokedAt.Time.UTC()
stored.RevokedAt = &revokedAt
}
if row.RevocationReason.Valid {
stored.RevocationReason = row.RevocationReason.String
}
return stored, nil
}
@@ -24,6 +24,7 @@ var organizationConstraintErrors = map[constraintViolation]error{
{uniqueViolationCode, "memberships_user_id_organization_id_key"}: outbound.ErrMembershipExists,
{foreignKeyViolationCode, "memberships_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
{foreignKeyViolationCode, "memberships_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "holdings_founder_account_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "organization_representatives_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
}
@@ -72,10 +73,14 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
case owner.OrganizationID() != organization.ID() || owner.Role() != domain.OrganizationRoleOwner || !owner.GrantsAccess():
return fmt.Errorf("%s - owner must be the active owner membership of the organization: %w", location, domain.ErrInvalidMembership)
}
holdingID, err := repository.ensureFounderHolding(ctx, owner.UserID(), organization.CreatedAt())
if err != nil {
return fmt.Errorf("%s - join founder holding: %w", location, err)
}
profile := organization.Profile()
contacts := profile.Contacts()
verification := organization.Verification()
err := repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
err = repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
ID: pgUUID(organization.ID()),
Name: profile.Name(),
Description: pgOptionalText(profile.Description()),
@@ -90,6 +95,7 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
Version: organization.Version(),
CreatedAt: pgTime(organization.CreatedAt()),
UpdatedAt: pgTime(organization.UpdatedAt()),
HoldingID: pgUUID(holdingID),
})
if err != nil {
return fmt.Errorf("%s - insert organization: %w", location, mapOrganizationError(err))
@@ -103,6 +109,37 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
return nil
}
// ensureFounderHolding returns the holding of the founder account and creates
// it in the caller's transaction when the account has none. The insert ignores
// an existing holding, so a concurrent creation of the same account waits for
// the other transaction and then reads the holding that was stored.
func (repository organizationRepository) ensureFounderHolding(
ctx context.Context,
founderID uuid.UUID,
createdAt time.Time,
) (uuid.UUID, error) {
const location = "organizationRepository.ensureFounderHolding"
holding, err := domain.NewHolding(founderID, createdAt)
if err != nil {
return uuid.Nil, fmt.Errorf("%s - build holding: %w", location, err)
}
if err := repository.queries.InsertHoldingIfAbsent(ctx, sqlc.InsertHoldingIfAbsentParams{
ID: pgUUID(holding.ID()),
FounderAccountID: pgUUID(holding.FounderAccountID()),
CreatedAt: pgTime(holding.CreatedAt()),
}); err != nil {
return uuid.Nil, fmt.Errorf("%s - insert holding: %w", location, mapOrganizationError(err))
}
stored, err := repository.queries.GetHoldingIDByFounder(ctx, pgUUID(founderID))
if err != nil {
return uuid.Nil, fmt.Errorf("%s - read stored holding: %w", location, mapOrganizationError(err))
}
if !stored.Valid {
return uuid.Nil, fmt.Errorf("%s - stored holding has no identifier", location)
}
return uuid.UUID(stored.Bytes), nil
}
func (repository organizationRepository) SaveCreationResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
@@ -11,6 +11,39 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const countCompanyCardViewQuotaHoldingWindow = `-- name: CountCompanyCardViewQuotaHoldingWindow :one
SELECT
count(*)::bigint AS usage_count,
min(usage.last_seen_at) AS earliest_at
FROM company_card_view_quota_usage AS usage
INNER JOIN organizations AS organization ON organization.id = usage.organization_id
WHERE
organization.holding_id = $1
AND organization.verification_level = 'e0'
AND usage.last_seen_at > $2
`
type CountCompanyCardViewQuotaHoldingWindowParams struct {
HoldingID pgtype.UUID
WindowStart pgtype.Timestamptz
}
type CountCompanyCardViewQuotaHoldingWindowRow struct {
UsageCount int64
EarliestAt interface{}
}
// Counts the distinct-card usage of the E0 pool of a holding, with the same
// rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted
// per organization: the same candidate seen by two organizations of one
// holding is two charges.
func (q *Queries) CountCompanyCardViewQuotaHoldingWindow(ctx context.Context, arg CountCompanyCardViewQuotaHoldingWindowParams) (CountCompanyCardViewQuotaHoldingWindowRow, error) {
row := q.db.QueryRow(ctx, countCompanyCardViewQuotaHoldingWindow, arg.HoldingID, arg.WindowStart)
var i CountCompanyCardViewQuotaHoldingWindowRow
err := row.Scan(&i.UsageCount, &i.EarliestAt)
return i, err
}
const countCompanyCardViewQuotaWindow = `-- name: CountCompanyCardViewQuotaWindow :one
SELECT
count(*)::bigint AS usage_count,
@@ -38,6 +71,38 @@ func (q *Queries) CountCompanyCardViewQuotaWindow(ctx context.Context, arg Count
return i, err
}
const countCompanyInvitationQuotaHoldingWindow = `-- name: CountCompanyInvitationQuotaHoldingWindow :one
SELECT
count(*)::bigint AS usage_count,
min(usage.reserved_at) AS earliest_at
FROM company_invitation_quota_usage AS usage
INNER JOIN organizations AS organization ON organization.id = usage.organization_id
WHERE
organization.holding_id = $1
AND organization.verification_level = 'e0'
AND usage.reserved_at > $2
`
type CountCompanyInvitationQuotaHoldingWindowParams struct {
HoldingID pgtype.UUID
WindowStart pgtype.Timestamptz
}
type CountCompanyInvitationQuotaHoldingWindowRow struct {
UsageCount int64
EarliestAt interface{}
}
// Counts the invitation usage of the E0 pool of a holding: the usage of every
// organization of the holding whose trust level is E0 when the count runs. Each
// row stays attributed to the organization that consumed it.
func (q *Queries) CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error) {
row := q.db.QueryRow(ctx, countCompanyInvitationQuotaHoldingWindow, arg.HoldingID, arg.WindowStart)
var i CountCompanyInvitationQuotaHoldingWindowRow
err := row.Scan(&i.UsageCount, &i.EarliestAt)
return i, err
}
const countCompanyInvitationQuotaWindow = `-- name: CountCompanyInvitationQuotaWindow :one
SELECT
count(*)::bigint AS usage_count,
@@ -185,12 +250,33 @@ func (q *Queries) InsertCompanyInvitationQuotaUsage(ctx context.Context, arg Ins
return err
}
const lockCompanyQuotaHolding = `-- name: LockCompanyQuotaHolding :one
SELECT id
FROM holdings
WHERE id = $1
FOR NO KEY UPDATE
`
// Takes the pool lock of an E0 holding. It follows the organization lock, so
// every writer locks an organization first and its holding second. Two
// reservations of one holding queue here, and the second one counts the
// usage that the first one committed. The lock does not conflict with the
// FOR KEY SHARE that organizations.holding_id takes when an organization joins
// the holding.
func (q *Queries) LockCompanyQuotaHolding(ctx context.Context, holdingID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockCompanyQuotaHolding, holdingID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const lockCompanyQuotaOrganization = `-- name: LockCompanyQuotaOrganization :one
SELECT
id,
verification_level,
verification_basis,
verification_changed_at
verification_changed_at,
holding_id
FROM organizations
WHERE id = $1
FOR UPDATE
@@ -201,6 +287,7 @@ type LockCompanyQuotaOrganizationRow struct {
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
HoldingID pgtype.UUID
}
func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) {
@@ -211,21 +298,33 @@ func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organization
&i.VerificationLevel,
&i.VerificationBasis,
&i.VerificationChangedAt,
&i.HoldingID,
)
return i, err
}
const lockCompanyQuotaOrganizationFirst = `-- name: LockCompanyQuotaOrganizationFirst :one
SELECT id
SELECT
id,
verification_level,
holding_id
FROM organizations
WHERE id = $1
FOR NO KEY UPDATE
`
// Writers lock the organization first, then invitation/card-view state, and
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
type LockCompanyQuotaOrganizationFirstRow struct {
ID pgtype.UUID
VerificationLevel string
HoldingID pgtype.UUID
}
// Writers lock the organization first, then, for an E0 organization, the holding
// whose pool it shares, then invitation/card-view state, and finally usage rows.
// The organization lock serializes quota decisions for the tenant, the holding
// lock serializes the E0 pool across the organizations of one holding, and
// together they make the subsequent count and insert atomic.
// Takes the organization lock ahead of every share lock of a reader that will
// reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR
// SHARE, so readers of one organization queue up instead of deadlocking on a
@@ -233,12 +332,13 @@ FOR NO KEY UPDATE
// FOR KEY SHARE that a foreign key takes, such as the hidden-organization
// insert of a candidate, which holds the candidate's row and then needs this
// one. The reservation itself still takes FOR UPDATE inside the same
// transaction.
func (q *Queries) LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (pgtype.UUID, error) {
// transaction. The result carries the holding, whose pool an E0 organization
// shares; the caller locks that holding right after this lock.
func (q *Queries) LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationFirstRow, error) {
row := q.db.QueryRow(ctx, lockCompanyQuotaOrganizationFirst, organizationID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
var i LockCompanyQuotaOrganizationFirstRow
err := row.Scan(&i.ID, &i.VerificationLevel, &i.HoldingID)
return i, err
}
const refreshCompanyCardViewQuotaUsage = `-- name: RefreshCompanyCardViewQuotaUsage :execrows
@@ -0,0 +1,111 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: contact_grants.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getContactGrantByInvitation = `-- name: GetContactGrantByInvitation :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
organization_id = $1
AND source_invitation_id = $2
`
type GetContactGrantByInvitationParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
// Read the grant of one invitation of one organization. An invitation of
// another organization finds nothing.
func (q *Queries) GetContactGrantByInvitation(ctx context.Context, arg GetContactGrantByInvitationParams) (ContactGrant, error) {
row := q.db.QueryRow(ctx, getContactGrantByInvitation, arg.OrganizationID, arg.InvitationID)
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 insertContactGrant = `-- name: InsertContactGrant :exec
INSERT INTO contact_grants (
id,
organization_id,
candidate_id,
source_invitation_id,
consent_record_id,
terms_version,
fields,
consent_text_version,
granted_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7::text [],
$8,
$9
)
`
type InsertContactGrantParams struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
SourceInvitationID pgtype.UUID
ConsentRecordID pgtype.UUID
TermsVersion int64
Fields []string
ConsentTextVersion string
GrantedAt pgtype.Timestamptz
}
// Store the contact grant of an acceptance. The row is inserted in the same
// transaction as its C4 consent record and the accepted state; the database
// checks that the record, the invitation, and the candidate agree.
func (q *Queries) InsertContactGrant(ctx context.Context, arg InsertContactGrantParams) error {
_, err := q.db.Exec(ctx, insertContactGrant,
arg.ID,
arg.OrganizationID,
arg.CandidateID,
arg.SourceInvitationID,
arg.ConsentRecordID,
arg.TermsVersion,
arg.Fields,
arg.ConsentTextVersion,
arg.GrantedAt,
)
return err
}
@@ -0,0 +1,53 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: holdings.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getHoldingIDByFounder = `-- name: GetHoldingIDByFounder :one
SELECT id
FROM holdings
WHERE founder_account_id = $1
`
func (q *Queries) GetHoldingIDByFounder(ctx context.Context, founderAccountID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, getHoldingIDByFounder, founderAccountID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const insertHoldingIfAbsent = `-- name: InsertHoldingIfAbsent :exec
INSERT INTO holdings (
id,
founder_account_id,
created_at
) VALUES (
$1,
$2,
$3
)
ON CONFLICT (founder_account_id) DO NOTHING
`
type InsertHoldingIfAbsentParams struct {
ID pgtype.UUID
FounderAccountID pgtype.UUID
CreatedAt pgtype.Timestamptz
}
// Stores the holding of a founder account unless the account already has one.
// A concurrent creation of the same account waits on the founder key until the
// other transaction ends; then this insert does nothing, and the caller reads
// the stored holding with GetHoldingIDByFounder.
func (q *Queries) InsertHoldingIfAbsent(ctx context.Context, arg InsertHoldingIfAbsentParams) error {
_, err := q.db.Exec(ctx, insertHoldingIfAbsent, arg.ID, arg.FounderAccountID, arg.CreatedAt)
return err
}
@@ -11,6 +11,51 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const acceptInvitation = `-- name: AcceptInvitation :one
UPDATE invitations
SET
state = 'accepted',
version = $1,
responded_at = $2,
updated_at = $2
WHERE
organization_id = $3
AND id = $4
AND state IN ('delivered', 'viewed')
AND version = $5
AND terms_version = $6
AND response_deadline_at > $2
AND $1::bigint = $5::bigint + 1
RETURNING id
`
type AcceptInvitationParams struct {
NextVersion int64
AcceptedAt pgtype.Timestamptz
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ExpectedVersion int64
TermsVersion int64
}
// The compare-and-swap of an acceptance: it applies only to a delivered or
// viewed invitation at the version and the terms version that the candidate
// read, and before its deadline. The answer is the acceptance time, and the
// deadline is kept.
func (q *Queries) AcceptInvitation(ctx context.Context, arg AcceptInvitationParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, acceptInvitation,
arg.NextVersion,
arg.AcceptedAt,
arg.OrganizationID,
arg.InvitationID,
arg.ExpectedVersion,
arg.TermsVersion,
)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const declineInvitation = `-- name: DeclineInvitation :one
UPDATE invitations
SET
@@ -51,6 +96,26 @@ func (q *Queries) DeclineInvitation(ctx context.Context, arg DeclineInvitationPa
return id, err
}
const getInvitationAcceptResult = `-- name: GetInvitationAcceptResult :one
SELECT
invitation_id,
outcome
FROM invitation_accept_results
WHERE scope_hash = $1
`
type GetInvitationAcceptResultRow struct {
InvitationID pgtype.UUID
Outcome string
}
func (q *Queries) GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, error) {
row := q.db.QueryRow(ctx, getInvitationAcceptResult, scopeHash)
var i GetInvitationAcceptResultRow
err := row.Scan(&i.InvitationID, &i.Outcome)
return i, err
}
const getInvitationDeclineResult = `-- name: GetInvitationDeclineResult :one
SELECT
invitation_id,
@@ -71,6 +136,29 @@ func (q *Queries) GetInvitationDeclineResult(ctx context.Context, scopeHash []by
return i, err
}
const insertInvitationAcceptResult = `-- name: InsertInvitationAcceptResult :exec
INSERT INTO invitation_accept_results (
scope_hash,
invitation_id,
outcome
) VALUES (
$1,
$2,
$3
)
`
type InsertInvitationAcceptResultParams struct {
ScopeHash []byte
InvitationID pgtype.UUID
Outcome string
}
func (q *Queries) InsertInvitationAcceptResult(ctx context.Context, arg InsertInvitationAcceptResultParams) error {
_, err := q.db.Exec(ctx, insertInvitationAcceptResult, arg.ScopeHash, arg.InvitationID, arg.Outcome)
return err
}
const insertInvitationDecline = `-- name: InsertInvitationDecline :exec
INSERT INTO invitation_declines (
invitation_id,
@@ -476,6 +476,20 @@ type ConsumerProcessedEvent struct {
ProcessedAt pgtype.Timestamptz
}
type ContactGrant struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
SourceInvitationID pgtype.UUID
ConsentRecordID pgtype.UUID
TermsVersion int64
Fields []string
ConsentTextVersion string
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationReason pgtype.Text
}
type Delivery struct {
ID pgtype.UUID
SourceEventID pgtype.UUID
@@ -563,6 +577,12 @@ type EmailToken struct {
PendingOnboardingStep pgtype.Text
}
type Holding struct {
ID pgtype.UUID
FounderAccountID pgtype.UUID
CreatedAt pgtype.Timestamptz
}
type IdempotencyRecord struct {
ScopeHash []byte
Fingerprint []byte
@@ -592,6 +612,12 @@ type Invitation struct {
RespondedAt pgtype.Timestamptz
}
type InvitationAcceptResult struct {
ScopeHash []byte
InvitationID pgtype.UUID
Outcome string
}
type InvitationCreationResult struct {
ScopeHash []byte
Snapshot []byte
@@ -715,6 +741,7 @@ type Organization struct {
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
HoldingID pgtype.UUID
}
type OrganizationCreationResult struct {
@@ -229,7 +229,8 @@ INSERT INTO organizations (
verification_changed_at,
version,
created_at,
updated_at
updated_at,
holding_id
) VALUES (
$1,
$2,
@@ -244,7 +245,8 @@ INSERT INTO organizations (
$11,
$12,
$13,
$14
$14,
$15
)
`
@@ -263,12 +265,13 @@ type InsertOrganizationParams struct {
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
HoldingID pgtype.UUID
}
// Stores a new organization with the verification level that the domain
// gave it. The deferred constraint organizations_owner_required fails the
// transaction at commit unless an active owner membership was inserted in
// it too.
// gave it and the holding of its creator. The deferred constraint
// organizations_owner_required fails the transaction at commit unless an
// active owner membership was inserted in it too.
func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error {
_, err := q.db.Exec(ctx, insertOrganization,
arg.ID,
@@ -285,6 +288,7 @@ func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganization
arg.Version,
arg.CreatedAt,
arg.UpdatedAt,
arg.HoldingID,
)
return err
}
@@ -549,6 +553,23 @@ type UpdateOrganizationProfileParams struct {
ManagerRoles []string
}
type UpdateOrganizationProfileRow struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Changes the profile of an organization over the version the caller read
// and advances the version in the same statement. It names no verification
// column, so a profile update cannot move the trust level. The change
@@ -562,7 +583,7 @@ type UpdateOrganizationProfileParams struct {
// follow it). No row returns for a stale version, an account that is no
// active manager, or an unknown organization; the adapter reads the
// membership to tell them apart.
func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error) {
func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (UpdateOrganizationProfileRow, error) {
row := q.db.QueryRow(ctx, updateOrganizationProfile,
arg.Name,
arg.Description,
@@ -577,7 +598,7 @@ func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrgan
arg.ActorID,
arg.ManagerRoles,
)
var i Organization
var i UpdateOrganizationProfileRow
err := row.Scan(
&i.ID,
&i.Name,
@@ -11,6 +11,11 @@ import (
)
type Querier interface {
// The compare-and-swap of an acceptance: it applies only to a delivered or
// viewed invitation at the version and the terms version that the candidate
// read, and before its deadline. The answer is the acceptance time, and the
// deadline is kept.
AcceptInvitation(ctx context.Context, arg AcceptInvitationParams) (pgtype.UUID, error)
// Adds recipients to the day and the month row. The caller holds their
// locks from LockMailQuotaRows and has checked both limits.
AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error)
@@ -131,7 +136,16 @@ type Querier interface {
CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error)
// Counts the hiding records of one candidate for the settings read.
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
// Counts the distinct-card usage of the E0 pool of a holding, with the same
// rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted
// per organization: the same candidate seen by two organizations of one
// holding is two charges.
CountCompanyCardViewQuotaHoldingWindow(ctx context.Context, arg CountCompanyCardViewQuotaHoldingWindowParams) (CountCompanyCardViewQuotaHoldingWindowRow, error)
CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error)
// Counts the invitation usage of the E0 pool of a holding: the usage of every
// organization of the holding whose trust level is E0 when the count runs. Each
// 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 families of a category that have at least one published
// version, however many versions each has.
@@ -275,6 +289,9 @@ type Querier interface {
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error)
GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error)
// Read the grant of one invitation of one organization. An invitation of
// another organization finds nothing.
GetContactGrantByInvitation(ctx context.Context, arg GetContactGrantByInvitationParams) (ContactGrant, error)
GetCurrentAssessmentCategoryOpening(ctx context.Context, category string) (AssessmentCategoryOpening, error)
// The newest unrevoked record of a purpose other than C4.
GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error)
@@ -304,6 +321,8 @@ type Querier interface {
GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error)
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
GetHoldingIDByFounder(ctx context.Context, founderAccountID pgtype.UUID) (pgtype.UUID, error)
GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, error)
GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error)
GetInvitationDeclineResult(ctx context.Context, scopeHash []byte) (GetInvitationDeclineResultRow, error)
GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error)
@@ -470,6 +489,10 @@ type Querier interface {
// when no row returns; the insert then changes nothing and does not abort
// the transaction.
InsertContactConsentRecord(ctx context.Context, arg InsertContactConsentRecordParams) (InsertContactConsentRecordRow, error)
// Store the contact grant of an acceptance. The row is inserted in the same
// transaction as its C4 consent record and the accepted state; the database
// checks that the record, the invitation, and the candidate agree.
InsertContactGrant(ctx context.Context, arg InsertContactGrantParams) error
// Stores a new delivery. A delivery with the same ID already exists when the
// same request is handled again; the statement then inserts nothing and
// returns 0 rows, and the stored content stays as it was. While another
@@ -477,10 +500,16 @@ type Querier interface {
// for it.
InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error)
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
// Stores the holding of a founder account unless the account already has one.
// A concurrent creation of the same account waits on the founder key until the
// other transaction ends; then this insert does nothing, and the caller reads
// the stored holding with GetHoldingIDByFounder.
InsertHoldingIfAbsent(ctx context.Context, arg InsertHoldingIfAbsentParams) error
// The invitation row, its first terms version, and its first audit event are
// inserted in one caller-owned transaction. The deferred reference to the
// current terms version is checked when the transaction commits.
InsertInvitation(ctx context.Context, arg InsertInvitationParams) error
InsertInvitationAcceptResult(ctx context.Context, arg InsertInvitationAcceptResultParams) error
InsertInvitationDecline(ctx context.Context, arg InsertInvitationDeclineParams) error
InsertInvitationDeclineResult(ctx context.Context, arg InsertInvitationDeclineResultParams) error
InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error
@@ -493,9 +522,9 @@ type Querier interface {
// unique key absorbs at-least-once redelivery without copying event content.
InsertNotificationInboxEvent(ctx context.Context, arg InsertNotificationInboxEventParams) (int64, error)
// Stores a new organization with the verification level that the domain
// gave it. The deferred constraint organizations_owner_required fails the
// transaction at commit unless an active owner membership was inserted in
// it too.
// gave it and the holding of its creator. The deferred constraint
// organizations_owner_required fails the transaction at commit unless an
// active owner membership was inserted in it too.
InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error
// The parent and first immutable snapshot are inserted in one caller-owned
// transaction. Deferred version references are checked when it commits.
@@ -741,10 +770,19 @@ type Querier interface {
// canceled, or reclaimed after the lease expired. While the lock is held,
// other workers skip the row, so the handler never runs twice at once.
LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error)
// Takes the pool lock of an E0 holding. It follows the organization lock, so
// every writer locks an organization first and its holding second. Two
// reservations of one holding queue here, and the second one counts the
// usage that the first one committed. The lock does not conflict with the
// FOR KEY SHARE that organizations.holding_id takes when an organization joins
// the holding.
LockCompanyQuotaHolding(ctx context.Context, holdingID pgtype.UUID) (pgtype.UUID, error)
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
// Writers lock the organization first, then invitation/card-view state, and
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
// Writers lock the organization first, then, for an E0 organization, the holding
// whose pool it shares, then invitation/card-view state, and finally usage rows.
// The organization lock serializes quota decisions for the tenant, the holding
// lock serializes the E0 pool across the organizations of one holding, and
// together they make the subsequent count and insert atomic.
// Takes the organization lock ahead of every share lock of a reader that will
// reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR
// SHARE, so readers of one organization queue up instead of deadlocking on a
@@ -752,8 +790,9 @@ type Querier interface {
// FOR KEY SHARE that a foreign key takes, such as the hidden-organization
// insert of a candidate, which holds the candidate's row and then needs this
// one. The reservation itself still takes FOR UPDATE inside the same
// transaction.
LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (pgtype.UUID, error)
// 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)
// 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.
@@ -1086,7 +1125,7 @@ type Querier interface {
// follow it). No row returns for a stale version, an account that is no
// active manager, or an unknown organization; the adapter reads the
// membership to tell them apart.
UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error)
UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (UpdateOrganizationProfileRow, error)
// Replaces the registration of an unverified account and advances the
// registration version in the same statement, so no caller can choose it.
// The version check rejects a writer that read an older row; a verified
+2 -1
View File
@@ -14,6 +14,7 @@ import (
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/companyquota"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/invitation"
"lincodex/backend/internal/usecase/notification"
@@ -70,7 +71,7 @@ func newInvitationHandler(
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: notifier, Clock: time.Now,
Notifier: notifier, Consents: consent.NewService(transactor, time.Now), Clock: time.Now,
})
if err != nil {
pool.Close()
+12 -1
View File
@@ -18,10 +18,21 @@ var (
ErrCompanyQuotaDenied = errors.New("company quota denied")
)
// SharesHoldingPool reports whether the usage of an organization at this tier
// is counted in the pool of its holding instead of its own. Only the
// unverified tier E0 shares a pool: the organizations of one holding at E0
// draw on one allowance, so creating more of them does not multiply it. A
// verified tier keeps its own pool, and usage of any organization that is no
// longer E0 leaves the shared pool.
func (tier OrganizationTier) SharesHoldingPool() bool {
return tier == OrganizationTierE0
}
// CompanyQuota is an immutable snapshot of the limits that apply to one
// organization at one instant. It carries the stored verification and
// effective policy identities so the transactional repository can verify
// that neither changed before it reserves usage.
// that neither changed before it reserves usage. Its usage scope is the
// organization, or the holding pool for a tier that SharesHoldingPool.
type CompanyQuota struct {
organizationID uuid.UUID
policyVersionID PolicyVersionID
+339
View File
@@ -0,0 +1,339 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"slices"
"time"
"github.com/google/uuid"
)
var (
// ErrInvalidContactGrant reports a grant that breaks a rule of the contact
// grant or does not agree with the accepted invitation and its C4 record.
ErrInvalidContactGrant = errors.New("invalid contact grant")
)
// ContactRevocationReason says why a contact grant was revoked. It is shown
// only to the candidate. The revocation itself belongs to a later operation.
type ContactRevocationReason string
const (
// ContactRevocationConsentRevoked closes every grant under a revoked C4.
ContactRevocationConsentRevoked ContactRevocationReason = "consent_revoked"
// ContactRevocationParticipationCancelled closes the grant of one
// invitation that the candidate cancelled.
ContactRevocationParticipationCancelled ContactRevocationReason = "participation_cancelled"
// ContactRevocationVisibilityClosed closes a grant after the publication
// was closed or the organization was hidden.
ContactRevocationVisibilityClosed ContactRevocationReason = "visibility_closed"
)
func (reason ContactRevocationReason) known() bool {
switch reason {
case ContactRevocationConsentRevoked, ContactRevocationParticipationCancelled, ContactRevocationVisibilityClosed:
return true
default:
return false
}
}
// ContactAccessBlock says why an active grant does not allow a read now.
type ContactAccessBlock string
// ContactAccessBlockVisibility means the profile is not published (C2) or is
// hidden from the organization. The acceptance never publishes the profile or
// lifts the hiding, so the grant becomes readable only when the candidate does.
const ContactAccessBlockVisibility ContactAccessBlock = "visibility"
// ContactGrantStatus is the state of a contact grant.
type ContactGrantStatus string
const (
ContactGrantActive ContactGrantStatus = "active"
ContactGrantRevoked ContactGrantStatus = "revoked"
)
const redactedContactGrant = "[redacted contact grant]"
// ContactGrant is the permission of one organization to read the selected
// contact kinds of one candidate, created by the acceptance of one invitation.
// It names the C4 consent record that gave it, so the grant and its consent
// always agree. The candidate identifier is internal and never logged.
type ContactGrant struct {
id uuid.UUID
organizationID uuid.UUID
candidateID uuid.UUID
invitationID uuid.UUID
consentRecordID uuid.UUID
fields ContactFieldSet
termsVersion int64
consentTextVersion ConsentTextVersion
grantedAt time.Time
revokedAt time.Time
revocationReason ContactRevocationReason
}
// StoredContactGrant carries the columns of a stored grant. A nil RevokedAt
// marks an active grant, and an empty RevocationReason goes with it.
type StoredContactGrant struct {
ID uuid.UUID
OrganizationID uuid.UUID
CandidateID uuid.UUID
InvitationID uuid.UUID
ConsentRecordID uuid.UUID
TermsVersion int64
Fields []string
ConsentTextVersion string
GrantedAt time.Time
RevokedAt *time.Time
RevocationReason string
}
// NewContactGrant builds the grant of an accepted invitation from its C4
// consent record. The record and the invitation must name the same subject,
// organization, invitation, and terms version, and the invitation must be
// accepted. The grant takes the fields, the text version, and the grant time
// of the record, so it covers exactly what the candidate consented to.
func NewContactGrant(record ConsentRecord, invitation Invitation) (ContactGrant, error) {
const location = "domain.NewContactGrant"
if record.Purpose() != ConsentPurposeContactDisclosure || record.Source() != ConsentSourceInvitationAcceptance {
return ContactGrant{}, fmt.Errorf("%s - the grant needs the C4 record of an acceptance: %w", location, ErrInvalidContactGrant)
}
if _, revoked := record.RevokedAt(); revoked {
return ContactGrant{}, fmt.Errorf("%s - a revoked C4 record gives no grant: %w", location, ErrInvalidContactGrant)
}
if invitation.State() != InvitationAccepted {
return ContactGrant{}, fmt.Errorf("%s - only an accepted invitation has a grant: %w", location, ErrInvalidContactGrant)
}
switch {
case record.OrganizationID() != invitation.OrganizationID(),
record.InvitationID() != invitation.ID(),
record.SubjectID() != invitation.CandidateID(),
record.InvitationTermsVersion() != invitation.TermsVersion():
return ContactGrant{}, fmt.Errorf("%s - the C4 record must name the accepted invitation: %w", location, ErrInvalidContactGrant)
case record.Fields().IsZero():
return ContactGrant{}, fmt.Errorf("%s - the C4 record must name its fields: %w", location, ErrInvalidContactGrant)
}
id, err := uuid.NewV7()
if err != nil {
return ContactGrant{}, fmt.Errorf("%s - generate grant ID: %w", location, err)
}
return ContactGrant{
id: id,
organizationID: invitation.OrganizationID(),
candidateID: invitation.CandidateID(),
invitationID: invitation.ID(),
consentRecordID: record.ID(),
fields: record.Fields(),
termsVersion: invitation.TermsVersion(),
consentTextVersion: record.TextVersion(),
grantedAt: record.GrantedAt(),
}, nil
}
// RestoreContactGrant validates a stored grant, so a row changed outside the
// application is not served.
func RestoreContactGrant(stored StoredContactGrant) (ContactGrant, error) {
const location = "domain.RestoreContactGrant"
switch {
case stored.ID == uuid.Nil, stored.OrganizationID == uuid.Nil, stored.CandidateID == uuid.Nil,
stored.InvitationID == uuid.Nil, stored.ConsentRecordID == uuid.Nil:
return ContactGrant{}, fmt.Errorf("%s - identifiers must be set: %w", location, ErrInvalidContactGrant)
case stored.TermsVersion < 1, stored.GrantedAt.IsZero():
return ContactGrant{}, fmt.Errorf("%s - terms version and grant time must be set: %w", location, ErrInvalidContactGrant)
}
fields, err := restoreGrantFields(stored.Fields)
if err != nil {
return ContactGrant{}, fmt.Errorf("%s - validate fields: %w", location, err)
}
version, err := ParseConsentTextVersion(stored.ConsentTextVersion)
if err != nil {
return ContactGrant{}, fmt.Errorf("%s - validate consent text version: %w", location, err)
}
grant := ContactGrant{
id: stored.ID, organizationID: stored.OrganizationID, candidateID: stored.CandidateID,
invitationID: stored.InvitationID, consentRecordID: stored.ConsentRecordID, fields: fields,
termsVersion: stored.TermsVersion, consentTextVersion: version, grantedAt: stored.GrantedAt,
}
switch {
case stored.RevokedAt == nil && stored.RevocationReason == "":
case stored.RevokedAt != nil && ContactRevocationReason(stored.RevocationReason).known() &&
!stored.RevokedAt.Before(stored.GrantedAt):
grant.revokedAt = *stored.RevokedAt
grant.revocationReason = ContactRevocationReason(stored.RevocationReason)
default:
return ContactGrant{}, fmt.Errorf("%s - the revocation stamp is inconsistent: %w", location, ErrInvalidContactGrant)
}
return grant, nil
}
// restoreGrantFields accepts the stored kinds only in the canonical form the
// database stores: distinct, known, and ascending.
func restoreGrantFields(stored []string) (ContactFieldSet, error) {
fields := make([]ContactField, 0, len(stored))
for _, value := range stored {
field, err := ParseContactField(value)
if err != nil {
return ContactFieldSet{}, err
}
fields = append(fields, field)
}
set, err := NewContactFieldSet(fields...)
if err != nil {
return ContactFieldSet{}, err
}
if !slices.Equal(contactFieldCodes(set), stored) {
return ContactFieldSet{}, fmt.Errorf("stored fields are not in canonical order: %w", ErrInvalidContactGrant)
}
return set, nil
}
func (grant ContactGrant) ID() uuid.UUID { return grant.id }
func (grant ContactGrant) OrganizationID() uuid.UUID { return grant.organizationID }
func (grant ContactGrant) CandidateID() uuid.UUID { return grant.candidateID }
func (grant ContactGrant) InvitationID() uuid.UUID { return grant.invitationID }
func (grant ContactGrant) ConsentRecordID() uuid.UUID { return grant.consentRecordID }
func (grant ContactGrant) Fields() ContactFieldSet { return grant.fields }
func (grant ContactGrant) TermsVersion() int64 { return grant.termsVersion }
func (grant ContactGrant) ConsentTextVersion() ConsentTextVersion { return grant.consentTextVersion }
func (grant ContactGrant) GrantedAt() time.Time { return grant.grantedAt }
// RevokedAt returns the revocation time, and false while the grant is active.
func (grant ContactGrant) RevokedAt() (time.Time, bool) {
return grant.revokedAt, !grant.revokedAt.IsZero()
}
// RevocationReason is empty while the grant is active.
func (grant ContactGrant) RevocationReason() ContactRevocationReason { return grant.revocationReason }
// Status is revoked once a revocation stamp is set; a grant never becomes
// active again.
func (grant ContactGrant) Status() ContactGrantStatus {
if grant.revokedAt.IsZero() {
return ContactGrantActive
}
return ContactGrantRevoked
}
// IsZero reports a grant not built by NewContactGrant or RestoreContactGrant.
func (grant ContactGrant) IsZero() bool { return grant.id == uuid.Nil }
// Stored returns the persisted form of the grant.
func (grant ContactGrant) Stored() StoredContactGrant {
stored := StoredContactGrant{
ID: grant.id, OrganizationID: grant.organizationID, CandidateID: grant.candidateID,
InvitationID: grant.invitationID, ConsentRecordID: grant.consentRecordID,
TermsVersion: grant.termsVersion, Fields: contactFieldCodes(grant.fields),
ConsentTextVersion: string(grant.consentTextVersion), GrantedAt: grant.grantedAt,
RevocationReason: string(grant.revocationReason),
}
if !grant.revokedAt.IsZero() {
revokedAt := grant.revokedAt
stored.RevokedAt = &revokedAt
}
return stored
}
// ContactGrantView is the grant as the candidate reads it. It holds kinds
// only, never contact values, and it names no organization identifier. The
// organization reads it through its own view.
type ContactGrantView struct {
ID uuid.UUID
Fields []ContactField
Status ContactGrantStatus
Readable bool
BlockedBy *ContactAccessBlock
TermsVersion int64
ConsentTextVersion ConsentTextVersion
GrantedAt time.Time
RevokedAt *time.Time
RevocationReason *ContactRevocationReason
}
// CandidateView returns the grant for the candidate. visible reports whether
// the organization may read the profile now, which is the publication and the
// hiding of the organization. An active grant is readable only when it is
// visible; a revoked grant is never readable and shows its reason instead.
func (grant ContactGrant) CandidateView(visible bool) ContactGrantView {
view := ContactGrantView{
ID: grant.id, Fields: grant.fields.Fields(), Status: grant.Status(),
TermsVersion: grant.termsVersion, ConsentTextVersion: grant.consentTextVersion, GrantedAt: grant.grantedAt,
}
if view.Status == ContactGrantRevoked {
revokedAt, reason := grant.revokedAt, grant.revocationReason
view.RevokedAt, view.RevocationReason = &revokedAt, &reason
return view
}
if visible {
view.Readable = true
return view
}
block := ContactAccessBlockVisibility
view.BlockedBy = &block
return view
}
func (grant ContactGrant) String() string { return redactedContactGrant }
func (grant ContactGrant) GoString() string { return redactedContactGrant }
func (grant ContactGrant) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedContactGrant)
}
// LogValue carries the grant identifier and its status only.
func (grant ContactGrant) LogValue() slog.Value {
return slog.GroupValue(slog.String("grant_id", grant.id.String()), slog.String("status", string(grant.Status())))
}
// ContactConsentText is the published C4 text that the candidate sees, with
// the organization name in it.
type ContactConsentText struct {
TextVersion ConsentTextVersion
Text string
}
// ContactConsentOffer is what the candidate can consent to while an
// acceptance is possible: the rendered text and the kinds the profile holds.
// Nothing is preselected, and no contact value is part of it.
type ContactConsentOffer struct {
Text ContactConsentText
AvailableFields []ContactField
}
// NewContactConsentOffer renders the C4 text for the organization name and
// lists the kinds that the profile holds, in the order given. It needs at least
// one kind, because a grant covers at least one field.
func NewContactConsentOffer(text ConsentText, organizationName string, available []ContactField) (ContactConsentOffer, error) {
const location = "domain.NewContactConsentOffer"
if len(available) == 0 || len(available) > maxContactFields {
return ContactConsentOffer{}, fmt.Errorf("%s - the offer needs 1 to %d kinds: %w", location, maxContactFields, ErrInvalidContactGrant)
}
for index, field := range available {
if _, err := ParseContactField(string(field)); err != nil {
return ContactConsentOffer{}, fmt.Errorf("%s - validate kind: %w", location, err)
}
if slices.Contains(available[:index], field) {
return ContactConsentOffer{}, fmt.Errorf("%s - kinds must be distinct: %w", location, ErrInvalidContactGrant)
}
}
rendered, err := text.RenderForOrganization(organizationName)
if err != nil {
return ContactConsentOffer{}, fmt.Errorf("%s - render consent text: %w", location, err)
}
return ContactConsentOffer{
Text: ContactConsentText{TextVersion: text.Version(), Text: rendered},
AvailableFields: slices.Clone(available),
}, nil
}
// contactFieldCodes returns the kinds of a set as the stored strings, in the
// set's canonical order.
func contactFieldCodes(set ContactFieldSet) []string {
codes := make([]string, 0, len(set.Fields()))
for _, field := range set.Fields() {
codes = append(codes, string(field))
}
return codes
}
@@ -0,0 +1,242 @@
package domain
import (
"errors"
"fmt"
"slices"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
const testContactTextBody = "I consent to the transfer of the contact data I select to {organization} for this invitation."
// testContactText is the published C4 text of the domain tests.
func testContactText(t *testing.T) ConsentText {
t.Helper()
hash := HashConsentText(testContactTextBody)
text, err := RestoreConsentText(StoredConsentText{
Purpose: string(ConsentPurposeContactDisclosure), Version: "c4-2026-10-01", Body: testContactTextBody,
Hash: hash[:], Kind: string(ConsentTextKindDemo), PublishedAt: time.Date(2026, time.October, 1, 0, 0, 0, 0, time.UTC),
})
if err != nil {
t.Fatalf("RestoreConsentText() error = %v", err)
}
return text
}
// acceptedTestInvitation accepts the delivered test invitation an hour after
// its delivery, from its delivered state and at its current terms version.
func acceptedTestInvitation(t *testing.T) (Invitation, time.Time) {
t.Helper()
delivered, _ := deliveredTestInvitation(t)
at := delivered.UpdatedAt().Add(time.Hour)
accepted, err := delivered.Accept(delivered.TermsVersion(), at)
if err != nil {
t.Fatalf("Accept() error = %v", err)
}
return accepted, at
}
// testConsentRecordFor stores the C4 record of an acceptance the way the ledger
// does: the hash of the text with the organization name filled in.
func testStoredConsentRecord(t *testing.T, invitation Invitation, granted time.Time, fields ...string) StoredConsentRecord {
t.Helper()
shown, err := testContactText(t).RenderForOrganization("Acme")
if err != nil {
t.Fatalf("RenderForOrganization() error = %v", err)
}
hash := HashConsentText(shown)
return StoredConsentRecord{
ID: uuid.Must(uuid.NewV7()), SubjectID: invitation.CandidateID(), Purpose: string(ConsentPurposeContactDisclosure),
TextVersion: "c4-2026-10-01", TextHash: hash[:], Source: string(ConsentSourceInvitationAcceptance),
State: string(ConsentStateActive), GrantedAt: granted, OrganizationID: invitation.OrganizationID(),
OrganizationName: "Acme", FieldSet: fields, InvitationID: invitation.ID(), InvitationTermsVersion: invitation.TermsVersion(),
}
}
// testConsentRecordFor restores the stored C4 record of an acceptance.
func testConsentRecordFor(t *testing.T, invitation Invitation, granted time.Time, fields ...string) ConsentRecord {
t.Helper()
record, err := RestoreConsentRecord(testStoredConsentRecord(t, invitation, granted, fields...))
if err != nil {
t.Fatalf("RestoreConsentRecord() error = %v", err)
}
return record
}
func TestNewContactGrantCoversExactlyTheRecordedFields(t *testing.T) {
accepted, at := acceptedTestInvitation(t)
record := testConsentRecordFor(t, accepted, at, "email")
grant, err := NewContactGrant(record, accepted)
if err != nil {
t.Fatalf("NewContactGrant() error = %v", err)
}
if grant.OrganizationID() != accepted.OrganizationID() || grant.InvitationID() != accepted.ID() ||
grant.CandidateID() != accepted.CandidateID() || grant.ConsentRecordID() != record.ID() ||
grant.TermsVersion() != accepted.TermsVersion() || grant.ConsentTextVersion() != "c4-2026-10-01" ||
!grant.GrantedAt().Equal(at) || grant.Status() != ContactGrantActive {
t.Fatalf("grant = %+v, want the scope of the accepted invitation and its record", grant.Stored())
}
if fields := grant.Fields().Fields(); len(fields) != 1 || fields[0] != ContactFieldEmail {
t.Fatalf("fields = %v, want the email only", fields)
}
if _, revoked := grant.RevokedAt(); revoked {
t.Fatal("a new grant is revoked")
}
restored, err := RestoreContactGrant(grant.Stored())
if err != nil || restored.ID() != grant.ID() || !restored.Fields().Equal(grant.Fields()) {
t.Fatalf("RestoreContactGrant(stored) = %+v, %v; want the same grant", restored.Stored(), err)
}
}
func TestNewContactGrantNeedsAnAcceptedInvitationAndItsOwnRecord(t *testing.T) {
accepted, at := acceptedTestInvitation(t)
delivered, _ := deliveredTestInvitation(t)
if _, err := NewContactGrant(testConsentRecordFor(t, delivered, at, "email"), delivered); !errors.Is(err, ErrInvalidContactGrant) {
t.Fatalf("grant of a delivered invitation error = %v, want ErrInvalidContactGrant", err)
}
otherInvitation := testConsentRecordFor(t, delivered, at, "email")
if _, err := NewContactGrant(otherInvitation, accepted); !errors.Is(err, ErrInvalidContactGrant) {
t.Fatalf("grant with another invitation's record error = %v, want ErrInvalidContactGrant", err)
}
stored := testStoredConsentRecord(t, accepted, at, "email")
stored.RevokedAt = &at
stored.RevocationSource = string(ConsentRevocationSourceConsentSettings)
stored.State = string(ConsentStateRevoked)
revoked, err := RestoreConsentRecord(stored)
if err != nil {
t.Fatalf("RestoreConsentRecord(revoked) error = %v", err)
}
if _, err := NewContactGrant(revoked, accepted); !errors.Is(err, ErrInvalidContactGrant) {
t.Fatalf("grant of a revoked record error = %v, want ErrInvalidContactGrant", err)
}
}
func TestContactGrantShowsWhetherTheOrganizationCanReadItNow(t *testing.T) {
accepted, at := acceptedTestInvitation(t)
grant, err := NewContactGrant(testConsentRecordFor(t, accepted, at, "email"), accepted)
if err != nil {
t.Fatalf("NewContactGrant() error = %v", err)
}
if view := grant.CandidateView(true); !view.Readable || view.BlockedBy != nil || view.Status != ContactGrantActive {
t.Fatalf("visible view = %+v, want readable and not blocked", view)
}
view := grant.CandidateView(false)
if view.Readable || view.BlockedBy == nil || *view.BlockedBy != ContactAccessBlockVisibility {
t.Fatalf("hidden view = %+v, want blocked by visibility", view)
}
revokedAt := at.Add(time.Hour)
revoked, err := RestoreContactGrant(StoredContactGrant{
ID: grant.ID(), OrganizationID: grant.OrganizationID(), CandidateID: grant.CandidateID(), InvitationID: grant.InvitationID(),
ConsentRecordID: grant.ConsentRecordID(), TermsVersion: grant.TermsVersion(), Fields: []string{"email"},
ConsentTextVersion: "c4-2026-10-01", GrantedAt: at, RevokedAt: &revokedAt, RevocationReason: string(ContactRevocationConsentRevoked),
})
if err != nil {
t.Fatalf("RestoreContactGrant(revoked) error = %v", err)
}
closed := revoked.CandidateView(true)
if closed.Readable || closed.BlockedBy != nil || closed.Status != ContactGrantRevoked || closed.RevokedAt == nil ||
!closed.RevokedAt.Equal(revokedAt) || closed.RevocationReason == nil || *closed.RevocationReason != ContactRevocationConsentRevoked {
t.Fatalf("revoked view = %+v, want closed with its reason and no read", closed)
}
}
func TestRestoreContactGrantRefusesNonCanonicalFieldsAndBrokenRevocation(t *testing.T) {
accepted, at := acceptedTestInvitation(t)
valid := StoredContactGrant{
ID: uuid.Must(uuid.NewV7()), OrganizationID: accepted.OrganizationID(), CandidateID: accepted.CandidateID(),
InvitationID: accepted.ID(), ConsentRecordID: uuid.Must(uuid.NewV7()), TermsVersion: accepted.TermsVersion(),
Fields: []string{"email", "phone"}, ConsentTextVersion: "c4-2026-10-01", GrantedAt: at,
}
if _, err := RestoreContactGrant(valid); err != nil {
t.Fatalf("RestoreContactGrant(valid) error = %v", err)
}
reversed := valid
reversed.Fields = []string{"phone", "email"}
beforeGrant := valid
beforeGrant.RevokedAt = ptrTime(at.Add(-time.Minute))
beforeGrant.RevocationReason = string(ContactRevocationVisibilityClosed)
noReason := valid
noReason.RevokedAt = ptrTime(at.Add(time.Minute))
unknownKind := valid
unknownKind.Fields = []string{"address"}
for name, stored := range map[string]StoredContactGrant{
"reversed fields": reversed,
"unknown kind": unknownKind,
"revocation before grant": beforeGrant,
"revocation without a reason": noReason,
} {
if _, err := RestoreContactGrant(stored); !errors.Is(err, ErrInvalidContactGrant) && !errors.Is(err, ErrInvalidConsent) {
t.Errorf("%s: RestoreContactGrant() error = %v, want a refusal", name, err)
}
}
}
func ptrTime(value time.Time) *time.Time { return &value }
func TestInvitationAcceptsOnlyTheCurrentTermsFromAnAnswerableState(t *testing.T) {
delivered, _ := deliveredTestInvitation(t)
at := delivered.UpdatedAt().Add(time.Hour)
if _, err := delivered.Accept(delivered.TermsVersion()+1, at); !errors.Is(err, ErrInvitationVersionConflict) {
t.Fatalf("stale terms error = %v, want ErrInvitationVersionConflict", err)
}
counter := withState(t, delivered, InvitationCounter, nil)
if _, err := counter.Accept(counter.TermsVersion(), at); !errors.Is(err, ErrInvitationNotAnswerable) {
t.Fatalf("counter error = %v, want ErrInvitationNotAnswerable", err)
}
if _, err := delivered.Accept(delivered.TermsVersion(), *delivered.Snapshot().ResponseDeadlineAt); !errors.Is(err, ErrInvitationNotAnswerable) {
t.Fatalf("accept at the deadline error = %v, want ErrInvitationNotAnswerable", err)
}
viewed, _, err := delivered.RecordView(at)
if err != nil {
t.Fatalf("RecordView() error = %v", err)
}
accepted, err := viewed.Accept(viewed.TermsVersion(), at.Add(time.Minute))
if err != nil {
t.Fatalf("Accept(viewed) error = %v", err)
}
snapshot := accepted.Snapshot()
if snapshot.State != InvitationAccepted || snapshot.Version != viewed.Version()+1 || snapshot.RespondedAt == nil ||
!snapshot.ResponseDeadlineAt.Equal(*delivered.Snapshot().ResponseDeadlineAt) {
t.Fatalf("accepted = %+v, want the next version accepted with the deadline kept", snapshot)
}
event, err := accepted.AnswerEvent(delivered.CandidateID())
if err != nil || event.Kind != InvitationEventAccepted || len(event.ChangedFields) != 0 {
t.Fatalf("AnswerEvent() = %+v, %v; want an accepted event naming no field", event, err)
}
}
func TestNewContactConsentOfferRendersTheTextAndListsTheHeldKinds(t *testing.T) {
offer, err := NewContactConsentOffer(testContactText(t), "Acme", []ContactField{ContactFieldFullName, ContactFieldEmail})
if err != nil {
t.Fatalf("NewContactConsentOffer() error = %v", err)
}
if !strings.Contains(offer.Text.Text, "Acme") || strings.Contains(offer.Text.Text, ConsentTextOrganizationPlaceholder) ||
offer.Text.TextVersion != "c4-2026-10-01" || !slices.Equal(offer.AvailableFields, []ContactField{ContactFieldFullName, ContactFieldEmail}) {
t.Fatalf("offer = %+v, want the rendered text and the kinds in the given order", offer)
}
if _, err := NewContactConsentOffer(testContactText(t), "Acme", nil); !errors.Is(err, ErrInvalidContactGrant) {
t.Fatalf("empty offer error = %v, want ErrInvalidContactGrant", err)
}
if _, err := NewContactConsentOffer(testContactText(t), "Acme", []ContactField{ContactFieldEmail, ContactFieldEmail}); !errors.Is(err, ErrInvalidContactGrant) {
t.Fatalf("repeated kind error = %v, want ErrInvalidContactGrant", err)
}
}
func TestContactGrantValuesAreRedacted(t *testing.T) {
accepted, at := acceptedTestInvitation(t)
grant, err := NewContactGrant(testConsentRecordFor(t, accepted, at, "email"), accepted)
if err != nil {
t.Fatalf("NewContactGrant() error = %v", err)
}
for _, rendered := range []string{fmt.Sprint(grant), fmt.Sprintf("%+v", grant), fmt.Sprintf("%#v", grant)} {
if strings.Contains(rendered, accepted.CandidateID().String()) || strings.Contains(rendered, "email") {
t.Fatalf("rendered grant = %q, want the identifier and the kinds hidden", rendered)
}
}
}
+49
View File
@@ -0,0 +1,49 @@
package domain
import (
"errors"
"fmt"
"time"
"github.com/google/uuid"
)
// ErrInvalidHolding reports a holding that was not built with a founder
// account and a creation time.
var ErrInvalidHolding = errors.New("invalid holding")
// Holding groups the organizations that one founder account created, as the
// divisions of one company belong to one parent. It carries no profile and no
// right: its only effect is the E0 quota pool that its organizations share.
// Organizations of one account are grouped; cross-owner merges are not
// modelled.
type Holding struct {
id uuid.UUID
founderAccountID uuid.UUID
createdAt time.Time
}
// NewHolding creates the holding of a founder account with a time-ordered
// UUIDv7 identifier. The storage keeps one holding per founder and returns the
// stored one when the account already has it, so the identifier of this value
// is only used when the holding is new.
func NewHolding(founderAccountID uuid.UUID, createdAt time.Time) (Holding, error) {
const location = "domain.NewHolding"
if founderAccountID == uuid.Nil {
return Holding{}, fmt.Errorf("%s - founder account must be set: %w", location, ErrInvalidHolding)
}
if createdAt.IsZero() {
return Holding{}, fmt.Errorf("%s - creation time must be set: %w", location, ErrInvalidHolding)
}
id, err := uuid.NewV7()
if err != nil {
return Holding{}, fmt.Errorf("%s - generate holding ID: %w", location, err)
}
return Holding{id: id, founderAccountID: founderAccountID, createdAt: createdAt.UTC()}, nil
}
func (holding Holding) ID() uuid.UUID { return holding.id }
func (holding Holding) FounderAccountID() uuid.UUID { return holding.founderAccountID }
func (holding Holding) CreatedAt() time.Time { return holding.createdAt }
+55 -4
View File
@@ -27,6 +27,9 @@ const (
// candidate's answer for the responsiveness metrics, never a consent or
// a hire, and it holds neither the reason nor the comment.
InvitationEventDeclined InvitationEventKind = "declined"
// InvitationEventAccepted is the audit event of an acceptance. It names no
// field: the consent C4 and the grant are stored in their own records.
InvitationEventAccepted InvitationEventKind = "accepted"
)
const (
@@ -46,6 +49,7 @@ var (
// answerEventKinds name the audit event of each answer state.
answerEventKinds = map[InvitationState]InvitationEventKind{
InvitationViewed: InvitationEventViewed, InvitationDeclined: InvitationEventDeclined,
InvitationAccepted: InvitationEventAccepted,
}
)
@@ -234,8 +238,44 @@ func (invitation Invitation) Decline(choice InvitationDeclineChoice, at time.Tim
return declined, decline, nil
}
// AnswerEvent builds the audit event of the version that a view or a
// decline by actor has just produced. It names no field and holds neither
// Accept returns the next version in the state accepted. The candidate may
// accept a delivered or viewed invitation before its deadline and only at the
// terms version that the candidate read; any other state, a late command, and
// a stale terms version are refused. The deadline and the terms are kept. The
// consent C4, the contact grant, and the audit event belong to the same
// transaction and are built by the caller.
func (invitation Invitation) Accept(termsVersion int64, at time.Time) (Invitation, error) {
const location = "Invitation.Accept"
if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) {
return Invitation{}, fmt.Errorf("%s - accept time must be set and not before the last change: %w", location, ErrInvalidInvitation)
}
if !invitation.acceptable() || !invitation.IsDelivered() || invitation.ResponseDeadlinePassed(at) {
return Invitation{}, fmt.Errorf("%s - %w", location, ErrInvitationNotAnswerable)
}
if termsVersion != invitation.record.TermsVersion {
return Invitation{}, fmt.Errorf("%s - the candidate read another terms version: %w", location, ErrInvitationVersionConflict)
}
at = at.UTC()
next := invitation.Stored()
next.State = string(InvitationAccepted)
next.Version++
next.UpdatedAt = at
next.RespondedAt = &at
accepted, err := RestoreInvitation(next)
if err != nil {
return Invitation{}, fmt.Errorf("%s - restore accepted invitation: %w", location, err)
}
return accepted, nil
}
// acceptable reports the states from which the candidate may accept: the
// delivered and viewed invitation. The planned counter offer is not one.
func (invitation Invitation) acceptable() bool {
return invitation.State() == InvitationDelivered || invitation.State() == InvitationViewed
}
// AnswerEvent builds the audit event of the version that a view, a decline,
// or an acceptance by actor has just produced. It names no field and holds neither
// the reason nor the comment of a decline.
func (invitation Invitation) AnswerEvent(actorID uuid.UUID) (InvitationEvent, error) {
const location = "Invitation.AnswerEvent"
@@ -257,6 +297,12 @@ func (invitation Invitation) AnswerEvent(actorID uuid.UUID) (InvitationEvent, er
}, nil
}
// answeredInvitationState reports the states that record the candidate's answer:
// a declined or an accepted invitation has its answer time.
func answeredInvitationState(state InvitationState) bool {
return state == InvitationDeclined || state == InvitationAccepted
}
// storedInvitationAnswerDefect checks the view and the answer against the
// state: a delivered invitation has neither, a viewed one has its view, a
// declined one has its answer, and neither precedes the delivery.
@@ -267,8 +313,8 @@ func storedInvitationAnswerDefect(stored StoredInvitation) string {
return "a delivered invitation has no view or answer"
case state == InvitationViewed && (stored.ViewedAt == nil || stored.RespondedAt != nil):
return "a viewed invitation has a view and no answer"
case state == InvitationDeclined && stored.RespondedAt == nil:
return "a declined invitation has an answer"
case answeredInvitationState(state) && stored.RespondedAt == nil:
return "a declined or accepted invitation has an answer"
case stored.ViewedAt != nil && (stored.DeliveredAt == nil || stored.ViewedAt.Before(*stored.DeliveredAt)):
return "a view follows the delivery"
case stored.RespondedAt != nil && (stored.DeliveredAt == nil || stored.RespondedAt.Before(*stored.DeliveredAt)):
@@ -305,6 +351,11 @@ type CandidateInvitationView struct {
RespondedAt *time.Time
UpdatedAt time.Time
Decline *InvitationDeclineView
// ContactConsent is set while an acceptance is possible, and ContactGrant
// once the invitation was accepted. The usecase fills both: they need the
// profile, the consent texts, and the visibility, which the view does not.
ContactConsent *ContactConsentOffer
ContactGrant *ContactGrantView
}
// CandidateView returns the invitation for the candidate it is addressed to.
+28 -18
View File
@@ -28,12 +28,18 @@ type CompanyQuotaDecision struct {
// creates the invitation or applies the visibility change in the same
// transaction, so a failed business operation cannot leave quota charged.
//
// Writers lock rows in this order: organization, active membership,
// invitation or visibility record, then quota usage. A repository may take an
// organization lock again inside the same transaction, but must not invert
// this order. Each method rechecks the organization's stored verification
// level, basis, and changed_at against the snapshot in CompanyQuota before it
// writes; a caller cannot grant itself a tier by supplying a different level.
// Writers lock rows in this order: organization, then for an E0 organization
// its holding, then active membership, invitation or visibility record, and
// last quota usage. A repository may take an organization lock again inside
// the same transaction, but must not invert this order. Each method rechecks
// the organization's stored verification level, basis, and changed_at against
// the snapshot in CompanyQuota before it writes; a caller cannot grant itself
// a tier by supplying a different level.
//
// The E0 limits are pooled per holding: the usage of every E0 organization of
// one holding counts toward the same window. Usage rows stay attributed to the
// organization that consumed them, and idempotency stays per organization.
// Organizations at E1 and above count only their own usage.
//
// Invitation usage is keyed by organization and invitation ID and remains
// until the organization is deleted. The unique key makes retries idempotent
@@ -49,24 +55,28 @@ type CompanyQuotaRepository interface {
// LockOrganization takes the organization lock that serializes the
// reservations of one organization (FOR NO KEY UPDATE, which does not block
// the foreign-key lock of a candidate's own hide), ahead of the share locks
// of a membership check. A
// caller that checks the membership first and reserves later would hold a
// share lock and then ask for the exclusive one, and two such callers of one
// organization deadlock. A caller that reserves after a share lock takes
// this lock first, in the documented order. It returns
// of a membership check. A caller that checks the membership first and
// reserves later would hold a share lock and then ask for the exclusive
// one, and two such callers of one organization deadlock. A caller that
// reserves after a share lock takes this lock first, in the documented
// order. For an E0 organization it also takes the lock of its holding,
// which serializes the shared E0 pool; the holding is locked right after
// the organization, before any other lock of the caller, so the callers of
// one holding cannot deadlock on it. It returns
// ErrCompanyQuotaSnapshotChanged for a removed organization.
LockOrganization(ctx context.Context, organizationID uuid.UUID) error
// ReserveInvitation counts a new invitation against the current policy
// limit. An existing invitation ID is returned as allowed and reused
// without a second charge, regardless of its age or the request key. A
// denied new invitation writes no usage and reports RetryAt after the
// earliest currently counted invitation expires.
// limit of the organization's usage scope. An existing invitation ID is
// returned as allowed and reused without a second charge, regardless of
// its age or the request key. A denied new invitation writes no usage and
// reports RetryAt after the earliest currently counted invitation expires.
ReserveInvitation(ctx context.Context, quota domain.CompanyQuota, invitationID uuid.UUID) (CompanyQuotaDecision, error)
// ReserveCardView counts a distinct candidate within the rolling card-view
// window. A repeat while the prior view is active is allowed and reused,
// and refreshes last_seen with a monotonic update. A denied new view writes
// no usage and reports RetryAt after the earliest active view expires.
// window of the organization's usage scope. A repeat while the prior view
// of the same organization is active is allowed and reused, and refreshes
// last_seen with a monotonic update. A denied new view writes no usage and
// reports RetryAt after the earliest active view expires.
ReserveCardView(ctx context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (CompanyQuotaDecision, error)
}
@@ -0,0 +1,29 @@
package outbound
import (
"context"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// ErrContactGrantNotFound reports that the invitation has no contact grant of
// the organization. An accepted invitation always has one, so a missing grant
// of an accepted invitation is a storage defect.
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.
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.
GetByInvitation(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.ContactGrant, error)
}
@@ -36,6 +36,10 @@ var (
// ErrInvitationDeclineResultNotFound reports a missing outcome of a
// decline for a live idempotency record.
ErrInvitationDeclineResultNotFound = errors.New("invitation decline result not found")
// ErrInvitationAcceptResultNotFound reports a missing outcome of an
// acceptance for a live idempotency record.
ErrInvitationAcceptResultNotFound = errors.New("invitation accept result not found")
)
// MaxInvitationPageSize is the largest organization-scoped or candidate page
@@ -49,6 +53,8 @@ type InvitationRepositories interface {
InvitationCreationResults() InvitationCreationResultRepository
InvitationSendResults() InvitationSendResultRepository
InvitationDeclineResults() InvitationDeclineResultRepository
InvitationAcceptResults() InvitationAcceptResultRepository
ContactGrants() ContactGrantRepository
}
// InvitationRepository stores invitations, their immutable terms versions, and
@@ -130,6 +136,14 @@ type InvitationRepository interface {
// GetDecline returns the stored decline of the invitation or
// ErrInvitationDeclineNotFound.
GetDecline(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.InvitationDecline, error)
// Accept moves a delivered or viewed invitation from expectedVersion to the
// accepted version of next before its deadline, keeps the deadline and the
// terms, and records the audit event. It returns
// ErrInvitationVersionConflict when the stored row is not answerable at
// 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
}
// InvitationCreationResultRepository stores the original response of a
@@ -246,3 +260,30 @@ type InvitationDeclineResultRepository interface {
SaveDeclineResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result InvitationDeclineResult) error
GetDeclineResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (InvitationDeclineResult, error)
}
// InvitationAcceptOutcome is the stored result of an acceptance under an
// Idempotency-Key. The contract stores a success, a missing invitation, and a
// state conflict; a stale version and a consent refusal are not stored.
type InvitationAcceptOutcome string
const (
InvitationAcceptAccepted InvitationAcceptOutcome = "accepted"
InvitationAcceptNotFound InvitationAcceptOutcome = "not_found"
InvitationAcceptStateConflict InvitationAcceptOutcome = "state_conflict"
)
// InvitationAcceptResult is the outcome of one acceptance. It keeps no copy of
// the response: an accepted invitation keeps its answer and its grant, so a
// replay rebuilds the response from them.
type InvitationAcceptResult struct {
InvitationID uuid.UUID
Outcome InvitationAcceptOutcome
}
// InvitationAcceptResultRepository stores the outcome of an idempotent
// acceptance. The scope references the generic idempotency record, so the
// outcome is removed when that record is purged.
type InvitationAcceptResultRepository interface {
SaveAcceptResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result InvitationAcceptResult) error
GetAcceptResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (InvitationAcceptResult, error)
}
@@ -61,11 +61,14 @@ type OrganizationRepositories interface {
type OrganizationRepository interface {
// CreateWithOwner stores a new organization and the active owner
// membership of its creator. The two inserts run in the surrounding
// transaction, so a failure between them leaves neither. The database also
// refuses to commit an organization that has no active owner (constraint
// organizations_owner_required, SQLSTATE 23514, raised by the commit of
// the transaction), whatever code inserted it. owner must be an active
// owner membership of organization; an unknown account fails with
// transaction, so a failure between them leaves neither. The organization
// joins the holding of the owner account: the holding is created in the
// same transaction when that account has none, and an existing one is
// reused, so concurrent creations of one account end in one holding. The
// database also refuses to commit an organization that has no active owner
// (constraint organizations_owner_required, SQLSTATE 23514, raised by the
// commit of the transaction), whatever code inserted it. owner must be an
// active owner membership of organization; an unknown account fails with
// ErrUserNotFound, and the caller's transaction is aborted.
CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error
@@ -43,8 +43,9 @@ func NewService(clock func() time.Time) *Service {
}
// ReserveInvitation atomically records a new invitation against the policy
// effective at the operation's clock snapshot. Repeating invitationID is
// idempotent even when the caller uses a different request key.
// effective at the operation's clock snapshot. The limit applies to the usage
// scope of the organization: its own usage, or the holding pool at E0. Repeating
// invitationID is idempotent even when the caller uses a different request key.
func (service *Service) ReserveInvitation(
ctx context.Context,
repositories Repositories,
@@ -72,9 +73,10 @@ func (service *Service) ReserveInvitation(
return decision, nil
}
// ReserveCardView atomically counts a distinct candidate in the organization's
// rolling view window. A repeat within the window refreshes the stored time
// without charging another distinct view.
// ReserveCardView atomically counts a distinct candidate in the rolling view
// window of the organization's usage scope. A repeat within the window by the
// same organization refreshes the stored time without charging another distinct
// view.
func (service *Service) ReserveCardView(
ctx context.Context,
repositories Repositories,
@@ -0,0 +1,413 @@
package invitation
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/consent"
)
const (
acceptOperation = "candidate_invitation.accept"
acceptLocation = "invitation.Service.AcceptMine"
// consentTextPointer and consentFieldsPointer name the consent rules of
// the body in the problem response.
consentTextPointer = "/consent_c4/text_version"
consentFieldsPointer = "/consent_c4/fields"
)
// AcceptCommand binds the session candidate and the path to one acceptance:
// the invitation version and the terms version that the candidate read, the
// consent text version that the candidate saw, and the contact kinds that the
// candidate selected, in the order sent.
type AcceptCommand struct {
ActorID uuid.UUID
InvitationID uuid.UUID
IdempotencyKey string
ExpectedVersion int64
TermsVersion int64
TextVersion string
Fields []domain.ContactField
}
type acceptRequest struct {
fingerprint [outbound.IdempotencyDigestSize]byte
scope [outbound.IdempotencyDigestSize]byte
record outbound.IdempotencyRecord
now time.Time
textVersion domain.ConsentTextVersion
fields domain.ContactFieldSet
}
// acceptFingerprint is the canonical request of an acceptance. The fields keep
// their order, so a reordered choice is a different request under one key.
type acceptFingerprint struct {
InvitationID uuid.UUID `json:"invitation_id"`
ExpectedVersion int64 `json:"expected_version"`
TermsVersion int64 `json:"terms_version"`
TextVersion string `json:"text_version"`
Fields []domain.ContactField `json:"fields"`
}
// acceptOutcome is what a committed acceptance transaction decided: the
// invitation, or a refusal that the contract stores under the key and that the
// caller returns after the commit.
type acceptOutcome struct {
view domain.CandidateInvitationView
refusal error
}
// AcceptMine accepts the current terms of an invitation of the session
// candidate with the consent C4. In one transaction it checks the candidate,
// the key, the invitation, a repeat of the acceptance, a terminal state or a
// passed deadline, the versions, the state, and the consent rules; then it
// moves the invitation to accepted, records the consent C4 in the consent
// ledger, stores the contact grant of exactly the selected fields, and appends
// the audit event. The acceptance never publishes the profile and never lifts
// a hiding: the grant is readable only while the organization may read the
// profile.
//
// Locks: the idempotency record of the candidate's own key and then only the
// invitation row, never the organization, as for the other candidate commands.
func (service *Service) AcceptMine(ctx context.Context, command AcceptCommand) (domain.CandidateInvitationView, error) {
request, err := service.prepareAccept(command)
if err != nil {
return domain.CandidateInvitationView{}, err
}
var outcome acceptOutcome
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
outcome, err = service.acceptInTransaction(ctx, unit, command, request)
return err
})
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", acceptLocation, err)
}
if outcome.refusal != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - %w", acceptLocation, outcome.refusal)
}
return outcome.view, nil
}
// prepareAccept validates the request before any storage is read, in the order
// of the contract: the request is validated before the account.
func (service *Service) prepareAccept(command AcceptCommand) (acceptRequest, error) {
const location = "invitation.Service.prepareAccept"
switch {
case command.ActorID == uuid.Nil:
return acceptRequest{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden)
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
return acceptRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey)
case command.ExpectedVersion < 1:
return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"})
case command.TermsVersion < 1:
return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/terms_version", Reason: "must be positive"})
}
textVersion, err := domain.ParseConsentTextVersion(command.TextVersion)
if err != nil {
return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: consentTextPointer, Reason: "must be a consent text version"})
}
fields, err := domain.NewContactFieldSet(command.Fields...)
if err != nil {
return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: consentFieldsPointer, Reason: "must name one to four distinct kinds"})
}
now, err := service.now(location)
if err != nil {
return acceptRequest{}, err
}
canonical, err := json.Marshal(acceptFingerprint{
InvitationID: command.InvitationID, ExpectedVersion: command.ExpectedVersion, TermsVersion: command.TermsVersion,
TextVersion: command.TextVersion, Fields: command.Fields,
})
if err != nil {
return acceptRequest{}, fmt.Errorf("%s - encode canonical request: %w", location, err)
}
fingerprint := service.keyring.Fingerprint(canonical)
scope := service.keyring.IdempotencyScope(acceptOperation, command.IdempotencyKey, command.ActorID.String())
return acceptRequest{
fingerprint: fingerprint, scope: scope, now: now, textVersion: textVersion, fields: fields,
record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention)},
}, nil
}
// acceptInTransaction follows the order of checks of the contract after the
// HTTP boundary: the account (403), the key (422 or a replay), the invitation
// (404, stored), the repeat of an accepted invitation (200), a terminal state
// or a passed deadline (409, stored), the versions (412, not stored), any other
// state that does not allow an acceptance (409, stored), and the consent rules
// (400, not stored).
func (service *Service) acceptInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command AcceptCommand,
request acceptRequest,
) (acceptOutcome, error) {
if err := authorizeCandidate(ctx, unit, command.ActorID); err != nil {
return acceptOutcome{}, err
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return acceptOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", acceptLocation, err)
}
if !created {
return service.replayAccept(ctx, unit, request, command, stored)
}
entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true)
if errors.Is(err, outbound.ErrInvitationNotFound) {
return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptNotFound)
}
if err != nil {
return acceptOutcome{}, err
}
return service.acceptFound(ctx, unit, command, request, entry)
}
// acceptFound applies the checks that follow a found invitation and, when they
// pass, stores the acceptance with its consent and grant.
func (service *Service) acceptFound(
ctx context.Context,
unit outbound.UnitOfWork,
command AcceptCommand,
request acceptRequest,
entry outbound.CandidateInvitationEntry,
) (acceptOutcome, error) {
current := entry.Invitation
at := notBefore(request.now, current.UpdatedAt())
switch {
case current.State() == domain.InvitationAccepted:
return service.repeatAccept(ctx, unit, command, request, entry)
case current.IsTerminal() || current.ResponseDeadlinePassed(at):
return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict)
}
if command.ExpectedVersion != current.Version() || command.TermsVersion != current.TermsVersion() {
return acceptOutcome{}, fmt.Errorf("%s - compare versions: %w", acceptLocation, domain.ErrInvitationVersionConflict)
}
accepted, err := current.Accept(command.TermsVersion, at)
if errors.Is(err, domain.ErrInvitationNotAnswerable) {
return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict)
}
if err != nil {
return acceptOutcome{}, fmt.Errorf("%s - accept invitation: %w", acceptLocation, err)
}
if err := service.checkAcceptConsent(ctx, unit, command, request); err != nil {
return acceptOutcome{}, err
}
if err := service.storeAcceptance(ctx, unit, command, request, entry, accepted); err != nil {
return acceptOutcome{}, err
}
entry.Invitation = accepted
return service.completeAccept(ctx, unit, request, entry)
}
// checkAcceptConsent refuses a consent text that is not the published one and a
// kind that the profile does not hold. It stores nothing: the caller returns the
// error, and the transaction rolls back.
func (service *Service) checkAcceptConsent(
ctx context.Context,
unit outbound.UnitOfWork,
command AcceptCommand,
request acceptRequest,
) error {
if _, err := service.consents.CheckTextVersion(ctx, unit, domain.ConsentPurposeContactDisclosure, request.textVersion); err != nil {
if errors.Is(err, consent.ErrStaleConsentText) {
return fmt.Errorf("%s - %w", acceptLocation, &domain.InvitationFieldError{Pointer: consentTextPointer, Reason: "must be the published consent text"})
}
return fmt.Errorf("%s - check consent text: %w", acceptLocation, err)
}
profile, err := unit.CandidateProfiles().Get(ctx, command.ActorID)
if err != nil {
return fmt.Errorf("%s - read candidate profile: %w", acceptLocation, err)
}
held := heldContactFields(profile)
for index, field := range command.Fields {
if !slices.Contains(held, field) {
return fmt.Errorf("%s - %w", acceptLocation, &domain.InvitationFieldError{
Pointer: fmt.Sprintf("%s/%d", consentFieldsPointer, index), Reason: "the profile holds no such contact",
})
}
}
return nil
}
// storeAcceptance writes the acceptance in the transaction: the invitation moves
// to accepted with its audit event, the consent C4 is recorded in the ledger, and
// the grant of the selected fields is stored next to them.
func (service *Service) storeAcceptance(
ctx context.Context,
unit outbound.UnitOfWork,
command AcceptCommand,
request acceptRequest,
entry outbound.CandidateInvitationEntry,
accepted domain.Invitation,
) error {
current := entry.Invitation
event, err := accepted.AnswerEvent(command.ActorID)
if err != nil {
return fmt.Errorf("%s - build audit event: %w", acceptLocation, err)
}
if err := unit.Invitations().Accept(ctx, current.Version(), accepted, event); err != nil {
if errors.Is(err, outbound.ErrInvitationVersionConflict) {
return fmt.Errorf("%s - store acceptance: %w", acceptLocation, domain.ErrInvitationVersionConflict)
}
return fmt.Errorf("%s - store acceptance: %w", acceptLocation, err)
}
granted, err := service.consents.GrantContact(ctx, unit, consent.ContactGrantInput{
SubjectID: command.ActorID, OrganizationID: current.OrganizationID(), OrganizationName: entry.OrganizationName,
Fields: request.fields, InvitationID: current.ID(), InvitationTermsVersion: command.TermsVersion,
TextVersion: request.textVersion,
})
if err != nil {
return fmt.Errorf("%s - grant consent C4: %w", acceptLocation, err)
}
if !granted.Created {
return fmt.Errorf("%s - the invitation already has a consent C4 record: %w", acceptLocation, domain.ErrInvalidContactGrant)
}
grant, err := domain.NewContactGrant(granted.Record, accepted)
if err != nil {
return fmt.Errorf("%s - build contact grant: %w", acceptLocation, err)
}
if err := unit.ContactGrants().Create(ctx, grant); err != nil {
return fmt.Errorf("%s - store contact grant: %w", acceptLocation, err)
}
return nil
}
// repeatAccept answers an acceptance of an invitation that is already accepted.
// The same terms version and the same fields answer 200 with the invitation,
// even under a new key or an older expected version, and record nothing. Any
// other terms version or field set is a conflict with the accepted answer.
func (service *Service) repeatAccept(
ctx context.Context,
unit outbound.UnitOfWork,
command AcceptCommand,
request acceptRequest,
entry outbound.CandidateInvitationEntry,
) (acceptOutcome, error) {
grant, err := unit.ContactGrants().GetByInvitation(ctx, entry.Invitation.OrganizationID(), entry.Invitation.ID())
if err != nil {
return acceptOutcome{}, fmt.Errorf("%s - read contact grant: %w", acceptLocation, err)
}
if grant.TermsVersion() == command.TermsVersion && grant.Fields().Equal(request.fields) {
return service.completeAccept(ctx, unit, request, entry)
}
return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict)
}
// completeAccept stores the successful outcome under the key and builds the
// response with the contact grant.
func (service *Service) completeAccept(
ctx context.Context,
unit outbound.UnitOfWork,
request acceptRequest,
entry outbound.CandidateInvitationEntry,
) (acceptOutcome, error) {
view, err := service.candidateView(ctx, unit, entry, request.now)
if err != nil {
return acceptOutcome{}, err
}
result := outbound.InvitationAcceptResult{InvitationID: entry.Invitation.ID(), Outcome: outbound.InvitationAcceptAccepted}
if err := finishAccept(ctx, unit, request, result); err != nil {
return acceptOutcome{}, err
}
return acceptOutcome{view: view}, nil
}
// refuseAccept stores a refusal that the contract keeps under the key and lets
// the transaction commit, since nothing else was written.
func (service *Service) refuseAccept(
ctx context.Context,
unit outbound.UnitOfWork,
command AcceptCommand,
request acceptRequest,
outcome outbound.InvitationAcceptOutcome,
) (acceptOutcome, error) {
result := outbound.InvitationAcceptResult{InvitationID: command.InvitationID, Outcome: outcome}
if err := finishAccept(ctx, unit, request, result); err != nil {
return acceptOutcome{}, err
}
return acceptOutcome{refusal: acceptRefusal(outcome)}, nil
}
func finishAccept(ctx context.Context, unit outbound.UnitOfWork, request acceptRequest, result outbound.InvitationAcceptResult) error {
if err := unit.InvitationAcceptResults().SaveAcceptResult(ctx, request.scope, result); err != nil {
return fmt.Errorf("%s - store outcome: %w", acceptLocation, err)
}
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
return fmt.Errorf("%s - purge expired idempotency records: %w", acceptLocation, err)
}
return nil
}
func acceptRefusal(outcome outbound.InvitationAcceptOutcome) error {
if outcome == outbound.InvitationAcceptNotFound {
return outbound.ErrInvitationNotFound
}
return ErrAnswerBlocked
}
// replayAccept returns the stored outcome of the same request, or refuses a key
// used with another request. A stored acceptance is rebuilt from the invitation
// and its grant, which the acceptance keeps.
func (service *Service) replayAccept(
ctx context.Context,
unit outbound.UnitOfWork,
request acceptRequest,
command AcceptCommand,
stored outbound.IdempotencyRecord,
) (acceptOutcome, error) {
if stored.Fingerprint != request.fingerprint {
return acceptOutcome{}, fmt.Errorf("%s - compare request fingerprint: %w", acceptLocation, ErrIdempotencyKeyReused)
}
original, err := unit.InvitationAcceptResults().GetAcceptResult(ctx, request.scope)
if err != nil {
return acceptOutcome{}, fmt.Errorf("%s - read original outcome: %w", acceptLocation, err)
}
if original.InvitationID != command.InvitationID {
return acceptOutcome{}, fmt.Errorf("%s - validate original outcome: %w", acceptLocation, domain.ErrInvalidInvitation)
}
if original.Outcome != outbound.InvitationAcceptAccepted {
return acceptOutcome{refusal: acceptRefusal(original.Outcome)}, nil
}
entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, false)
if err != nil {
return acceptOutcome{}, err
}
view, err := service.candidateView(ctx, unit, entry, request.now)
if err != nil {
return acceptOutcome{}, err
}
return acceptOutcome{view: view}, nil
}
// heldContactFields lists the kinds that the profile holds as confirmed claims,
// in the order of ContactFieldKind. A suggestion that nobody confirmed is not
// held, so it can never be disclosed.
func heldContactFields(profile domain.CandidateProfile) []domain.ContactField {
content := profile.Content()
held := make([]domain.ContactField, 0, 4)
if claim, ok := content.FullName(); confirmedClaim(claim.Status(), ok) {
held = append(held, domain.ContactFieldFullName)
}
if claim, ok := content.Email(); confirmedClaim(claim.Status(), ok) {
held = append(held, domain.ContactFieldEmail)
}
if claim, ok := content.Phone(); confirmedClaim(claim.Status(), ok) {
held = append(held, domain.ContactFieldPhone)
}
if claim, ok := content.Telegram(); confirmedClaim(claim.Status(), ok) {
held = append(held, domain.ContactFieldTelegram)
}
return held
}
func confirmedClaim(status domain.ProfileClaimStatus, present bool) bool {
return present && status == domain.ProfileClaimConfirmed
}
@@ -0,0 +1,467 @@
package invitation
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// testC4Version is the published C4 text of the fakes.
const testC4Version = domain.ConsentTextVersion("c4-2026-10-01")
func (unit *testUnit) ContactGrants() outbound.ContactGrantRepository {
return testContactGrants{state: unit.state}
}
func (unit *testUnit) InvitationAcceptResults() outbound.InvitationAcceptResultRepository {
return testInvitations{state: unit.state}
}
func (unit *testUnit) CandidateProfiles() outbound.CandidateProfileRepository {
return testProfiles{state: unit.state}
}
func (unit *testUnit) ConsentTexts() outbound.ConsentTextRepository {
return testConsentTexts{}
}
func (unit *testUnit) ConsentLedger() outbound.ConsentLedger {
return testConsentLedger{state: unit.state}
}
func (unit *testUnit) PrivacySettings() outbound.PrivacySettingsRepository {
return testPrivacySettings{state: unit.state}
}
// Accept applies the compare-and-swap of the acceptance like the database does:
// the stored invitation must be answerable at the expected version.
func (repository testInvitations) Accept(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error {
current, ok := repository.state.invitations[next.ID()]
answerable := current.State() == domain.InvitationDelivered || current.State() == domain.InvitationViewed
if !ok || current.Version() != expectedVersion || !answerable {
return outbound.ErrInvitationVersionConflict
}
repository.state.invitations[next.ID()] = next
repository.state.events = append(repository.state.events, event)
return nil
}
func (repository testInvitations) SaveAcceptResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.InvitationAcceptResult) error {
repository.state.acceptResults[scope] = result
return nil
}
func (repository testInvitations) GetAcceptResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (outbound.InvitationAcceptResult, error) {
result, ok := repository.state.acceptResults[scope]
if !ok {
return outbound.InvitationAcceptResult{}, outbound.ErrInvitationAcceptResultNotFound
}
return result, nil
}
type testContactGrants struct {
state *testState
}
func (repository testContactGrants) Create(_ context.Context, grant domain.ContactGrant) error {
if _, exists := repository.state.grants[grant.InvitationID()]; exists {
return errors.New("contact grant already exists")
}
repository.state.grants[grant.InvitationID()] = grant
return nil
}
func (repository testContactGrants) GetByInvitation(_ context.Context, organizationID, invitationID uuid.UUID) (domain.ContactGrant, error) {
grant, ok := repository.state.grants[invitationID]
if !ok || grant.OrganizationID() != organizationID {
return domain.ContactGrant{}, outbound.ErrContactGrantNotFound
}
return grant, nil
}
type testProfiles struct {
outbound.CandidateProfileRepository
state *testState
}
func (repository testProfiles) Get(_ context.Context, userID uuid.UUID) (domain.CandidateProfile, error) {
if profile, ok := repository.state.profiles[userID]; ok {
return profile, nil
}
return domain.EmptyCandidateProfile(userID)
}
// testConsentTexts publishes one C4 text that names the organization.
type testConsentTexts struct {
outbound.ConsentTextRepository
}
func (testConsentTexts) Current(_ context.Context, purpose domain.ConsentPurpose, _ time.Time) (domain.ConsentText, error) {
if purpose != domain.ConsentPurposeContactDisclosure {
return domain.ConsentText{}, outbound.ErrConsentTextNotFound
}
body := "I consent to the transfer of the contact data I select to {organization} for this invitation."
hash := domain.HashConsentText(body)
text, err := domain.RestoreConsentText(domain.StoredConsentText{
Purpose: string(purpose), Version: string(testC4Version), Body: body, Hash: hash[:], Kind: string(domain.ConsentTextKindDemo),
PublishedAt: time.Date(2026, time.October, 1, 0, 0, 0, 0, time.UTC),
})
if err != nil {
return domain.ConsentText{}, err
}
return text, nil
}
// testConsentLedger stores the C4 record of an acceptance once per invitation,
// as the ledger does.
type testConsentLedger struct {
outbound.ConsentLedger
state *testState
}
func (ledger testConsentLedger) GrantContact(_ context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) {
if existing, ok := ledger.state.consentRecords[grant.InvitationID()]; ok {
return existing, false, nil
}
hash := grant.TextHash()
fields := make([]string, 0, 4)
for _, field := range grant.Fields().Fields() {
fields = append(fields, string(field))
}
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(domain.ConsentPurposeContactDisclosure),
TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance),
State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(), OrganizationID: grant.OrganizationID(),
OrganizationName: grant.OrganizationName(), FieldSet: fields, InvitationID: grant.InvitationID(),
InvitationTermsVersion: grant.InvitationTermsVersion(),
})
if err != nil {
return domain.ConsentRecord{}, false, err
}
ledger.state.consentRecords[grant.InvitationID()] = record
return record, true, nil
}
// testPrivacySettings reads the publication and the hidings of the fakes. A
// candidate who never published has the closed publication.
type testPrivacySettings struct {
outbound.PrivacySettingsRepository
state *testState
}
func (repository testPrivacySettings) ReadSettings(_ context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) {
publication, ok := repository.state.publications[userID]
if !ok {
closed, err := domain.NewPublication(userID)
if err != nil {
return outbound.CandidatePrivacySettings{}, err
}
publication = closed
}
return outbound.CandidatePrivacySettings{Publication: publication}, nil
}
func (repository testPrivacySettings) GetHiddenOrganization(_ context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error) {
if !repository.state.hidden[[2]uuid.UUID{userID, organizationID}] {
return outbound.HiddenOrganizationRecord{}, outbound.ErrCandidatePrivacySettingsNotFound
}
return outbound.HiddenOrganizationRecord{OrganizationID: organizationID, OrganizationName: "Test organization"}, nil
}
// testProfile builds a candidate profile whose confirmed claims are the held
// kinds, the way the profile service stores them.
func testProfile(t *testing.T, candidateID uuid.UUID, held ...domain.ContactField) domain.CandidateProfile {
t.Helper()
confirmed := func(value string) *domain.ProfileClaimInput[string] {
return &domain.ProfileClaimInput[string]{Value: value, Status: domain.ProfileClaimConfirmed}
}
var input domain.CandidateProfileInput
for _, field := range held {
switch field {
case domain.ContactFieldFullName:
input.FullName = confirmed("Test Candidate")
case domain.ContactFieldEmail:
input.Email = confirmed("candidate@example.test")
case domain.ContactFieldPhone:
input.Phone = confirmed("+70000000000")
case domain.ContactFieldTelegram:
input.Telegram = confirmed("@candidate_test")
}
}
empty, err := domain.EmptyCandidateProfile(candidateID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
profile, _, err := empty.Replace(input, 0, time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC))
if err != nil {
t.Fatalf("Replace() error = %v", err)
}
return profile
}
// setState changes the committed state of the fakes between commands.
func (test *harness) setState(change func(state *testState)) {
test.transactor.mu.Lock()
defer test.transactor.mu.Unlock()
change(&test.transactor.state)
}
func (test *harness) setProfile(t *testing.T, candidateID uuid.UUID, held ...domain.ContactField) {
t.Helper()
profile := testProfile(t, candidateID, held...)
test.setState(func(state *testState) { state.profiles[candidateID] = profile })
}
func (test *harness) publish(candidateID uuid.UUID, at time.Time) {
publication, err := domain.RestorePublication(domain.StoredPublication{
UserID: candidateID, State: string(domain.PublicationPublished), Fields: []string{string(domain.CardFieldCategories)},
ConsentRecordID: uuid.Must(uuid.NewV7()), PublishedAt: at, Version: 1,
})
if err != nil {
panic(err)
}
test.setState(func(state *testState) { state.publications[candidateID] = publication })
}
func acceptCommand(actorID, invitationID uuid.UUID, version, terms int64, key string, fields ...domain.ContactField) AcceptCommand {
return AcceptCommand{
ActorID: actorID, InvitationID: invitationID, IdempotencyKey: key, ExpectedVersion: version,
TermsVersion: terms, TextVersion: string(testC4Version), Fields: fields,
}
}
func TestAcceptMineStoresTheAcceptanceAndTheGrantOfTheSelectedFieldsOnly(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
test.setProfile(t, candidateID, domain.ContactFieldEmail)
test.setTime(sent.DeliveredAt.Add(time.Hour))
// The profile holds only the email, so a phone request is refused by its
// pointer, and nothing is stored.
_, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-phone",
domain.ContactFieldPhone))
if got := fieldPointer(t, err); got != "/consent_c4/fields/0" {
t.Fatalf("pointer = %s, want /consent_c4/fields/0", got)
}
if state := test.transactor.snapshot(); len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.acceptResults) != 0 {
t.Fatalf("a refused acceptance stored grants %d, consents %d, outcomes %d", len(state.grants), len(state.consentRecords), len(state.acceptResults))
}
view, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-email",
domain.ContactFieldEmail))
if err != nil {
t.Fatalf("AcceptMine() error = %v", err)
}
if view.State != domain.InvitationAccepted || view.Version != sent.Version+1 || view.TermsVersion != sent.TermsVersion ||
view.RespondedAt == nil || view.ContactConsent != nil || view.ContactGrant == nil {
t.Fatalf("accepted = %+v, want the accepted invitation with its grant and no offer", view)
}
grant := view.ContactGrant
if len(grant.Fields) != 1 || grant.Fields[0] != domain.ContactFieldEmail || grant.Status != domain.ContactGrantActive ||
grant.Readable || grant.BlockedBy == nil || *grant.BlockedBy != domain.ContactAccessBlockVisibility ||
grant.TermsVersion != sent.TermsVersion || grant.ConsentTextVersion != testC4Version {
t.Fatalf("grant = %+v, want the email only, active, blocked by visibility while the profile is not published", grant)
}
state := test.transactor.snapshot()
invitation := state.invitations[sent.ID]
last := state.events[len(state.events)-1]
if invitation.State() != domain.InvitationAccepted || len(state.grants) != 1 || len(state.consentRecords) != 1 ||
last.Kind != domain.InvitationEventAccepted || last.ActorID != candidateID || len(last.ChangedFields) != 0 {
t.Fatalf("stored state = %s grants %d consents %d last event %s, want one acceptance, grant, and consent",
invitation.State(), len(state.grants), len(state.consentRecords), last.Kind)
}
record := state.consentRecords[sent.ID]
if record.InvitationTermsVersion() != sent.TermsVersion || record.OrganizationName() != "Test organization" ||
len(record.Fields().Fields()) != 1 || record.Fields().Fields()[0] != domain.ContactFieldEmail {
t.Fatalf("C4 record = %s, want the organization, the terms version, and the email only", record)
}
}
func TestAcceptMineRepeatsWithoutRecordingAgainAndRefusesAnotherChoice(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
test.setProfile(t, candidateID, domain.ContactFieldEmail, domain.ContactFieldPhone)
test.setTime(sent.DeliveredAt.Add(time.Hour))
first, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first",
domain.ContactFieldEmail))
if err != nil {
t.Fatalf("AcceptMine() error = %v", err)
}
before := test.transactor.snapshot()
test.setTime(sent.DeliveredAt.Add(2 * time.Hour))
// A new key with the older expected version and the same terms and fields
// answers the accepted invitation without a second grant or event.
again, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-again",
domain.ContactFieldEmail))
if err != nil || again.Version != first.Version || again.ContactGrant == nil || again.ContactGrant.ID != first.ContactGrant.ID {
t.Fatalf("repeat = %+v, %v; want the first acceptance", again, err)
}
replay, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first",
domain.ContactFieldEmail))
if err != nil || replay.ContactGrant == nil || replay.ContactGrant.ID != first.ContactGrant.ID {
t.Fatalf("replay = %+v, %v; want the stored response", replay, err)
}
after := test.transactor.snapshot()
if len(after.events) != len(before.events) || len(after.grants) != 1 || len(after.consentRecords) != 1 {
t.Fatalf("repeats stored events %d to %d, grants %d, consents %d", len(before.events), len(after.events), len(after.grants), len(after.consentRecords))
}
// Another field set or a reused key with another body is refused, and the
// refusal is stored under its key.
if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-more",
domain.ContactFieldEmail, domain.ContactFieldPhone)); !errors.Is(err, ErrAnswerBlocked) {
t.Fatalf("another field set error = %v, want ErrAnswerBlocked", err)
}
if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first",
domain.ContactFieldPhone)); !errors.Is(err, ErrIdempotencyKeyReused) {
t.Fatalf("reused key error = %v, want ErrIdempotencyKeyReused", err)
}
if got := test.transactor.snapshot().acceptResults; len(got) != 3 {
t.Fatalf("stored outcomes = %d, want accepted, accepted again, and the refused field set", len(got))
}
}
func TestAcceptMineRefusesAStaleTermsVersionWithoutStoringAnything(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
test.setProfile(t, candidateID, domain.ContactFieldEmail)
before := test.transactor.snapshot()
// The terms the candidate read are not the current ones: 412, nothing
// recorded, and no outcome under the key.
for name, command := range map[string]AcceptCommand{
"stale terms": acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion+1, "stale-terms", domain.ContactFieldEmail),
"stale version": acceptCommand(candidateID, sent.ID, sent.Version+1, sent.TermsVersion, "stale-version", domain.ContactFieldEmail),
} {
if _, err := test.service.AcceptMine(t.Context(), command); !errors.Is(err, domain.ErrInvitationVersionConflict) {
t.Fatalf("%s error = %v, want ErrInvitationVersionConflict", name, err)
}
}
after := test.transactor.snapshot()
if len(after.grants) != 0 || len(after.consentRecords) != 0 || len(after.acceptResults) != 0 || len(after.events) != len(before.events) {
t.Fatalf("a stale acceptance stored grants %d, consents %d, outcomes %d", len(after.grants), len(after.consentRecords), len(after.acceptResults))
}
if after.invitations[sent.ID].State() != domain.InvitationDelivered {
t.Fatalf("state = %s, want delivered", after.invitations[sent.ID].State())
}
}
func TestAcceptMineAtTheDeadlineStoresTheConflictAndGrantsNothing(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
test.setProfile(t, candidateID, domain.ContactFieldEmail)
test.setTime(*sent.ResponseDeadlineAt)
_, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version+5, sent.TermsVersion, "late",
domain.ContactFieldEmail))
if !errors.Is(err, ErrAnswerBlocked) {
t.Fatalf("late acceptance error = %v, want ErrAnswerBlocked whatever the version", err)
}
state := test.transactor.snapshot()
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))
}
}
func TestAcceptMineChecksTheConsentTextAndTheHeldKinds(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
test.setProfile(t, candidateID, domain.ContactFieldFullName)
test.setTime(sent.DeliveredAt.Add(time.Hour))
outdated := acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "outdated", domain.ContactFieldFullName)
outdated.TextVersion = "c4-2025-01-01"
if got := fieldPointer(t, mustFail(t, test, outdated)); got != "/consent_c4/text_version" {
t.Fatalf("outdated text pointer = %s, want /consent_c4/text_version", got)
}
if got := fieldPointer(t, mustFail(t, test, acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "email",
domain.ContactFieldFullName, domain.ContactFieldEmail))); got != "/consent_c4/fields/1" {
t.Fatalf("unheld kind pointer = %s, want /consent_c4/fields/1", got)
}
if state := test.transactor.snapshot(); len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.acceptResults) != 0 {
t.Fatalf("refused consent stored grants %d, consents %d, outcomes %d", len(state.grants), len(state.consentRecords), len(state.acceptResults))
}
// The offer lists the held kinds in the order of the contract and shows the
// text with the organization name. A profile without a kind has no offer.
offered := decodeOffer(t, test, candidateID, sent.ID)
if offered.Text.TextVersion != testC4Version || !strings.Contains(offered.Text.Text, "Test organization") ||
strings.Contains(offered.Text.Text, "{organization}") || len(offered.AvailableFields) != 1 || offered.AvailableFields[0] != domain.ContactFieldFullName {
t.Fatalf("offer = %+v, want the rendered text and the held kind", offered)
}
test.setProfile(t, candidateID)
read, err := test.service.GetMine(t.Context(), candidateID, sent.ID)
if err != nil || read.ContactConsent != nil {
t.Fatalf("GetMine without a held kind = %+v, %v; want no offer", read.ContactConsent, err)
}
}
func TestAcceptedInvitationReadsTheGrantAndKeepsThePublicationAndTheHiding(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 })
publications := test.transactor.snapshot().publications
accepted, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "hidden",
domain.ContactFieldEmail))
if err != nil {
t.Fatalf("AcceptMine() while hidden error = %v", err)
}
if accepted.ContactGrant == nil || accepted.ContactGrant.Readable || accepted.ContactGrant.BlockedBy == nil {
t.Fatalf("grant while hidden = %+v, want stored and blocked by visibility", accepted.ContactGrant)
}
state := test.transactor.snapshot()
if len(state.publications) != len(publications) || state.publications[candidateID].State() != domain.PublicationPublished ||
!state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] {
t.Fatal("the acceptance changed the publication or lifted the hiding")
}
// Unhiding the organization makes the same grant readable; the grant
// itself never changes.
test.setState(func(state *testState) { delete(state.hidden, [2]uuid.UUID{candidateID, test.organizationID}) })
read, err := test.service.GetMine(t.Context(), candidateID, sent.ID)
if err != nil || read.ContactGrant == nil || !read.ContactGrant.Readable || read.ContactGrant.BlockedBy != nil ||
read.ContactGrant.ID != accepted.ContactGrant.ID {
t.Fatalf("read after unhiding = %+v, %v; want the same grant readable", read.ContactGrant, err)
}
}
// decodeOffer reads the invitation of the candidate and returns its consent offer.
func decodeOffer(t *testing.T, test *harness, candidateID, invitationID uuid.UUID) domain.ContactConsentOffer {
t.Helper()
read, err := test.service.GetMine(t.Context(), candidateID, invitationID)
if err != nil {
t.Fatalf("GetMine() error = %v", err)
}
if read.ContactConsent == nil {
t.Fatal("GetMine() = no contact consent offer, want one")
}
return *read.ContactConsent
}
// mustFail returns the error of an acceptance that must be refused.
func mustFail(t *testing.T, test *harness, command AcceptCommand) error {
t.Helper()
_, err := test.service.AcceptMine(t.Context(), command)
if err == nil {
t.Fatalf("AcceptMine(%s) succeeded, want a refusal", command.IdempotencyKey)
}
return err
}
@@ -144,7 +144,7 @@ func (service *Service) declineInTransaction(
return declineOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", declineLocation, err)
}
if !created {
return replayDecline(ctx, unit, request, command, stored)
return service.replayDecline(ctx, unit, request, command, stored)
}
entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true)
if errors.Is(err, outbound.ErrInvitationNotFound) {
@@ -176,7 +176,7 @@ func (service *Service) declineFound(
if previous.Choice.Equal(command.Choice) {
// The same decline answers with the invitation as it is, whatever
// the key or the version, and records nothing again.
return completeDecline(ctx, unit, request, entry)
return service.completeDecline(ctx, unit, request, entry)
}
return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict)
}
@@ -204,18 +204,18 @@ func (service *Service) declineFound(
return declineOutcome{}, fmt.Errorf("%s - store decline: %w", declineLocation, err)
}
entry.Invitation = declined
return completeDecline(ctx, unit, request, entry)
return service.completeDecline(ctx, unit, request, entry)
}
// completeDecline stores the successful outcome under the key and builds the
// response with the stored decline.
func completeDecline(
func (service *Service) completeDecline(
ctx context.Context,
unit outbound.UnitOfWork,
request declineRequest,
entry outbound.CandidateInvitationEntry,
) (declineOutcome, error) {
view, err := candidateView(ctx, unit, entry)
view, err := service.candidateView(ctx, unit, entry, request.now)
if err != nil {
return declineOutcome{}, err
}
@@ -263,7 +263,7 @@ func declineRefusal(outcome outbound.InvitationDeclineOutcome) error {
// key used with another request. A stored success is rebuilt from the
// declined invitation and its decline: both are final, so the replay shows
// the same answer without a second copy of the comment.
func replayDecline(
func (service *Service) replayDecline(
ctx context.Context,
unit outbound.UnitOfWork,
request declineRequest,
@@ -290,7 +290,7 @@ func replayDecline(
if entry.Invitation.State() != domain.InvitationDeclined {
return declineOutcome{}, fmt.Errorf("%s - validate original response: %w", declineLocation, domain.ErrInvalidInvitation)
}
view, err := candidateView(ctx, unit, entry)
view, err := service.candidateView(ctx, unit, entry, request.now)
if err != nil {
return declineOutcome{}, err
}
+20 -7
View File
@@ -3,9 +3,9 @@
// candidate card of the organization, the idempotent creation, and the
// idempotent send that delivers a draft to the candidate's inbox. On the
// candidate's side it lists that inbox, reads one invitation, records the
// view, and records a structured decline. The acceptance, the cancellation,
// and the contact grant belong to later operations that build on the same
// records.
// view, records a structured decline, and accepts the current terms with the
// consent C4 and its contact grant in one transaction. The cancellation and
// the revocation of a grant belong to later operations.
package invitation
import (
@@ -18,6 +18,7 @@ import (
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/consent"
)
var (
@@ -70,6 +71,14 @@ type CandidateResolver func(ctx context.Context, unit outbound.UnitOfWork, actor
// invitation that is already charged is allowed without a second charge.
type InvitationQuota func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error)
// ContactConsents is the consent ledger of the acceptance. It reads the
// published C4 text, checks the version that the candidate saw, and records
// the C4 grant inside the caller's transaction. consent.Service implements it.
type ContactConsents interface {
CheckTextVersion(ctx context.Context, repositories outbound.ConsentRepositories, purpose domain.ConsentPurpose, version domain.ConsentTextVersion) (domain.ConsentText, error)
GrantContact(ctx context.Context, repositories outbound.ConsentRepositories, input consent.ContactGrantInput) (consent.GrantResult, error)
}
// DeliveryNotifier records, inside the caller's transaction, the outbox
// events that tell the candidate about a delivered invitation: the in-platform
// notification and the email. Neither blocks the delivery: the invitation is
@@ -90,11 +99,13 @@ type Dependencies struct {
Candidates CandidateResolver
Quota InvitationQuota
Notifier DeliveryNotifier
Clock func() time.Time
// Consents records the consent C4 of an acceptance in its transaction.
Consents ContactConsents
Clock func() time.Time
}
// Service applies organization-scoped invitation commands and reads, and the
// candidate's reads, view, and decline of the own invitations.
// candidate's reads, view, decline, and acceptance of the own invitations.
type Service struct {
transactor outbound.Transactor
keyring Keyring
@@ -102,13 +113,14 @@ type Service struct {
candidates CandidateResolver
quota InvitationQuota
notifier DeliveryNotifier
consents ContactConsents
clock func() time.Time
}
// NewService fails at startup when a required dependency is missing.
func NewService(deps Dependencies) (*Service, error) {
if deps.Transactor == nil || deps.Keyring == nil || deps.Candidates == nil || deps.Quota == nil ||
deps.Notifier == nil || deps.Clock == nil {
deps.Notifier == nil || deps.Consents == nil || deps.Clock == nil {
return nil, errors.New("invitation.NewService - every dependency must be set")
}
if _, err := deps.PseudonymKey.ForOrganization(uuid.New(), uuid.New()); err != nil {
@@ -116,7 +128,8 @@ func NewService(deps Dependencies) (*Service, error) {
}
return &Service{
transactor: deps.Transactor, keyring: deps.Keyring, pseudonymKey: deps.PseudonymKey,
candidates: deps.Candidates, quota: deps.Quota, notifier: deps.Notifier, clock: deps.Clock,
candidates: deps.Candidates, quota: deps.Quota, notifier: deps.Notifier, consents: deps.Consents,
clock: deps.Clock,
}, nil
}
@@ -16,6 +16,7 @@ import (
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/consent"
)
type testKeyring struct{}
@@ -47,6 +48,16 @@ type testState struct {
// the decline outcomes kept under a key.
declines map[uuid.UUID]domain.InvitationDecline
declineResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult
// grants holds the contact grants by invitation, acceptResults the
// acceptance outcomes by key, and consentRecords the C4 records by
// invitation. profiles and publications are the candidates' profiles and
// publication settings, and hidden the hidden organizations by candidate.
grants map[uuid.UUID]domain.ContactGrant
acceptResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationAcceptResult
consentRecords map[uuid.UUID]domain.ConsentRecord
profiles map[uuid.UUID]domain.CandidateProfile
publications map[uuid.UUID]domain.Publication
hidden map[[2]uuid.UUID]bool
// charged lists the invitations charged against the organization quota,
// and notified the delivered invitations that were notified.
charged []uuid.UUID
@@ -63,6 +74,12 @@ func newTestState() testState {
needVersions: map[[3]string]bool{},
declines: map[uuid.UUID]domain.InvitationDecline{},
declineResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult{},
grants: map[uuid.UUID]domain.ContactGrant{},
acceptResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationAcceptResult{},
consentRecords: map[uuid.UUID]domain.ConsentRecord{},
profiles: map[uuid.UUID]domain.CandidateProfile{},
publications: map[uuid.UUID]domain.Publication{},
hidden: map[[2]uuid.UUID]bool{},
}
}
@@ -99,6 +116,24 @@ func (state testState) clone() testState {
for scope, result := range state.declineResults {
cloned.declineResults[scope] = result
}
for id, grant := range state.grants {
cloned.grants[id] = grant
}
for scope, result := range state.acceptResults {
cloned.acceptResults[scope] = result
}
for id, record := range state.consentRecords {
cloned.consentRecords[id] = record
}
for id, profile := range state.profiles {
cloned.profiles[id] = profile
}
for id, publication := range state.publications {
cloned.publications[id] = publication
}
for key, hidden := range state.hidden {
cloned.hidden[key] = hidden
}
cloned.charged = slices.Clone(state.charged)
cloned.notified = slices.Clone(state.notified)
return cloned
@@ -417,6 +452,7 @@ func newHarness(t *testing.T) *harness {
return outbound.CompanyQuotaDecision{Allowed: true}, nil
},
Notifier: testNotifier{},
Consents: consent.NewService(test.transactor, func() time.Time { return current }),
})
if err != nil {
t.Fatalf("NewService() error = %v", err)
+107 -9
View File
@@ -2,6 +2,7 @@ package invitation
import (
"context"
"errors"
"fmt"
"time"
@@ -25,8 +26,12 @@ func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid.
if actorID == uuid.Nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", getMineLocation, ErrForbidden)
}
now, err := service.now(getMineLocation)
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
}
@@ -34,7 +39,7 @@ func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid.
if err != nil {
return err
}
view, err = candidateView(ctx, unit, entry)
view, err = service.candidateView(ctx, unit, entry, now)
return err
})
if err != nil {
@@ -85,7 +90,7 @@ func (service *Service) ViewMine(ctx context.Context, actorID, invitationID uuid
}
entry.Invitation = viewed
}
view, err = candidateView(ctx, unit, entry)
view, err = service.candidateView(ctx, unit, entry, now)
return err
})
if err != nil {
@@ -123,25 +128,118 @@ func readCandidateEntry(
// organization from seeing the candidate, while the candidate needs to know
// who sent the offer to answer it. Pushed content, such as the inbox
// notification, follows the hiding instead.
func candidateView(ctx context.Context, unit outbound.UnitOfWork, entry outbound.CandidateInvitationEntry) (domain.CandidateInvitationView, error) {
const location = "invitation.candidateView"
//
// The consent offer is set while an acceptance is possible, and the contact
// grant once the invitation is accepted. The grant is readable only while the
// organization may read the profile, so a hidden profile shows the grant as
// blocked by visibility. at is the time of the command that builds the view.
func (service *Service) candidateView(
ctx context.Context,
unit outbound.UnitOfWork,
entry outbound.CandidateInvitationEntry,
at time.Time,
) (domain.CandidateInvitationView, error) {
const location = "invitation.Service.candidateView"
current := entry.Invitation
var decline *domain.InvitationDecline
if entry.Invitation.State() == domain.InvitationDeclined {
stored, err := unit.Invitations().GetDecline(ctx, entry.Invitation.OrganizationID(), entry.Invitation.ID())
if current.State() == domain.InvitationDeclined {
stored, err := unit.Invitations().GetDecline(ctx, current.OrganizationID(), current.ID())
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - read decline: %w", location, err)
}
decline = &stored
}
view, err := entry.Invitation.CandidateView(domain.InvitationOrganizationRef{
ID: entry.Invitation.OrganizationID(), Name: entry.OrganizationName,
view, err := current.CandidateView(domain.InvitationOrganizationRef{
ID: current.OrganizationID(), Name: entry.OrganizationName,
}, decline)
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - build view: %w", location, err)
}
switch {
case current.State() == domain.InvitationAccepted:
grant, err := unit.ContactGrants().GetByInvitation(ctx, current.OrganizationID(), current.ID())
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - read contact grant: %w", location, err)
}
visible, err := candidateVisibleTo(ctx, unit, current.CandidateID(), current.OrganizationID())
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - read visibility: %w", location, err)
}
grantView := grant.CandidateView(visible)
view.ContactGrant = &grantView
case acceptancePossible(current, at):
offer, offered, err := contactConsentOffer(ctx, unit, current, entry.OrganizationName, at)
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - build consent offer: %w", location, err)
}
if offered {
view.ContactConsent = &offer
}
}
return view, nil
}
// acceptancePossible reports the states and the time in which the candidate
// may accept: a delivered or viewed invitation before its deadline.
func acceptancePossible(invitation domain.Invitation, at time.Time) bool {
state := invitation.State()
return (state == domain.InvitationDelivered || state == domain.InvitationViewed) &&
invitation.IsDelivered() && !invitation.ResponseDeadlinePassed(at)
}
// candidateVisibleTo reports whether the organization may read the profile of
// the candidate now: the publication is effective, and the candidate has not
// hidden the organization. The read model of the profile applies C2 and the
// revocation of C2; the hiding is a record of its own.
func candidateVisibleTo(ctx context.Context, unit outbound.UnitOfWork, candidateID, organizationID uuid.UUID) (bool, error) {
const location = "invitation.candidateVisibleTo"
settings, err := unit.PrivacySettings().ReadSettings(ctx, candidateID)
if err != nil {
return false, fmt.Errorf("%s - read privacy settings: %w", location, err)
}
if settings.Publication.State() != domain.PublicationPublished {
return false, nil
}
_, err = unit.PrivacySettings().GetHiddenOrganization(ctx, candidateID, organizationID)
switch {
case err == nil:
return false, nil
case errors.Is(err, outbound.ErrCandidatePrivacySettingsNotFound):
return true, nil
default:
return false, fmt.Errorf("%s - read hidden organization: %w", location, err)
}
}
// contactConsentOffer builds the consent offer of an invitation: the rendered
// C4 text and the kinds that the profile holds. It reports false when the
// profile holds no kind, because a grant must cover at least one field.
func contactConsentOffer(
ctx context.Context,
unit outbound.UnitOfWork,
invitation domain.Invitation,
organizationName string,
at time.Time,
) (domain.ContactConsentOffer, bool, error) {
profile, err := unit.CandidateProfiles().Get(ctx, invitation.CandidateID())
if err != nil {
return domain.ContactConsentOffer{}, false, fmt.Errorf("read candidate profile: %w", err)
}
held := heldContactFields(profile)
if len(held) == 0 {
return domain.ContactConsentOffer{}, false, nil
}
text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposeContactDisclosure, at)
if err != nil {
return domain.ContactConsentOffer{}, false, fmt.Errorf("read consent C4 text: %w", err)
}
offer, err := domain.NewContactConsentOffer(text, organizationName, held)
if err != nil {
return domain.ContactConsentOffer{}, false, fmt.Errorf("build offer: %w", err)
}
return offer, true, nil
}
// notBefore keeps a clock that stepped back from recording a change before
// the last one.
func notBefore(now, last time.Time) time.Time {