feat(visibility): add the candidate publication, hiding and search status contract
This commit is contained in:
1 parent
4436f626a3
commit
0529601021
87 files changed
+21456
-83
No files matched your search
@@ -0,0 +1,440 @@
|
||||
-- +goose Up
|
||||
-- Visibility of the candidate card (PRD FR02 and FR12, TASK-088): the
|
||||
-- publication, the search status, the organizations the candidate hides the
|
||||
-- profile from, and the history of these settings. Enum-like columns are text
|
||||
-- with CHECK constraints, as in the other tables.
|
||||
--
|
||||
-- A profile is closed by default: nothing here is created with the profile
|
||||
-- or with the account, and a missing row means "closed", "not looking", or
|
||||
-- "not hidden". Every row is written by an explicit act of the candidate.
|
||||
--
|
||||
-- The three settings are separate tables on purpose. The consent C2 stays in
|
||||
-- the consent ledger and proves that the candidate accepted the publication
|
||||
-- text; candidate_publications refers to that record and records what the
|
||||
-- ledger deliberately does not (which fields, and when). The search status is
|
||||
-- a statement of the candidate, never a consent, so it has no consent column
|
||||
-- and no statement of one table writes another table. No row stores a
|
||||
-- profile value, a name, or a contact: the rows hold card field codes,
|
||||
-- identifiers, and times.
|
||||
|
||||
-- Card field codes in the canonical form of the stored sets: distinct,
|
||||
-- without NULLs, known, in ascending byte order. A canonical form makes equal
|
||||
-- sets equal arrays. The set is empty for a closed publication. The codes
|
||||
-- are the contract's CardField, which never includes the name, a contact, or
|
||||
-- the lowest salary.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean
|
||||
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
|
||||
SELECT
|
||||
(cardinality(fields) = 0 OR array_ndims(fields) = 1)
|
||||
AND cardinality(fields) BETWEEN 0 AND 6
|
||||
AND array_position(fields, NULL) IS NULL
|
||||
AND fields <@ ARRAY[
|
||||
'categories', 'experience', 'location', 'relocation',
|
||||
'soft_skills', 'stack'
|
||||
]::text []
|
||||
AND fields = ARRAY(
|
||||
SELECT DISTINCT field COLLATE "C"
|
||||
FROM unnest(fields) AS field
|
||||
ORDER BY field COLLATE "C"
|
||||
);
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- A composite foreign key below needs a unique key over the ledger columns
|
||||
-- it names. The record id is already unique, so this adds no restriction; it
|
||||
-- lets a publication refer to a C2 record of its own account and no other.
|
||||
CREATE UNIQUE INDEX consent_records_id_subject_purpose_key
|
||||
ON consent_records (id, subject_id, purpose);
|
||||
|
||||
-- One row per candidate, created by the first explicit publication. A row
|
||||
-- exists only after the candidate published once, so a new profile has no
|
||||
-- row and is closed. state is the stored setting; the effective state also
|
||||
-- needs the referenced C2 record to be unrevoked, which the read query joins
|
||||
-- from the ledger. A revocation therefore closes the card at once without any
|
||||
-- write here, and a later C2 grant opens nothing: a publication is bound to
|
||||
-- the record that backed it, and republishing binds it to the new one.
|
||||
CREATE TABLE candidate_publications (
|
||||
user_id uuid NOT NULL,
|
||||
-- published: organizations may read the fields. closed: the candidate
|
||||
-- closed the publication; the row keeps the last published time and the
|
||||
-- C2 record as evidence.
|
||||
state text NOT NULL,
|
||||
-- Card field codes in canonical order; empty exactly when closed.
|
||||
fields text [] NOT NULL,
|
||||
-- The C2 record that backed the latest publication. Always the C2 of this
|
||||
-- account: the foreign key names the subject and the purpose.
|
||||
consent_record_id uuid NOT NULL,
|
||||
consent_purpose text GENERATED ALWAYS AS ('c2') STORED,
|
||||
-- The time of the latest change that published or republished the card.
|
||||
published_at timestamptz NOT NULL,
|
||||
-- The time the candidate closed the publication; NULL while published.
|
||||
closed_at timestamptz,
|
||||
-- Optimistic concurrency version; the first publication creates 1 and
|
||||
-- the contract's version 0 is the absence of a row.
|
||||
version bigint NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT candidate_publications_pkey PRIMARY KEY (user_id),
|
||||
CONSTRAINT candidate_publications_user_id_fkey FOREIGN KEY (user_id)
|
||||
REFERENCES users (id) ON DELETE CASCADE,
|
||||
-- Consent evidence outlives a careless delete of the setting: the record
|
||||
-- cannot be deleted while a publication refers to it.
|
||||
CONSTRAINT candidate_publications_consent_fkey FOREIGN KEY (
|
||||
consent_record_id, user_id, consent_purpose
|
||||
) REFERENCES consent_records (id, subject_id, purpose) ON DELETE RESTRICT,
|
||||
CONSTRAINT candidate_publications_state_known CHECK (
|
||||
state IN ('published', 'closed')
|
||||
),
|
||||
CONSTRAINT candidate_publications_fields_canonical CHECK (
|
||||
candidate_card_fields_are_canonical(fields)
|
||||
),
|
||||
CONSTRAINT candidate_publications_state_shape CHECK (
|
||||
(
|
||||
state = 'published'
|
||||
AND cardinality(fields) > 0
|
||||
AND closed_at IS NULL
|
||||
)
|
||||
OR (
|
||||
state = 'closed'
|
||||
AND cardinality(fields) = 0
|
||||
AND closed_at IS NOT NULL
|
||||
AND closed_at >= published_at
|
||||
)
|
||||
),
|
||||
CONSTRAINT candidate_publications_version_positive CHECK (version > 0),
|
||||
CONSTRAINT candidate_publications_updated_after_creation CHECK (
|
||||
updated_at >= created_at
|
||||
)
|
||||
);
|
||||
|
||||
-- The search status of the candidate. A status that was never set has no row
|
||||
-- (not_looking). looking stores the confirmation time and the lapse time,
|
||||
-- which the application fixes from the search_status section of the product
|
||||
-- policy version in force at the confirmation, and the version it used. The
|
||||
-- lapse itself is computed by comparing lapses_at with the clock and is never
|
||||
-- written: no process turns an expired status into a more public state.
|
||||
-- Nothing here refers to a consent, the publication, or the hidden
|
||||
-- organizations.
|
||||
CREATE TABLE candidate_search_statuses (
|
||||
user_id uuid NOT NULL,
|
||||
status text NOT NULL,
|
||||
-- The latest confirmation of looking; NULL for not_looking.
|
||||
confirmed_at timestamptz,
|
||||
-- When the confirmed status lapses; NULL for not_looking.
|
||||
lapses_at timestamptz,
|
||||
-- The policy version whose interval produced lapses_at; NULL for
|
||||
-- not_looking. Policy versions are immutable and never deleted. A trigger
|
||||
-- below checks the reference instead of a foreign key, because a foreign
|
||||
-- key would make PostgreSQL refuse TRUNCATE of policy_versions before its
|
||||
-- own immutability trigger could answer.
|
||||
policy_version_id uuid,
|
||||
version bigint NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT candidate_search_statuses_pkey PRIMARY KEY (user_id),
|
||||
CONSTRAINT candidate_search_statuses_user_id_fkey FOREIGN KEY (user_id)
|
||||
REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT candidate_search_statuses_status_known CHECK (
|
||||
status IN ('looking', 'not_looking')
|
||||
),
|
||||
-- looking always carries its confirmation, lapse, and policy version;
|
||||
-- not_looking carries none of them.
|
||||
CONSTRAINT candidate_search_statuses_confirmation CHECK (
|
||||
(
|
||||
status = 'looking'
|
||||
AND confirmed_at IS NOT NULL
|
||||
AND lapses_at IS NOT NULL
|
||||
AND policy_version_id IS NOT NULL
|
||||
AND lapses_at > confirmed_at
|
||||
)
|
||||
OR (
|
||||
status = 'not_looking'
|
||||
AND confirmed_at IS NULL
|
||||
AND lapses_at IS NULL
|
||||
AND policy_version_id IS NULL
|
||||
)
|
||||
),
|
||||
CONSTRAINT candidate_search_statuses_version_positive CHECK (version > 0),
|
||||
CONSTRAINT candidate_search_statuses_updated_after_creation CHECK (
|
||||
updated_at >= created_at
|
||||
)
|
||||
);
|
||||
|
||||
-- Stands in for a foreign key to policy_versions: an unknown policy version
|
||||
-- raises SQLSTATE 23503 under the constraint name that the foreign key would
|
||||
-- have had. Policy versions are immutable and cannot be deleted, so checking
|
||||
-- when the reference is written is enough.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_search_statuses_check_policy() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.policy_version_id IS NOT NULL AND NOT EXISTS (
|
||||
SELECT 1 FROM policy_versions WHERE id = NEW.policy_version_id
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'foreign_key_violation',
|
||||
CONSTRAINT = 'candidate_search_statuses_policy_fkey',
|
||||
TABLE = 'candidate_search_statuses',
|
||||
MESSAGE = 'search status references an unknown policy version';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER candidate_search_statuses_check_policy
|
||||
BEFORE INSERT OR UPDATE OF policy_version_id ON candidate_search_statuses
|
||||
FOR EACH ROW EXECUTE FUNCTION candidate_search_statuses_check_policy();
|
||||
|
||||
-- The organizations a candidate hides the profile from. The record belongs to
|
||||
-- the candidate and references the organization; no organization reads it.
|
||||
-- One record per pair, so a hiding is unique. The primary key starts with the
|
||||
-- candidate, which serves every candidate-scoped read. Organizations are never
|
||||
-- deleted by the application, so RESTRICT keeps a hiding from silently
|
||||
-- disappearing with one.
|
||||
CREATE TABLE candidate_hidden_organizations (
|
||||
user_id uuid NOT NULL,
|
||||
organization_id uuid NOT NULL,
|
||||
hidden_at timestamptz NOT NULL,
|
||||
CONSTRAINT candidate_hidden_organizations_pkey PRIMARY KEY (
|
||||
user_id, organization_id
|
||||
),
|
||||
CONSTRAINT candidate_hidden_organizations_user_id_fkey FOREIGN KEY (user_id)
|
||||
REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT candidate_hidden_organizations_organization_id_fkey FOREIGN KEY (
|
||||
organization_id
|
||||
) REFERENCES organizations (id) ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
-- Serves the candidate's list, newest first.
|
||||
CREATE INDEX candidate_hidden_organizations_listing_idx
|
||||
ON candidate_hidden_organizations (user_id, hidden_at DESC, organization_id DESC);
|
||||
|
||||
-- Serves the organization side, which has to exclude hidden candidates from
|
||||
-- its reads without learning who hid it.
|
||||
CREATE INDEX candidate_hidden_organizations_organization_idx
|
||||
ON candidate_hidden_organizations (organization_id, user_id);
|
||||
|
||||
-- Bounds the hidden list of one candidate. The trigger serializes the inserts
|
||||
-- of one candidate through a lock on the account row (a no-key update lock,
|
||||
-- which does not block other readers of the account), counts the committed
|
||||
-- rows, and refuses the insert over the bound with SQLSTATE 23514 and the
|
||||
-- constraint name candidate_hidden_organizations_limit, which the adapter
|
||||
-- maps to a port sentinel without reading the message. Raising the bound
|
||||
-- also raises the maximum of the contract's hidden_organizations_total.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_hidden_organizations_enforce_limit() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM 1 FROM users WHERE id = NEW.user_id FOR NO KEY UPDATE;
|
||||
IF (
|
||||
SELECT count(*) FROM candidate_hidden_organizations
|
||||
WHERE user_id = NEW.user_id
|
||||
) >= 1000 THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'check_violation',
|
||||
CONSTRAINT = 'candidate_hidden_organizations_limit',
|
||||
TABLE = 'candidate_hidden_organizations',
|
||||
MESSAGE = 'a candidate hides at most 1000 organizations';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER candidate_hidden_organizations_enforce_limit
|
||||
BEFORE INSERT ON candidate_hidden_organizations
|
||||
FOR EACH ROW EXECUTE FUNCTION candidate_hidden_organizations_enforce_limit();
|
||||
|
||||
-- The append-only history of the settings: what the candidate published,
|
||||
-- announced, and hid, and when. It keeps the published field set and its
|
||||
-- changes with their times, which the C2 record of the ledger does not carry.
|
||||
-- A revocation of C2 and a lapse of the search status are computed and are not
|
||||
-- events. The rows hold identifiers, card field codes, and times; never a
|
||||
-- profile value or a name. The hide and unhide records are sensitive: they say
|
||||
-- which employer a candidate avoids.
|
||||
--
|
||||
-- It is evidence like the consent ledger. A trigger refuses every UPDATE, and
|
||||
-- refuses DELETE while the account is confirmed (the same condition as
|
||||
-- consent_records_refuse_delete, which the retention rule and the account
|
||||
-- deletion procedure extend in their own migration). The account reference
|
||||
-- cascades, so the unverified account cleanup removes the rows of an account
|
||||
-- it deletes and a confirmed account is protected by the trigger.
|
||||
-- TRUNCATE stays allowed for test isolation.
|
||||
CREATE TABLE candidate_privacy_events (
|
||||
-- UUIDv7 generated in Go.
|
||||
id uuid NOT NULL,
|
||||
user_id uuid NOT NULL,
|
||||
kind text NOT NULL,
|
||||
occurred_at timestamptz NOT NULL,
|
||||
-- The published field set after a publication event; empty for a closing;
|
||||
-- NULL for every other kind.
|
||||
fields text [],
|
||||
-- The C2 record behind a publication or republication; NULL otherwise.
|
||||
consent_record_id uuid,
|
||||
consent_purpose text GENERATED ALWAYS AS (
|
||||
CASE WHEN consent_record_id IS NOT NULL THEN 'c2' END
|
||||
) STORED,
|
||||
-- The organization of a hiding event. Only the identifier is kept: the
|
||||
-- candidate's read resolves the current name, so the history holds no
|
||||
-- text about an organization.
|
||||
organization_id uuid,
|
||||
CONSTRAINT candidate_privacy_events_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT candidate_privacy_events_user_id_fkey FOREIGN KEY (user_id)
|
||||
REFERENCES users (id) ON DELETE CASCADE,
|
||||
-- MATCH SIMPLE skips the check while consent_purpose is NULL.
|
||||
CONSTRAINT candidate_privacy_events_consent_fkey FOREIGN KEY (
|
||||
consent_record_id, user_id, consent_purpose
|
||||
) REFERENCES consent_records (id, subject_id, purpose) ON DELETE RESTRICT,
|
||||
CONSTRAINT candidate_privacy_events_organization_id_fkey FOREIGN KEY (
|
||||
organization_id
|
||||
) REFERENCES organizations (id) ON DELETE RESTRICT,
|
||||
CONSTRAINT candidate_privacy_events_kind_known CHECK (
|
||||
kind IN (
|
||||
'publication_opened', 'publication_changed', 'publication_closed',
|
||||
'search_status_confirmed', 'search_status_cleared',
|
||||
'organization_hidden', 'organization_unhidden'
|
||||
)
|
||||
),
|
||||
CONSTRAINT candidate_privacy_events_shape CHECK (
|
||||
(
|
||||
kind IN ('publication_opened', 'publication_changed')
|
||||
AND fields IS NOT NULL
|
||||
AND cardinality(fields) > 0
|
||||
AND candidate_card_fields_are_canonical(fields)
|
||||
AND consent_record_id IS NOT NULL
|
||||
AND organization_id IS NULL
|
||||
)
|
||||
OR (
|
||||
kind = 'publication_closed'
|
||||
AND fields IS NOT NULL
|
||||
AND cardinality(fields) = 0
|
||||
AND consent_record_id IS NULL
|
||||
AND organization_id IS NULL
|
||||
)
|
||||
OR (
|
||||
kind IN ('search_status_confirmed', 'search_status_cleared')
|
||||
AND fields IS NULL
|
||||
AND consent_record_id IS NULL
|
||||
AND organization_id IS NULL
|
||||
)
|
||||
OR (
|
||||
kind IN ('organization_hidden', 'organization_unhidden')
|
||||
AND fields IS NULL
|
||||
AND consent_record_id IS NULL
|
||||
AND organization_id IS NOT NULL
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- Serves the candidate's history, newest first.
|
||||
CREATE INDEX candidate_privacy_events_user_occurred_idx
|
||||
ON candidate_privacy_events (user_id, occurred_at DESC, id DESC);
|
||||
|
||||
-- Refuses every UPDATE of an event with SQLSTATE 23000 and the constraint
|
||||
-- name candidate_privacy_events_immutable. The message quotes no row value.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_privacy_events_refuse_update() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'candidate_privacy_events_immutable',
|
||||
TABLE = 'candidate_privacy_events',
|
||||
MESSAGE = 'privacy events are append-only: record a new event instead';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER candidate_privacy_events_refuse_update
|
||||
BEFORE UPDATE ON candidate_privacy_events
|
||||
FOR EACH ROW EXECUTE FUNCTION candidate_privacy_events_refuse_update();
|
||||
|
||||
-- Allows deleting an event only while its account is not confirmed: the
|
||||
-- unverified account cleanup. The history of a confirmed account is evidence
|
||||
-- and stays (SQLSTATE 23000, constraint candidate_privacy_events_retained).
|
||||
-- The retention rule and the right to erasure extend this condition in their
|
||||
-- own migration.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_privacy_events_refuse_delete() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM users
|
||||
WHERE users.id = OLD.user_id AND users.email_verified_at IS NOT NULL
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'candidate_privacy_events_retained',
|
||||
TABLE = 'candidate_privacy_events',
|
||||
MESSAGE = 'privacy events of a confirmed account are retained';
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER candidate_privacy_events_refuse_delete
|
||||
BEFORE DELETE ON candidate_privacy_events
|
||||
FOR EACH ROW EXECUTE FUNCTION candidate_privacy_events_refuse_delete();
|
||||
|
||||
-- The cascade of the account deletion runs after the account row is gone, so
|
||||
-- the delete trigger above cannot see that the account was confirmed. This
|
||||
-- trigger on users refuses deleting a confirmed account that has history, with
|
||||
-- the same constraint name, before the cascade starts.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_privacy_events_protect_account() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF OLD.email_verified_at IS NOT NULL AND EXISTS (
|
||||
SELECT 1 FROM candidate_privacy_events WHERE user_id = OLD.id
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'candidate_privacy_events_retained',
|
||||
TABLE = 'candidate_privacy_events',
|
||||
MESSAGE = 'privacy events of a confirmed account are retained';
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER candidate_privacy_events_protect_account
|
||||
BEFORE DELETE ON users
|
||||
FOR EACH ROW EXECUTE FUNCTION candidate_privacy_events_protect_account();
|
||||
|
||||
-- The only way an organization-facing read may see a publication: published
|
||||
-- by the candidate AND backed by a C2 record that is not revoked. Every read
|
||||
-- on behalf of an organization (the search, the card, the contact read) must
|
||||
-- select from this view and must add NOT EXISTS over
|
||||
-- candidate_hidden_organizations for the reading organization. Reading
|
||||
-- candidate_publications directly is reserved for the candidate's own
|
||||
-- settings queries; a test over db/queries enforces the list.
|
||||
CREATE VIEW candidate_effective_publications
|
||||
WITH (security_invoker = true) AS
|
||||
SELECT
|
||||
publication.user_id,
|
||||
publication.fields,
|
||||
publication.published_at,
|
||||
publication.version
|
||||
FROM candidate_publications AS publication
|
||||
INNER JOIN consent_records AS consent
|
||||
ON consent.id = publication.consent_record_id
|
||||
WHERE publication.state = 'published' AND consent.revoked_at IS NULL;
|
||||
|
||||
-- +goose Down
|
||||
DROP VIEW candidate_effective_publications;
|
||||
DROP TRIGGER candidate_privacy_events_protect_account ON users;
|
||||
DROP FUNCTION candidate_privacy_events_protect_account();
|
||||
DROP TABLE candidate_privacy_events;
|
||||
DROP FUNCTION candidate_privacy_events_refuse_delete();
|
||||
DROP FUNCTION candidate_privacy_events_refuse_update();
|
||||
DROP TABLE candidate_hidden_organizations;
|
||||
DROP FUNCTION candidate_hidden_organizations_enforce_limit();
|
||||
DROP TABLE candidate_search_statuses;
|
||||
DROP FUNCTION candidate_search_statuses_check_policy();
|
||||
DROP TABLE candidate_publications;
|
||||
DROP INDEX consent_records_id_subject_purpose_key;
|
||||
DROP FUNCTION candidate_card_fields_are_canonical(text []);
|
||||
@@ -0,0 +1,81 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// directPublicationReaders are the only queries that may name the table
|
||||
// candidate_publications. The first three are the candidate's own settings
|
||||
// queries; every read on behalf of an organization must go through the view
|
||||
// candidate_effective_publications (published and backed by an unrevoked C2)
|
||||
// and exclude the hidden organizations, as ReadPublicationVisibleToOrganization
|
||||
// does. A new query that reads the table directly fails this test, so it
|
||||
// cannot leak a closed or revoked publication by accident.
|
||||
//
|
||||
// Only queries/*.sql are covered: the project keeps SQL in sqlc queries and
|
||||
// migrations, and the standards forbid raw SQL in Go code.
|
||||
var directPublicationReaders = []string{
|
||||
"ReadCandidatePublication",
|
||||
"InsertCandidatePublication",
|
||||
"UpdateCandidatePublication",
|
||||
}
|
||||
|
||||
var (
|
||||
// sqlc accepts both comment forms and tolerates trailing whitespace.
|
||||
queryHeaderPattern = regexp.MustCompile(`(?m)^(?:--|/\*)[ \t]*name:[ \t]+(\w+)[ \t]+:\w+[ \t]*(?:\*/)?[ \t]*$`)
|
||||
// Any mention of the marker, to count headers that the pattern missed.
|
||||
queryMarkerPattern = regexp.MustCompile(`(?i)name:\s*\w+\s+:\w+`)
|
||||
publicationTableName = regexp.MustCompile(`(?i)\bcandidate_publications\b`)
|
||||
effectiveViewName = regexp.MustCompile(`(?i)\bcandidate_effective_publications\b`)
|
||||
hiddenTableName = regexp.MustCompile(`(?i)\bcandidate_hidden_organizations\b`)
|
||||
lineComment = regexp.MustCompile(`(?m)--.*$`)
|
||||
blockComment = regexp.MustCompile(`(?s)/\*.*?\*/`)
|
||||
)
|
||||
|
||||
func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
|
||||
files, err := filepath.Glob("queries/*.sql")
|
||||
if err != nil || len(files) == 0 {
|
||||
t.Fatalf("list the query files = %v, %v", files, err)
|
||||
}
|
||||
var found []string
|
||||
for _, file := range files {
|
||||
content, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", file, err)
|
||||
}
|
||||
text := string(content)
|
||||
headers := queryHeaderPattern.FindAllStringSubmatchIndex(text, -1)
|
||||
if markers := len(queryMarkerPattern.FindAllString(text, -1)); markers != len(headers) {
|
||||
t.Fatalf("%s has %d query markers but %d parsed headers: use the sqlc header form so every query is checked", file, markers, len(headers))
|
||||
}
|
||||
for index, header := range headers {
|
||||
end := len(text)
|
||||
if index+1 < len(headers) {
|
||||
end = headers[index+1][0]
|
||||
}
|
||||
// Comments may name the table; statements may not.
|
||||
statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "")
|
||||
name := text[header[2]:header[3]]
|
||||
if publicationTableName.MatchString(statement) {
|
||||
found = append(found, name)
|
||||
}
|
||||
if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) {
|
||||
t.Errorf("%s reads candidate_effective_publications without excluding candidate_hidden_organizations", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(found)
|
||||
want := slices.Clone(directPublicationReaders)
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(found, want) {
|
||||
t.Fatalf("queries that name candidate_publications = %v, want only %v: organization-facing reads use candidate_effective_publications", found, want)
|
||||
}
|
||||
if strings.Contains(strings.Join(found, ","), "Visible") {
|
||||
t.Fatal("the organization-facing read names the table directly")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
-- Queries of the candidate visibility settings (TASK-088): the publication of
|
||||
-- the card, the search status, the hidden organizations, and the history of
|
||||
-- these settings. Every statement is scoped by the candidate's user_id, and
|
||||
-- no statement selects another account's row. No statement reads or writes a
|
||||
-- profile value, a name, or a contact. A candidate with no row is closed, not
|
||||
-- looking, and hides nobody; no statement creates a row except an explicit
|
||||
-- act of the candidate.
|
||||
|
||||
-- Reads the publication with the revocation state of the C2 record behind it
|
||||
-- in one statement, so the stored setting and the ledger come from one
|
||||
-- snapshot. The effective state is computed from them: published only while
|
||||
-- consent_revoked_at is NULL. No row means the candidate never published.
|
||||
-- name: ReadCandidatePublication :one
|
||||
SELECT
|
||||
candidate_publications.user_id,
|
||||
candidate_publications.state,
|
||||
candidate_publications.fields,
|
||||
candidate_publications.consent_record_id,
|
||||
candidate_publications.published_at,
|
||||
candidate_publications.closed_at,
|
||||
candidate_publications.version,
|
||||
candidate_publications.created_at,
|
||||
candidate_publications.updated_at,
|
||||
consent_records.revoked_at AS consent_revoked_at
|
||||
FROM candidate_publications
|
||||
INNER JOIN consent_records
|
||||
ON consent_records.id = candidate_publications.consent_record_id
|
||||
WHERE candidate_publications.user_id = sqlc.arg(user_id);
|
||||
|
||||
-- Stores the first publication at version 1. No row returns when the account
|
||||
-- already has a row, so a first publication that lost a race with another
|
||||
-- one is answered as a version conflict. The foreign key refuses a record
|
||||
-- that is not a C2 record of this account.
|
||||
-- name: InsertCandidatePublication :one
|
||||
INSERT INTO candidate_publications (
|
||||
user_id,
|
||||
state,
|
||||
fields,
|
||||
consent_record_id,
|
||||
published_at,
|
||||
closed_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
sqlc.arg(user_id),
|
||||
sqlc.arg(state),
|
||||
sqlc.arg(fields),
|
||||
sqlc.arg(consent_record_id),
|
||||
sqlc.arg(published_at),
|
||||
sqlc.narg(closed_at),
|
||||
1,
|
||||
sqlc.arg(at),
|
||||
sqlc.arg(at)
|
||||
)
|
||||
ON CONFLICT (user_id) DO NOTHING
|
||||
RETURNING user_id, version;
|
||||
|
||||
-- Replaces the publication over the version the caller read and advances the
|
||||
-- version in the same statement. No row returns for a stale version, which
|
||||
-- the caller answers as a version conflict. The update time never moves back,
|
||||
-- as in the profile.
|
||||
-- name: UpdateCandidatePublication :one
|
||||
UPDATE candidate_publications
|
||||
SET
|
||||
state = sqlc.arg(state),
|
||||
fields = sqlc.arg(fields),
|
||||
consent_record_id = sqlc.arg(consent_record_id),
|
||||
published_at = sqlc.arg(published_at),
|
||||
closed_at = sqlc.narg(closed_at),
|
||||
version = candidate_publications.version + 1,
|
||||
updated_at = greatest(candidate_publications.updated_at, sqlc.arg(at))
|
||||
WHERE
|
||||
candidate_publications.user_id = sqlc.arg(user_id)
|
||||
AND candidate_publications.version = sqlc.arg(expected_version)
|
||||
RETURNING user_id, version;
|
||||
|
||||
-- No row means the status was never set, which reads as not looking. The
|
||||
-- lapse is computed by the caller from lapses_at and its clock and is never
|
||||
-- written.
|
||||
-- name: ReadCandidateSearchStatus :one
|
||||
SELECT
|
||||
user_id,
|
||||
status,
|
||||
confirmed_at,
|
||||
lapses_at,
|
||||
policy_version_id,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM candidate_search_statuses
|
||||
WHERE user_id = sqlc.arg(user_id);
|
||||
|
||||
-- Stores the first status at version 1; no row returns when one exists.
|
||||
-- name: InsertCandidateSearchStatus :one
|
||||
INSERT INTO candidate_search_statuses (
|
||||
user_id,
|
||||
status,
|
||||
confirmed_at,
|
||||
lapses_at,
|
||||
policy_version_id,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
sqlc.arg(user_id),
|
||||
sqlc.arg(status),
|
||||
sqlc.narg(confirmed_at),
|
||||
sqlc.narg(lapses_at),
|
||||
sqlc.narg(policy_version_id),
|
||||
1,
|
||||
sqlc.arg(at),
|
||||
sqlc.arg(at)
|
||||
)
|
||||
ON CONFLICT (user_id) DO NOTHING
|
||||
RETURNING user_id, version;
|
||||
|
||||
-- Replaces the status over the version the caller read. Looking also stores
|
||||
-- the new confirmation, lapse time, and policy version; not looking clears
|
||||
-- them. It never names the publication or the hidden organizations.
|
||||
-- name: UpdateCandidateSearchStatus :one
|
||||
UPDATE candidate_search_statuses
|
||||
SET
|
||||
status = sqlc.arg(status),
|
||||
confirmed_at = sqlc.narg(confirmed_at),
|
||||
lapses_at = sqlc.narg(lapses_at),
|
||||
policy_version_id = sqlc.narg(policy_version_id),
|
||||
version = candidate_search_statuses.version + 1,
|
||||
updated_at = greatest(candidate_search_statuses.updated_at, sqlc.arg(at))
|
||||
WHERE
|
||||
candidate_search_statuses.user_id = sqlc.arg(user_id)
|
||||
AND candidate_search_statuses.version = sqlc.arg(expected_version)
|
||||
RETURNING user_id, version;
|
||||
|
||||
-- Hides one organization. No row returns when the pair already exists, and
|
||||
-- the caller reads the existing record with its original time. The foreign key
|
||||
-- refuses an unknown organization (SQLSTATE 23503); the caller answers it
|
||||
-- exactly like an organization the candidate cannot see. The trigger refuses
|
||||
-- the 1001st record (candidate_hidden_organizations_limit). The trigger runs
|
||||
-- before the conflict check, so the caller reads the existing record first
|
||||
-- and a repeat at the limit is never refused.
|
||||
-- name: InsertCandidateHiddenOrganization :one
|
||||
INSERT INTO candidate_hidden_organizations (
|
||||
user_id,
|
||||
organization_id,
|
||||
hidden_at
|
||||
) VALUES (
|
||||
sqlc.arg(user_id),
|
||||
sqlc.arg(organization_id),
|
||||
sqlc.arg(at)
|
||||
)
|
||||
ON CONFLICT (user_id, organization_id) DO NOTHING
|
||||
RETURNING user_id, organization_id, hidden_at;
|
||||
|
||||
-- Reads one hiding of the candidate with the current name of the
|
||||
-- organization.
|
||||
-- name: GetCandidateHiddenOrganization :one
|
||||
SELECT
|
||||
candidate_hidden_organizations.organization_id,
|
||||
organizations.name AS organization_name,
|
||||
candidate_hidden_organizations.hidden_at
|
||||
FROM candidate_hidden_organizations
|
||||
INNER JOIN organizations
|
||||
ON organizations.id = candidate_hidden_organizations.organization_id
|
||||
WHERE
|
||||
candidate_hidden_organizations.user_id = sqlc.arg(user_id)
|
||||
AND candidate_hidden_organizations.organization_id = sqlc.arg(organization_id);
|
||||
|
||||
-- Lifts one hiding. No row returns when the organization was not hidden, so
|
||||
-- the caller writes the history event only for a real deletion and answers
|
||||
-- 204 either way.
|
||||
-- name: DeleteCandidateHiddenOrganization :one
|
||||
DELETE FROM candidate_hidden_organizations
|
||||
WHERE user_id = sqlc.arg(user_id) AND organization_id = sqlc.arg(organization_id)
|
||||
RETURNING organization_id;
|
||||
|
||||
-- One page of the candidate's hidden organizations, newest first with the
|
||||
-- organization identifier as the tie-breaker. The page continues after the
|
||||
-- (hidden_at, organization_id) position of the last record of the previous
|
||||
-- page.
|
||||
-- name: ListCandidateHiddenOrganizations :many
|
||||
SELECT
|
||||
candidate_hidden_organizations.organization_id,
|
||||
organizations.name AS organization_name,
|
||||
candidate_hidden_organizations.hidden_at
|
||||
FROM candidate_hidden_organizations
|
||||
INNER JOIN organizations
|
||||
ON organizations.id = candidate_hidden_organizations.organization_id
|
||||
WHERE
|
||||
candidate_hidden_organizations.user_id = sqlc.arg(user_id)
|
||||
AND (
|
||||
sqlc.narg(after_hidden_at)::timestamptz IS NULL
|
||||
OR (
|
||||
candidate_hidden_organizations.hidden_at,
|
||||
candidate_hidden_organizations.organization_id
|
||||
) < (
|
||||
sqlc.narg(after_hidden_at)::timestamptz,
|
||||
sqlc.narg(after_organization_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY
|
||||
candidate_hidden_organizations.hidden_at DESC,
|
||||
candidate_hidden_organizations.organization_id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- Counts the hiding records of one candidate for the settings read.
|
||||
-- name: CountCandidateHiddenOrganizations :one
|
||||
SELECT count(*) AS total
|
||||
FROM candidate_hidden_organizations
|
||||
WHERE user_id = sqlc.arg(user_id);
|
||||
|
||||
-- Appends one event to the settings history. The row holds identifiers, card
|
||||
-- field codes, and times, never a name; the caller
|
||||
-- writes it in the transaction of the change it records.
|
||||
-- name: InsertCandidatePrivacyEvent :exec
|
||||
INSERT INTO candidate_privacy_events (
|
||||
id,
|
||||
user_id,
|
||||
kind,
|
||||
occurred_at,
|
||||
fields,
|
||||
consent_record_id,
|
||||
organization_id
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(user_id),
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(occurred_at),
|
||||
sqlc.narg(fields),
|
||||
sqlc.narg(consent_record_id),
|
||||
sqlc.narg(organization_id)
|
||||
);
|
||||
|
||||
-- One page of the candidate's settings history, newest first with the event
|
||||
-- identifier as the tie-breaker. The organization name is resolved here, at
|
||||
-- read time, and is the current name. The page continues after the
|
||||
-- (occurred_at, id) position of the last event of the previous page.
|
||||
-- name: ListCandidatePrivacyEvents :many
|
||||
SELECT
|
||||
candidate_privacy_events.id,
|
||||
candidate_privacy_events.kind,
|
||||
candidate_privacy_events.occurred_at,
|
||||
candidate_privacy_events.fields,
|
||||
candidate_privacy_events.consent_record_id,
|
||||
candidate_privacy_events.organization_id,
|
||||
organizations.name AS organization_name
|
||||
FROM candidate_privacy_events
|
||||
LEFT JOIN organizations
|
||||
ON organizations.id = candidate_privacy_events.organization_id
|
||||
WHERE
|
||||
candidate_privacy_events.user_id = sqlc.arg(user_id)
|
||||
AND (
|
||||
sqlc.narg(after_occurred_at)::timestamptz IS NULL
|
||||
OR (candidate_privacy_events.occurred_at, candidate_privacy_events.id) < (
|
||||
sqlc.narg(after_occurred_at)::timestamptz,
|
||||
sqlc.narg(after_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY
|
||||
candidate_privacy_events.occurred_at DESC,
|
||||
candidate_privacy_events.id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- Takes the candidate's current unrevoked C2 record for a publication and
|
||||
-- keeps it locked until the transaction ends. The share lock conflicts with
|
||||
-- the revocation stamp (an UPDATE of the row), so a revocation either commits
|
||||
-- before this statement, which then returns no row and the publication is
|
||||
-- refused, or waits until the publication transaction commits and closes the
|
||||
-- card right after. The caller must run it in the transaction that writes the
|
||||
-- publication and must re-read the effective state (ReadCandidatePublication)
|
||||
-- in that transaction to build its response.
|
||||
-- name: LockCurrentC2Record :one
|
||||
SELECT id
|
||||
FROM consent_records
|
||||
WHERE
|
||||
subject_id = sqlc.arg(subject_id)
|
||||
AND purpose = 'c2'
|
||||
AND revoked_at IS NULL
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE;
|
||||
|
||||
-- The organization-facing read of a candidate's publication: the effective
|
||||
-- view (published and backed by an unrevoked C2) and no hiding of the reading
|
||||
-- organization. No row means the organization reads nothing, whichever of
|
||||
-- the reasons applies, so it cannot tell a hidden candidate from an
|
||||
-- unpublished one. Every organization-facing read of a publication starts
|
||||
-- from this shape (TASK-185, TASK-089, TASK-090).
|
||||
-- name: ReadPublicationVisibleToOrganization :one
|
||||
SELECT
|
||||
effective.user_id,
|
||||
effective.fields,
|
||||
effective.published_at
|
||||
FROM candidate_effective_publications AS effective
|
||||
WHERE
|
||||
effective.user_id = sqlc.arg(user_id)
|
||||
AND NOT exists(
|
||||
SELECT 1 FROM candidate_hidden_organizations AS hidden
|
||||
WHERE
|
||||
hidden.user_id = effective.user_id
|
||||
AND hidden.organization_id = sqlc.arg(organization_id)
|
||||
);
|
||||
Reference in new issue
Block a user