Files
lincodex/backend/db/migrations/00040_accept_invitations.sql
T

348 lines
13 KiB
PL/PgSQL

-- +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')
);