1057 lines
54 KiB
Go
1057 lines
54 KiB
Go
//go:build integration
|
|
|
|
package integration_test
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"slices"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/usecase/policy"
|
|
)
|
|
|
|
const (
|
|
candidatePrivacyTestTimeout = 3 * time.Minute
|
|
privacyForeignKeyViolation = "23503"
|
|
privacyCheckViolation = "23514"
|
|
privacyIntegrityViolation = "23000"
|
|
privacyC2Version = "c2-2026-10-01"
|
|
privacyC1Version = "c1-2026-10-01"
|
|
)
|
|
|
|
var (
|
|
candidatePublicationsTable = pgx.Identifier{"candidate_publications"}
|
|
candidateSearchStatusesTable = pgx.Identifier{"candidate_search_statuses"}
|
|
candidateHiddenOrganizationsTable = pgx.Identifier{"candidate_hidden_organizations"}
|
|
candidatePrivacyEventsTable = pgx.Identifier{"candidate_privacy_events"}
|
|
// candidatePrivacyTables reference users, organizations, and the consent
|
|
// ledger, so every TRUNCATE of those names them through
|
|
// usersDependentTables.
|
|
candidatePrivacyTables = []pgx.Identifier{
|
|
candidatePrivacyEventsTable, candidateHiddenOrganizationsTable, candidateSearchStatusesTable, candidatePublicationsTable,
|
|
}
|
|
)
|
|
|
|
// candidatePrivacyFixture works on the bootstrap database. The tables are
|
|
// truncated between subtests; the product policy is immutable and shared.
|
|
type candidatePrivacyFixture struct {
|
|
ctx context.Context
|
|
pool *pgxpool.Pool
|
|
queries *sqlc.Queries
|
|
identity identityFixture
|
|
organizations organizationFixture
|
|
ledger *postgresadapter.ConsentStore
|
|
policy domain.PolicyVersion
|
|
now time.Time
|
|
}
|
|
|
|
func TestCandidatePrivacyStorage(t *testing.T) {
|
|
env := bootstrap(t, postgresService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout)
|
|
defer cancel()
|
|
pool := env.newPool(ctx, t)
|
|
now := time.Now().UTC().Truncate(time.Microsecond)
|
|
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
|
|
policies := postgresadapter.NewPolicyStore(pool)
|
|
if _, err := policy.NewPublisher(policies.Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
|
|
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
|
|
}
|
|
latest, err := policies.Policies().GetLatest(ctx, domain.ProductPolicyKey)
|
|
if err != nil {
|
|
t.Fatalf("GetLatest(product) error = %v", err)
|
|
}
|
|
fixture := candidatePrivacyFixture{
|
|
ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity,
|
|
organizations: organizationFixture{ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now},
|
|
ledger: postgresadapter.NewConsentStore(pool),
|
|
policy: latest,
|
|
now: now,
|
|
}
|
|
reset := func(t *testing.T) {
|
|
t.Helper()
|
|
truncateTables(ctx, t, pool, usersDependentTables...)
|
|
}
|
|
|
|
t.Run("a new profile has no published state and nothing hidden", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
// Saving a full profile, as the profile contract does, opens nothing.
|
|
profiles := candidateProfileFixture{ctx: ctx, pool: pool, queries: fixture.queries, identity: identity, now: now}
|
|
profiles.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna Sokolova")}, 0)
|
|
|
|
for _, table := range candidatePrivacyTables {
|
|
assertRowCount(ctx, t, pool, table, 0)
|
|
}
|
|
if _, err := fixture.queries.ReadCandidatePublication(ctx, uuidParam(candidate.ID)); !errors.Is(err, pgx.ErrNoRows) {
|
|
t.Fatalf("ReadCandidatePublication() error = %v, want no row: the profile is closed by default", err)
|
|
}
|
|
if _, err := fixture.queries.ReadCandidateSearchStatus(ctx, uuidParam(candidate.ID)); !errors.Is(err, pgx.ErrNoRows) {
|
|
t.Fatalf("ReadCandidateSearchStatus() error = %v, want no row", err)
|
|
}
|
|
if total, err := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(candidate.ID)); err != nil || total != 0 {
|
|
t.Fatalf("CountCandidateHiddenOrganizations() = %d, %v, want 0", total, err)
|
|
}
|
|
// The domain reads the absence as a closed profile at version 0.
|
|
closed, err := domain.NewPublication(candidate.ID)
|
|
if err != nil || closed.State() != domain.PublicationClosed || closed.ClosedReason() != domain.ClosedNeverPublished || closed.Version() != 0 {
|
|
t.Fatalf("NewPublication() = %v %v v%d, %v, want closed and never published", closed.State(), closed.ClosedReason(), closed.Version(), err)
|
|
}
|
|
})
|
|
|
|
t.Run("publication refers to the C2 record and a revocation closes it", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
|
|
published := fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack, domain.CardFieldCategories)
|
|
if published.State() != domain.PublicationPublished || published.Version() != 1 || published.ConsentRecordID() != c2.ID() ||
|
|
!published.Fields().Equal(domainFields(t, domain.CardFieldCategories, domain.CardFieldStack)) {
|
|
t.Fatalf("stored publication = %v v%d, want published at version 1 under the C2 record", published.State(), published.Version())
|
|
}
|
|
|
|
// Revoking C2 in the ledger closes the card with no write to the setting.
|
|
before := fixture.rawPublication(t, candidate.ID)
|
|
fixture.revokeC2(t, candidate.ID, now)
|
|
if after := fixture.rawPublication(t, candidate.ID); after != before {
|
|
t.Fatalf("revoking C2 changed the stored publication: %+v -> %+v", before, after)
|
|
}
|
|
revoked := fixture.loadPublication(t, candidate.ID)
|
|
if revoked.State() != domain.PublicationClosed || revoked.ClosedReason() != domain.ClosedConsentRevoked || !revoked.Fields().IsEmpty() {
|
|
t.Fatalf("after the revocation = %v (%v), want closed because the consent was revoked", revoked.State(), revoked.ClosedReason())
|
|
}
|
|
|
|
// A new C2 grant publishes nothing by itself.
|
|
newC2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(time.Minute))
|
|
if again := fixture.loadPublication(t, candidate.ID); again.State() != domain.PublicationClosed {
|
|
t.Fatalf("a new C2 grant left the card %v, want closed until the candidate publishes again", again.State())
|
|
}
|
|
reopened := fixture.publish(t, candidate.ID, newC2.ID(), 1, domain.CardFieldStack)
|
|
if reopened.State() != domain.PublicationPublished || reopened.ConsentRecordID() != newC2.ID() || reopened.Version() != 2 {
|
|
t.Fatalf("republished = %v v%d under %s, want the new record at version 2", reopened.State(), reopened.Version(), reopened.ConsentRecordID())
|
|
}
|
|
|
|
// Closing is an explicit change that keeps the evidence.
|
|
change, err := reopened.Apply(mustPublicationRequest(t, domain.PublicationClosed), 2, uuid.Nil, now.Add(time.Hour))
|
|
if err != nil || !change.Changed {
|
|
t.Fatalf("Apply(close) = %+v, %v", change, err)
|
|
}
|
|
fixture.storePublication(t, change.Publication, 2)
|
|
closed := fixture.loadPublication(t, candidate.ID)
|
|
if closed.State() != domain.PublicationClosed || closed.ClosedReason() != domain.ClosedByCandidate || closed.Version() != 3 || !closed.PublishedAt().Equal(reopened.PublishedAt()) {
|
|
t.Fatalf("closed = %v (%v) v%d, want closed by the candidate with the last publication time", closed.State(), closed.ClosedReason(), closed.Version())
|
|
}
|
|
})
|
|
|
|
t.Run("the publication row refuses a consent that is not the account's C2 and fields that are not card fields", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
other := fixture.candidate(t, "other@example.com")
|
|
c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
otherC2 := fixture.grant(t, other.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
c1 := fixture.grant(t, candidate.ID, domain.ConsentPurposePersonalData, privacyC1Version, now.Add(-time.Hour))
|
|
|
|
insert := func(user uuid.UUID, consent uuid.UUID, state string, fields []string, closedAt pgtype.Timestamptz) error {
|
|
_, err := fixture.queries.InsertCandidatePublication(ctx, sqlc.InsertCandidatePublicationParams{
|
|
UserID: uuidParam(user), State: state, Fields: fields, ConsentRecordID: uuidParam(consent),
|
|
PublishedAt: timeParam(now), ClosedAt: closedAt, At: timeParam(now),
|
|
})
|
|
return err
|
|
}
|
|
for _, test := range []struct {
|
|
name string
|
|
err error
|
|
sqlstate string
|
|
}{
|
|
{"another account's C2", insert(candidate.ID, otherC2.ID(), "published", []string{"stack"}, pgtype.Timestamptz{}), privacyForeignKeyViolation},
|
|
{"a C1 record", insert(candidate.ID, c1.ID(), "published", []string{"stack"}, pgtype.Timestamptz{}), privacyForeignKeyViolation},
|
|
{"an unknown record", insert(candidate.ID, uuid.New(), "published", []string{"stack"}, pgtype.Timestamptz{}), privacyForeignKeyViolation},
|
|
{"the full name as a field", insert(candidate.ID, c2.ID(), "published", []string{"full_name"}, pgtype.Timestamptz{}), privacyCheckViolation},
|
|
{"a phone as a field", insert(candidate.ID, c2.ID(), "published", []string{"phone"}, pgtype.Timestamptz{}), privacyCheckViolation},
|
|
{"fields out of order", insert(candidate.ID, c2.ID(), "published", []string{"stack", "categories"}, pgtype.Timestamptz{}), privacyCheckViolation},
|
|
{"a repeated field", insert(candidate.ID, c2.ID(), "published", []string{"stack", "stack"}, pgtype.Timestamptz{}), privacyCheckViolation},
|
|
{"published without a field", insert(candidate.ID, c2.ID(), "published", []string{}, pgtype.Timestamptz{}), privacyCheckViolation},
|
|
{"closed with a field", insert(candidate.ID, c2.ID(), "closed", []string{"stack"}, timeParam(now)), privacyCheckViolation},
|
|
{"an unknown state", insert(candidate.ID, c2.ID(), "draft", []string{"stack"}, pgtype.Timestamptz{}), privacyCheckViolation},
|
|
} {
|
|
if code := sqlState(test.err); code != test.sqlstate {
|
|
t.Errorf("%s: SQLSTATE = %q (%v), want %s", test.name, code, test.err, test.sqlstate)
|
|
}
|
|
}
|
|
assertRowCount(ctx, t, pool, candidatePublicationsTable, 0)
|
|
|
|
// A C2 record that a publication refers to cannot be deleted.
|
|
fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack)
|
|
_, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1`, c2.ID())
|
|
if code := sqlState(err); code == "" {
|
|
t.Fatal("a C2 record behind a publication was deleted")
|
|
}
|
|
})
|
|
|
|
t.Run("a stale version updates nothing and a first publication is created once", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack)
|
|
|
|
_, err := fixture.queries.InsertCandidatePublication(ctx, sqlc.InsertCandidatePublicationParams{
|
|
UserID: uuidParam(candidate.ID), State: "published", Fields: []string{"stack"}, ConsentRecordID: uuidParam(c2.ID()),
|
|
PublishedAt: timeParam(now), At: timeParam(now),
|
|
})
|
|
if !errors.Is(err, pgx.ErrNoRows) {
|
|
t.Fatalf("a second first-publication error = %v, want no row", err)
|
|
}
|
|
_, err = fixture.queries.UpdateCandidatePublication(ctx, sqlc.UpdateCandidatePublicationParams{
|
|
UserID: uuidParam(candidate.ID), ExpectedVersion: 0, State: "published", Fields: []string{"location"}, ConsentRecordID: uuidParam(c2.ID()),
|
|
PublishedAt: timeParam(now), At: timeParam(now),
|
|
})
|
|
if !errors.Is(err, pgx.ErrNoRows) {
|
|
t.Fatalf("an update over a stale version error = %v, want no row", err)
|
|
}
|
|
if got := fixture.loadPublication(t, candidate.ID); got.Version() != 1 || !got.Fields().Equal(domainFields(t, domain.CardFieldStack)) {
|
|
t.Fatal("a stale update changed the publication")
|
|
}
|
|
})
|
|
|
|
t.Run("looking stores its confirmation under the policy version and lapses without a write", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
status := fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 0, now)
|
|
if status.StoredValue() != domain.SearchStatusLooking || !status.ConfirmedAt().Equal(now) || status.PolicyVersionID() != fixture.policy.ID() || status.Version() != 1 {
|
|
t.Fatalf("stored status = %v confirmed %v under %v, want looking confirmed now under the policy version", status.StoredValue(), status.ConfirmedAt(), status.PolicyVersionID())
|
|
}
|
|
// The interval is the one of the policy version, 30 days in the demo.
|
|
interval := fixture.policy.Policy().SearchStatus.SearchingConfirmationInterval.Duration()
|
|
if !status.LapsesAt().Equal(now.Add(interval)) {
|
|
t.Fatalf("lapses at %v, want %v", status.LapsesAt(), now.Add(interval))
|
|
}
|
|
|
|
before := fixture.rawSearchStatus(t, candidate.ID)
|
|
lapsedAt := status.LapsesAt().Add(time.Second)
|
|
if loaded := fixture.loadSearchStatus(t, candidate.ID); loaded.Effective(lapsedAt) != domain.SearchStatusNotLooking || !loaded.Lapsed(lapsedAt) || loaded.Effective(now) != domain.SearchStatusLooking {
|
|
t.Fatal("the stored status does not lapse at its lapse time")
|
|
}
|
|
if fixture.rawSearchStatus(t, candidate.ID) != before {
|
|
t.Fatal("a lapse changed the stored status: it must be computed, never written")
|
|
}
|
|
|
|
// Confirming again after the lapse is an explicit change over the current version.
|
|
confirmed := fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 1, lapsedAt)
|
|
if confirmed.Version() != 2 || !confirmed.ConfirmedAt().Equal(lapsedAt) || confirmed.Effective(lapsedAt) != domain.SearchStatusLooking {
|
|
t.Fatalf("confirmed again = v%d %v, want version 2 and looking", confirmed.Version(), confirmed.Effective(lapsedAt))
|
|
}
|
|
cleared := fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusNotLooking, 2, lapsedAt.Add(time.Hour))
|
|
if cleared.StoredValue() != domain.SearchStatusNotLooking || !cleared.ConfirmedAt().IsZero() || cleared.Version() != 3 {
|
|
t.Fatalf("cleared = %v v%d, want not_looking carrying no confirmation", cleared.StoredValue(), cleared.Version())
|
|
}
|
|
})
|
|
|
|
t.Run("the status row refuses a looking without its confirmation and has no link to a consent", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
insert := func(status string, confirmed, lapses pgtype.Timestamptz, policyID pgtype.UUID) error {
|
|
_, err := fixture.queries.InsertCandidateSearchStatus(ctx, sqlc.InsertCandidateSearchStatusParams{
|
|
UserID: uuidParam(candidate.ID), Status: status, ConfirmedAt: confirmed, LapsesAt: lapses, PolicyVersionID: policyID, At: timeParam(now),
|
|
})
|
|
return err
|
|
}
|
|
policyID := uuidParam(fixture.policy.ID().UUID())
|
|
for _, test := range []struct {
|
|
name string
|
|
err error
|
|
sqlstate string
|
|
}{
|
|
{"looking without a confirmation", insert("looking", pgtype.Timestamptz{}, pgtype.Timestamptz{}, policyID), privacyCheckViolation},
|
|
{"looking without a lapse time", insert("looking", timeParam(now), pgtype.Timestamptz{}, policyID), privacyCheckViolation},
|
|
{"looking that lapses before it is confirmed", insert("looking", timeParam(now), timeParam(now.Add(-time.Hour)), policyID), privacyCheckViolation},
|
|
{"looking without a policy version", insert("looking", timeParam(now), timeParam(now.Add(time.Hour)), pgtype.UUID{}), privacyCheckViolation},
|
|
{"looking under an unknown policy version", insert("looking", timeParam(now), timeParam(now.Add(time.Hour)), uuidParam(uuid.New())), privacyForeignKeyViolation},
|
|
{"not looking with a confirmation", insert("not_looking", timeParam(now), timeParam(now.Add(time.Hour)), policyID), privacyCheckViolation},
|
|
{"an unknown status", insert("open", pgtype.Timestamptz{}, pgtype.Timestamptz{}, pgtype.UUID{}), privacyCheckViolation},
|
|
} {
|
|
if code := sqlState(test.err); code != test.sqlstate {
|
|
t.Errorf("%s: SQLSTATE = %q (%v), want %s", test.name, code, test.err, test.sqlstate)
|
|
}
|
|
}
|
|
|
|
// The status is not a consent: its only foreign key is the account; the policy version is checked by a trigger.
|
|
rows, err := pool.Query(ctx, `
|
|
SELECT confrelid::regclass::text FROM pg_constraint
|
|
WHERE conrelid = 'candidate_search_statuses'::regclass AND contype = 'f' ORDER BY 1`)
|
|
if err != nil {
|
|
t.Fatalf("list the foreign keys: %v", err)
|
|
}
|
|
references, err := pgx.CollectRows(rows, pgx.RowTo[string])
|
|
if err != nil || !slices.Equal(references, []string{"users"}) {
|
|
t.Fatalf("candidate_search_statuses references %v (%v), want only users (the policy version is checked by a trigger)", references, err)
|
|
}
|
|
var consentColumns int
|
|
if err := pool.QueryRow(ctx, `
|
|
SELECT count(*) FROM information_schema.columns
|
|
WHERE table_name IN ('candidate_search_statuses', 'candidate_hidden_organizations') AND column_name LIKE '%consent%'`).Scan(&consentColumns); err != nil || consentColumns != 0 {
|
|
t.Fatalf("the status and hiding tables have %d consent columns (%v), want none", consentColumns, err)
|
|
}
|
|
})
|
|
|
|
t.Run("the search status leaves C2, the publication, and the hidden organizations as they were", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
employer := fixture.organizations.employer(t, "owner@example.com")
|
|
organization := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now)
|
|
c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldCategories, domain.CardFieldLocation)
|
|
fixture.hide(t, candidate.ID, organization.ID(), now)
|
|
|
|
consentBefore := fixture.rawConsentRecords(t, candidate.ID)
|
|
publicationBefore := fixture.rawPublication(t, candidate.ID)
|
|
hiddenBefore := fixture.rawHidden(t, candidate.ID)
|
|
|
|
fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 0, now.Add(time.Minute))
|
|
fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 1, now.Add(2*time.Minute))
|
|
fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusNotLooking, 2, now.Add(3*time.Minute))
|
|
|
|
if fixture.rawConsentRecords(t, candidate.ID) != consentBefore {
|
|
t.Error("updating the search status changed the consent ledger")
|
|
}
|
|
if fixture.rawPublication(t, candidate.ID) != publicationBefore {
|
|
t.Error("updating the search status changed the publication")
|
|
}
|
|
if fixture.rawHidden(t, candidate.ID) != hiddenBefore {
|
|
t.Error("updating the search status changed the hidden organizations")
|
|
}
|
|
if published := fixture.loadPublication(t, candidate.ID); published.State() != domain.PublicationPublished || published.Version() != 1 {
|
|
t.Fatal("updating the search status changed the effective publication")
|
|
}
|
|
})
|
|
|
|
t.Run("a hidden organization belongs to the candidate and is unique", func(t *testing.T) {
|
|
reset(t)
|
|
first := fixture.candidate(t, "first@example.com")
|
|
second := fixture.candidate(t, "second@example.com")
|
|
employer := fixture.organizations.employer(t, "owner@example.com")
|
|
acme := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now)
|
|
globex := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Globex Synthetic LLC"), now)
|
|
|
|
fixture.hide(t, first.ID, acme.ID(), now)
|
|
// The pair is unique: a second insert returns no row and keeps the original time.
|
|
_, err := fixture.queries.InsertCandidateHiddenOrganization(ctx, sqlc.InsertCandidateHiddenOrganizationParams{
|
|
UserID: uuidParam(first.ID), OrganizationID: uuidParam(acme.ID()), At: timeParam(now.Add(time.Hour)),
|
|
})
|
|
if !errors.Is(err, pgx.ErrNoRows) {
|
|
t.Fatalf("hiding the same organization twice error = %v, want no row", err)
|
|
}
|
|
record, err := fixture.queries.GetCandidateHiddenOrganization(ctx, sqlc.GetCandidateHiddenOrganizationParams{UserID: uuidParam(first.ID), OrganizationID: uuidParam(acme.ID())})
|
|
if err != nil || !record.HiddenAt.Time.Equal(now) || record.OrganizationName != "Acme Synthetic LLC" {
|
|
t.Fatalf("GetCandidateHiddenOrganization() = %+v, %v, want the original record with the current name", record, err)
|
|
}
|
|
if _, err := fixture.pool.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, first.ID, acme.ID(), now); sqlState(err) != organizationUniqueViolation {
|
|
t.Fatalf("a raw duplicate hiding SQLSTATE = %q, want %s", sqlState(err), organizationUniqueViolation)
|
|
}
|
|
|
|
// Another candidate hides the same organization independently and reads only their own records.
|
|
fixture.hide(t, second.ID, acme.ID(), now.Add(time.Minute))
|
|
fixture.hide(t, second.ID, globex.ID(), now.Add(2*time.Minute))
|
|
if total, _ := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(first.ID)); total != 1 {
|
|
t.Fatalf("the first candidate has %d hidden organizations, want 1", total)
|
|
}
|
|
page, err := fixture.queries.ListCandidateHiddenOrganizations(ctx, sqlc.ListCandidateHiddenOrganizationsParams{UserID: uuidParam(second.ID), RowLimit: 1})
|
|
if err != nil || len(page) != 1 || uuid.UUID(page[0].OrganizationID.Bytes) != globex.ID() {
|
|
t.Fatalf("first page = %+v, %v, want the newest hiding", page, err)
|
|
}
|
|
next, err := fixture.queries.ListCandidateHiddenOrganizations(ctx, sqlc.ListCandidateHiddenOrganizationsParams{
|
|
UserID: uuidParam(second.ID), RowLimit: 10, AfterHiddenAt: page[0].HiddenAt, AfterOrganizationID: page[0].OrganizationID,
|
|
})
|
|
if err != nil || len(next) != 1 || uuid.UUID(next[0].OrganizationID.Bytes) != acme.ID() {
|
|
t.Fatalf("next page = %+v, %v, want the older hiding", next, err)
|
|
}
|
|
|
|
// An unknown organization is refused by the reference, and the caller
|
|
// answers it as it answers an organization the candidate cannot see.
|
|
_, err = fixture.queries.InsertCandidateHiddenOrganization(ctx, sqlc.InsertCandidateHiddenOrganizationParams{
|
|
UserID: uuidParam(first.ID), OrganizationID: uuidParam(uuid.New()), At: timeParam(now),
|
|
})
|
|
if sqlState(err) != privacyForeignKeyViolation {
|
|
t.Fatalf("hiding an unknown organization SQLSTATE = %q, want %s", sqlState(err), privacyForeignKeyViolation)
|
|
}
|
|
// Lifting a hiding deletes it once; a repeat deletes nothing.
|
|
lift := sqlc.DeleteCandidateHiddenOrganizationParams{UserID: uuidParam(first.ID), OrganizationID: uuidParam(acme.ID())}
|
|
if deleted, err := fixture.queries.DeleteCandidateHiddenOrganization(ctx, lift); err != nil || uuid.UUID(deleted.Bytes) != acme.ID() {
|
|
t.Fatalf("DeleteCandidateHiddenOrganization() = %v, %v, want the organization", deleted, err)
|
|
}
|
|
if _, err := fixture.queries.DeleteCandidateHiddenOrganization(ctx, lift); !errors.Is(err, pgx.ErrNoRows) {
|
|
t.Fatalf("a repeated delete error = %v, want no row", err)
|
|
}
|
|
if total, _ := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(second.ID)); total != 2 {
|
|
t.Fatalf("lifting the first candidate's hiding left the second with %d records, want 2", total)
|
|
}
|
|
// The organization cannot be deleted while a candidate hides it.
|
|
if _, err := pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, globex.ID()); sqlState(err) == "" {
|
|
t.Fatal("an organization that a candidate hides was deleted")
|
|
}
|
|
})
|
|
|
|
t.Run("a candidate hides at most 1000 organizations", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
employer := fixture.organizations.employer(t, "owner@example.com")
|
|
limit := domain.MaxHiddenOrganizations
|
|
// The organizations are created in bulk with one owner; the deferred
|
|
// owner trigger sees the membership of the same transaction.
|
|
tx, err := pool.Begin(ctx)
|
|
if err != nil {
|
|
t.Fatalf("begin: %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)
|
|
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 {
|
|
t.Fatalf("create organizations: %v", err)
|
|
}
|
|
if _, err := tx.Exec(ctx, `
|
|
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
|
|
SELECT gen_random_uuid(), id, $1, 'owner', 'active', $2, $2 FROM organizations WHERE name LIKE 'Bulk %'`, employer.ID, now); err != nil {
|
|
t.Fatalf("create memberships: %v", err)
|
|
}
|
|
if _, err := tx.Exec(ctx, `
|
|
INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at)
|
|
SELECT $1, id, $2 FROM organizations WHERE name LIKE 'Bulk %' ORDER BY id LIMIT $3`, candidate.ID, now, limit); err != nil {
|
|
t.Fatalf("hide %d organizations: %v", limit, err)
|
|
}
|
|
_, err = tx.Exec(ctx, `
|
|
INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at)
|
|
SELECT $1, id, $2 FROM organizations WHERE name LIKE 'Bulk %' ORDER BY id DESC LIMIT 1 OFFSET 0`, candidate.ID, now)
|
|
var pgError *pgconn.PgError
|
|
if !errors.As(err, &pgError) || pgError.Code != privacyCheckViolation || pgError.ConstraintName != "candidate_hidden_organizations_limit" {
|
|
t.Fatalf("hiding organization %d error = %v, want SQLSTATE %s on candidate_hidden_organizations_limit", limit+1, err, privacyCheckViolation)
|
|
}
|
|
})
|
|
|
|
t.Run("the history is append-only and keeps the published fields with their times", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
employer := fixture.organizations.employer(t, "owner@example.com")
|
|
organization := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now)
|
|
c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
|
|
published := fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack)
|
|
change, err := published.Apply(mustPublicationRequest(t, domain.PublicationPublished, domain.CardFieldStack, domain.CardFieldLocation), 1, c2.ID(), now.Add(time.Minute))
|
|
if err != nil {
|
|
t.Fatalf("Apply() error = %v", err)
|
|
}
|
|
fixture.storePublication(t, change.Publication, 1)
|
|
fixture.recordPublicationEvent(t, change, now.Add(time.Minute))
|
|
fixture.hide(t, candidate.ID, organization.ID(), now.Add(2*time.Minute))
|
|
|
|
page, err := fixture.queries.ListCandidatePrivacyEvents(ctx, sqlc.ListCandidatePrivacyEventsParams{UserID: uuidParam(candidate.ID), RowLimit: 10})
|
|
if err != nil || len(page) != 3 {
|
|
t.Fatalf("ListCandidatePrivacyEvents() = %d rows, %v, want 3", len(page), err)
|
|
}
|
|
kinds := []string{page[0].Kind, page[1].Kind, page[2].Kind}
|
|
if !slices.Equal(kinds, []string{"organization_hidden", "publication_changed", "publication_opened"}) {
|
|
t.Fatalf("event kinds = %v, want newest first", kinds)
|
|
}
|
|
if !slices.Equal(page[1].Fields, []string{"location", "stack"}) || uuid.UUID(page[1].ConsentRecordID.Bytes) != c2.ID() || !page[1].OccurredAt.Time.Equal(now.Add(time.Minute)) {
|
|
t.Fatalf("the change event = %v under %v at %v, want the published fields, the C2 record, and the time", page[1].Fields, page[1].ConsentRecordID, page[1].OccurredAt.Time)
|
|
}
|
|
if page[0].OrganizationName.String != "Acme Synthetic LLC" {
|
|
t.Fatalf("the hiding event names %q, want the current name resolved at read time", page[0].OrganizationName.String)
|
|
}
|
|
var nameColumns int
|
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns WHERE table_name = 'candidate_privacy_events' AND column_name LIKE '%name%'`).Scan(&nameColumns); err != nil || nameColumns != 0 {
|
|
t.Fatalf("the history table has %d name columns (%v), want none: it stores identifiers only", nameColumns, err)
|
|
}
|
|
// Pagination continues after the position of the last row.
|
|
next, err := fixture.queries.ListCandidatePrivacyEvents(ctx, sqlc.ListCandidatePrivacyEventsParams{
|
|
UserID: uuidParam(candidate.ID), RowLimit: 10, AfterOccurredAt: page[0].OccurredAt, AfterID: page[0].ID,
|
|
})
|
|
if err != nil || len(next) != 2 {
|
|
t.Fatalf("next page = %d rows, %v, want 2", len(next), err)
|
|
}
|
|
|
|
// Append-only: no UPDATE, and no DELETE once the account is confirmed.
|
|
for _, test := range []struct{ statement, constraint string }{
|
|
{`UPDATE candidate_privacy_events SET occurred_at = occurred_at + interval '1 hour'`, "candidate_privacy_events_immutable"},
|
|
} {
|
|
_, err := pool.Exec(ctx, test.statement)
|
|
var pgError *pgconn.PgError
|
|
if !errors.As(err, &pgError) || pgError.Code != privacyIntegrityViolation || pgError.ConstraintName != test.constraint {
|
|
t.Fatalf("%q error = %v, want SQLSTATE %s on %s", test.statement, err, privacyIntegrityViolation, test.constraint)
|
|
}
|
|
}
|
|
if _, err := pool.Exec(ctx, `UPDATE users SET email_verified_at = $2 WHERE id = $1`, candidate.ID, now); err != nil {
|
|
t.Fatalf("confirm the account: %v", err)
|
|
}
|
|
_, err = pool.Exec(ctx, `DELETE FROM candidate_privacy_events`)
|
|
var retained *pgconn.PgError
|
|
if !errors.As(err, &retained) || retained.Code != privacyIntegrityViolation || retained.ConstraintName != "candidate_privacy_events_retained" {
|
|
t.Fatalf("deleting the history of a confirmed account error = %v, want SQLSTATE %s on candidate_privacy_events_retained", err, privacyIntegrityViolation)
|
|
}
|
|
for name, params := range map[string]sqlc.InsertCandidatePrivacyEventParams{
|
|
"a publication without fields": {Kind: "publication_opened", Fields: []string{}, ConsentRecordID: uuidParam(c2.ID())},
|
|
"a publication without a consent": {Kind: "publication_changed", Fields: []string{"stack"}},
|
|
"a hiding without an organization": {Kind: "organization_hidden"},
|
|
"a status event with an organization": {Kind: "search_status_cleared", OrganizationID: uuidParam(organization.ID())},
|
|
"a closing with a field": {Kind: "publication_closed", Fields: []string{"stack"}},
|
|
"an unknown kind": {Kind: "published"},
|
|
} {
|
|
params.ID, params.UserID, params.OccurredAt = uuidParam(uuid.Must(uuid.NewV7())), uuidParam(candidate.ID), timeParam(now)
|
|
if err := fixture.queries.InsertCandidatePrivacyEvent(ctx, params); sqlState(err) != privacyCheckViolation {
|
|
t.Errorf("%s: SQLSTATE = %q (%v), want %s", name, sqlState(err), err, privacyCheckViolation)
|
|
}
|
|
}
|
|
// An account with history cannot be deleted until a procedure handles it.
|
|
if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, candidate.ID); sqlState(err) == "" {
|
|
t.Fatal("an account with consent and privacy history was deleted")
|
|
}
|
|
})
|
|
|
|
t.Run("closing over a revoked C2 stores the closing and records it", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack)
|
|
fixture.revokeC2(t, candidate.ID, now)
|
|
|
|
revoked := fixture.loadPublication(t, candidate.ID)
|
|
change, err := revoked.Apply(mustPublicationRequest(t, domain.PublicationClosed), 1, uuid.Nil, now.Add(time.Minute))
|
|
if err != nil || !change.Changed || change.Event != domain.PrivacyEventPublicationClosed {
|
|
t.Fatalf("Apply(close over a revoked C2) = %+v, %v, want a recorded closing", change, err)
|
|
}
|
|
fixture.storePublication(t, change.Publication, 1)
|
|
fixture.recordPublicationEvent(t, change, now.Add(time.Minute))
|
|
|
|
var stored string
|
|
if err := pool.QueryRow(ctx, `SELECT state FROM candidate_publications WHERE user_id = $1`, candidate.ID).Scan(&stored); err != nil || stored != "closed" {
|
|
t.Fatalf("stored state = %q (%v), want the row normalized to closed", stored, err)
|
|
}
|
|
if closed := fixture.loadPublication(t, candidate.ID); closed.ClosedReason() != domain.ClosedByCandidate || closed.Version() != 2 {
|
|
t.Fatalf("closed = %v v%d, want closed by the candidate at version 2", closed.ClosedReason(), closed.Version())
|
|
}
|
|
page, err := fixture.queries.ListCandidatePrivacyEvents(ctx, sqlc.ListCandidatePrivacyEventsParams{UserID: uuidParam(candidate.ID), RowLimit: 10})
|
|
if err != nil || len(page) != 2 || page[0].Kind != "publication_closed" {
|
|
t.Fatalf("history = %d rows, %v, want the closing newest", len(page), err)
|
|
}
|
|
})
|
|
|
|
t.Run("an organization reads a publication only through the effective view and not when hidden", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
employer := fixture.organizations.employer(t, "owner@example.com")
|
|
acme := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now)
|
|
globex := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Globex Synthetic LLC"), now)
|
|
read := func(organization uuid.UUID) error {
|
|
_, err := fixture.queries.ReadPublicationVisibleToOrganization(ctx, sqlc.ReadPublicationVisibleToOrganizationParams{
|
|
UserID: uuidParam(candidate.ID), OrganizationID: uuidParam(organization),
|
|
})
|
|
return err
|
|
}
|
|
if err := read(acme.ID()); !errors.Is(err, pgx.ErrNoRows) {
|
|
t.Fatalf("a closed-by-default profile read error = %v, want no row", err)
|
|
}
|
|
c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
published := fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack)
|
|
if err := read(acme.ID()); err != nil {
|
|
t.Fatalf("a published profile read error = %v, want a row", err)
|
|
}
|
|
fixture.hide(t, candidate.ID, acme.ID(), now)
|
|
if err := read(acme.ID()); !errors.Is(err, pgx.ErrNoRows) {
|
|
t.Fatalf("a hidden organization read error = %v, want no row, the same as an unpublished profile", err)
|
|
}
|
|
if err := read(globex.ID()); err != nil {
|
|
t.Fatalf("another organization read error = %v, want a row", err)
|
|
}
|
|
fixture.revokeC2(t, candidate.ID, now)
|
|
if err := read(globex.ID()); !errors.Is(err, pgx.ErrNoRows) {
|
|
t.Fatalf("a read after the C2 revocation error = %v, want no row", err)
|
|
}
|
|
_ = published
|
|
})
|
|
|
|
t.Run("a revocation racing with a publication either refuses it or closes the card after it", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
|
|
// The publication holds the share lock: the revocation waits for it.
|
|
tx, err := pool.Begin(ctx)
|
|
if err != nil {
|
|
t.Fatalf("begin: %v", err)
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
locked, err := fixture.queries.WithTx(tx).LockCurrentC2Record(ctx, uuidParam(candidate.ID))
|
|
if err != nil || uuid.UUID(locked.Bytes) != c2.ID() {
|
|
t.Fatalf("LockCurrentC2Record() = %v, %v, want the C2 record", locked, err)
|
|
}
|
|
if _, err := fixture.queries.WithTx(tx).InsertCandidatePublication(ctx, sqlc.InsertCandidatePublicationParams{
|
|
UserID: uuidParam(candidate.ID), State: "published", Fields: []string{"stack"}, ConsentRecordID: locked, PublishedAt: timeParam(now), At: timeParam(now),
|
|
}); err != nil {
|
|
t.Fatalf("InsertCandidatePublication() error = %v", err)
|
|
}
|
|
revoked := make(chan error, 1)
|
|
go func() {
|
|
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
|
|
SubjectID: candidate.ID, Purpose: domain.ConsentPurposePublication,
|
|
Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: now.Add(time.Minute),
|
|
})
|
|
if err == nil {
|
|
_, err = fixture.ledger.ConsentLedger().Revoke(ctx, revocation)
|
|
}
|
|
revoked <- err
|
|
}()
|
|
select {
|
|
case err := <-revoked:
|
|
t.Fatalf("the revocation did not wait for the publication transaction (error = %v)", err)
|
|
case <-time.After(300 * time.Millisecond):
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
t.Fatalf("commit: %v", err)
|
|
}
|
|
if err := <-revoked; err != nil {
|
|
t.Fatalf("the revocation error = %v", err)
|
|
}
|
|
if after := fixture.loadPublication(t, candidate.ID); after.State() != domain.PublicationClosed || after.ClosedReason() != domain.ClosedConsentRevoked {
|
|
t.Fatalf("after the race = %v (%v), want closed because the consent was revoked", after.State(), after.ClosedReason())
|
|
}
|
|
|
|
// A revocation that committed first leaves nothing to lock: the publication is refused.
|
|
if _, err := fixture.queries.LockCurrentC2Record(ctx, uuidParam(candidate.ID)); !errors.Is(err, pgx.ErrNoRows) {
|
|
t.Fatalf("LockCurrentC2Record() after the revocation error = %v, want no row", err)
|
|
}
|
|
})
|
|
|
|
t.Run("the unverified account cleanup removes its hidden organizations and history and spares a confirmed account", func(t *testing.T) {
|
|
reset(t)
|
|
stale := fixture.candidate(t, "stale@example.com")
|
|
confirmed := fixture.candidate(t, "confirmed@example.com")
|
|
employer := fixture.organizations.employer(t, "owner@example.com")
|
|
acme := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now)
|
|
fixture.hide(t, stale.ID, acme.ID(), now)
|
|
fixture.hide(t, confirmed.ID, acme.ID(), now)
|
|
if _, err := pool.Exec(ctx, `UPDATE users SET email_verified_at = $3 WHERE id = ANY($1) OR id = $2`, []uuid.UUID{confirmed.ID}, employer.ID, now); err != nil {
|
|
t.Fatalf("confirm the accounts: %v", err)
|
|
}
|
|
deleted, err := fixture.queries.DeleteUnverifiedUsersRegisteredBefore(ctx, sqlc.DeleteUnverifiedUsersRegisteredBeforeParams{Cutoff: timeParam(now.Add(48 * time.Hour)), BatchLimit: 10})
|
|
if err != nil || deleted != 1 {
|
|
t.Fatalf("DeleteUnverifiedUsersRegisteredBefore() = %d, %v, want the one unverified account", deleted, err)
|
|
}
|
|
assertRowCount(ctx, t, pool, candidateHiddenOrganizationsTable, 1)
|
|
assertRowCount(ctx, t, pool, candidatePrivacyEventsTable, 1)
|
|
// A confirmed account is not deleted through the history either.
|
|
if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, confirmed.ID); sqlState(err) == "" {
|
|
t.Fatal("a confirmed account with privacy history was deleted")
|
|
}
|
|
})
|
|
|
|
t.Run("the cleanup deletes unverified accounts with a C2, a publication, and history, whatever the C2 history", func(t *testing.T) {
|
|
reset(t)
|
|
// The cleanup deletes the consent records and the account in one
|
|
// statement of data-modifying CTEs. The cascade from the account to the
|
|
// publication, which the restricting reference to the C2 record would
|
|
// block, depends on the order in which PostgreSQL applies them; this
|
|
// scenario fails if a change to the statement or to the references
|
|
// breaks that order.
|
|
full := fixture.candidate(t, "full@example.com")
|
|
fullC2 := fixture.grant(t, full.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
fixture.publish(t, full.ID, fullC2.ID(), 0, domain.CardFieldStack)
|
|
|
|
regranted := fixture.candidate(t, "regranted@example.com")
|
|
oldC2 := fixture.grant(t, regranted.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-2*time.Hour))
|
|
fixture.publish(t, regranted.ID, oldC2.ID(), 0, domain.CardFieldLocation)
|
|
fixture.revokeC2(t, regranted.ID, now.Add(-time.Hour))
|
|
fixture.grant(t, regranted.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-30*time.Minute))
|
|
|
|
consentOnly := fixture.candidate(t, "consent-only@example.com")
|
|
fixture.grant(t, consentOnly.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour))
|
|
|
|
deleted, err := fixture.queries.DeleteUnverifiedUsersRegisteredBefore(ctx, sqlc.DeleteUnverifiedUsersRegisteredBeforeParams{Cutoff: timeParam(now.Add(48 * time.Hour)), BatchLimit: 10})
|
|
if err != nil || deleted != 3 {
|
|
t.Fatalf("DeleteUnverifiedUsersRegisteredBefore() = %d, %v, want the three unverified accounts", deleted, err)
|
|
}
|
|
for _, table := range slices.Concat(candidatePrivacyTables, []pgx.Identifier{consentRecordsTable, {"users"}}) {
|
|
assertRowCount(ctx, t, pool, table, 0)
|
|
}
|
|
})
|
|
|
|
t.Run("concurrent hidings at the bound let exactly one through", func(t *testing.T) {
|
|
reset(t)
|
|
candidate := fixture.candidate(t, "candidate@example.com")
|
|
employer := fixture.organizations.employer(t, "owner@example.com")
|
|
const parallel = 8
|
|
limit := domain.MaxHiddenOrganizations
|
|
tx, err := pool.Begin(ctx)
|
|
if err != nil {
|
|
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 {
|
|
t.Fatalf("create organizations: %v", err)
|
|
}
|
|
if _, err := tx.Exec(ctx, `
|
|
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
|
|
SELECT gen_random_uuid(), id, $1, 'owner', 'active', $2, $2 FROM organizations WHERE name LIKE 'Bulk %'`, employer.ID, now); err != nil {
|
|
t.Fatalf("create memberships: %v", err)
|
|
}
|
|
if _, err := tx.Exec(ctx, `
|
|
INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at)
|
|
SELECT $1, id, $2 FROM (SELECT id FROM organizations WHERE name LIKE 'Bulk %' ORDER BY id LIMIT $3) AS first`, candidate.ID, now, limit-1); err != nil {
|
|
t.Fatalf("hide %d organizations: %v", limit-1, err)
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
t.Fatalf("commit: %v", err)
|
|
}
|
|
rows, err := pool.Query(ctx, `
|
|
SELECT id FROM organizations WHERE name LIKE 'Bulk %' AND id NOT IN (SELECT organization_id FROM candidate_hidden_organizations)`)
|
|
if err != nil {
|
|
t.Fatalf("list the free organizations: %v", err)
|
|
}
|
|
free, err := pgx.CollectRows(rows, pgx.RowTo[uuid.UUID])
|
|
if err != nil || len(free) != parallel {
|
|
t.Fatalf("free organizations = %d, %v, want %d", len(free), err, parallel)
|
|
}
|
|
results := make([]error, parallel)
|
|
var wait sync.WaitGroup
|
|
for index := range parallel {
|
|
wait.Add(1)
|
|
go func() {
|
|
defer wait.Done()
|
|
_, results[index] = pool.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, candidate.ID, free[index], now)
|
|
}()
|
|
}
|
|
wait.Wait()
|
|
succeeded := 0
|
|
for _, err := range results {
|
|
var pgError *pgconn.PgError
|
|
switch {
|
|
case err == nil:
|
|
succeeded++
|
|
case errors.As(err, &pgError) && pgError.ConstraintName == "candidate_hidden_organizations_limit":
|
|
default:
|
|
t.Fatalf("a concurrent hiding error = %v, want success or the limit", err)
|
|
}
|
|
}
|
|
if succeeded != 1 {
|
|
t.Fatalf("%d concurrent hidings succeeded at the bound, want exactly 1", succeeded)
|
|
}
|
|
if total, _ := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(candidate.ID)); int(total) != limit {
|
|
t.Fatalf("hidden organizations = %d, want exactly %d", total, limit)
|
|
}
|
|
})
|
|
|
|
t.Run("the privacy tables hold no profile value, name, contact, or file", func(t *testing.T) {
|
|
rows, err := pool.Query(ctx, `
|
|
SELECT table_name || '.' || column_name FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name LIKE 'candidate\_%' AND table_name IN (
|
|
'candidate_publications', 'candidate_search_statuses', 'candidate_hidden_organizations', 'candidate_privacy_events')
|
|
ORDER BY 1`)
|
|
if err != nil {
|
|
t.Fatalf("list the columns: %v", err)
|
|
}
|
|
columns, err := pgx.CollectRows(rows, pgx.RowTo[string])
|
|
if err != nil {
|
|
t.Fatalf("collect the columns: %v", err)
|
|
}
|
|
for _, column := range columns {
|
|
for _, forbidden := range []string{"email", "phone", "telegram", "contact", "full_name", "salary", "resume", "file", "value", "claim"} {
|
|
if containsWord(column, forbidden) {
|
|
t.Errorf("the column %s looks like %q", column, forbidden)
|
|
}
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
func containsWord(column, word string) bool {
|
|
for _, part := range splitIdentifier(column) {
|
|
if part == word {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func splitIdentifier(identifier string) []string {
|
|
var parts []string
|
|
start := 0
|
|
for index, character := range identifier {
|
|
if character == '_' || character == '.' {
|
|
parts = append(parts, identifier[start:index])
|
|
start = index + 1
|
|
}
|
|
}
|
|
return append(parts, identifier[start:])
|
|
}
|
|
|
|
func sqlState(err error) string {
|
|
var pgError *pgconn.PgError
|
|
if errors.As(err, &pgError) {
|
|
return pgError.Code
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func uuidParam(id uuid.UUID) pgtype.UUID { return pgtype.UUID{Bytes: id, Valid: true} }
|
|
|
|
func timeParam(at time.Time) pgtype.Timestamptz { return pgtype.Timestamptz{Time: at, Valid: true} }
|
|
|
|
func domainFields(t *testing.T, fields ...domain.CardField) domain.CardFieldSet {
|
|
t.Helper()
|
|
set, err := domain.NewCardFieldSet(fields)
|
|
if err != nil {
|
|
t.Fatalf("NewCardFieldSet() error = %v", err)
|
|
}
|
|
return set
|
|
}
|
|
|
|
func mustPublicationRequest(t *testing.T, state domain.PublicationState, fields ...domain.CardField) domain.PublicationRequest {
|
|
t.Helper()
|
|
request, err := domain.NewPublicationRequest(state, fields)
|
|
if err != nil {
|
|
t.Fatalf("NewPublicationRequest() error = %v", err)
|
|
}
|
|
return request
|
|
}
|
|
|
|
func (fixture candidatePrivacyFixture) candidate(t *testing.T, email string) domain.User {
|
|
t.Helper()
|
|
return fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.now.Add(-24*time.Hour))
|
|
}
|
|
|
|
func (fixture candidatePrivacyFixture) grant(t *testing.T, subject uuid.UUID, purpose domain.ConsentPurpose, version domain.ConsentTextVersion, at time.Time) domain.ConsentRecord {
|
|
t.Helper()
|
|
text, err := fixture.ledger.ConsentTexts().Get(fixture.ctx, purpose, version)
|
|
if err != nil {
|
|
t.Fatalf("ConsentTexts().Get(%s, %s) error = %v", purpose, version, err)
|
|
}
|
|
grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{
|
|
SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), TextHash: text.Hash(),
|
|
Source: domain.ConsentSourceConsentSettings, GrantedAt: at,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewConsentGrant() error = %v", err)
|
|
}
|
|
record, created, err := fixture.ledger.ConsentLedger().Grant(fixture.ctx, grant)
|
|
if err != nil || !created {
|
|
t.Fatalf("Grant(%s) = %v, %v, want a new record", purpose, created, err)
|
|
}
|
|
return record
|
|
}
|
|
|
|
func (fixture candidatePrivacyFixture) revokeC2(t *testing.T, subject uuid.UUID, at time.Time) {
|
|
t.Helper()
|
|
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
|
|
SubjectID: subject, Purpose: domain.ConsentPurposePublication,
|
|
Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: at,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewConsentRevocation() error = %v", err)
|
|
}
|
|
if revoked, err := fixture.ledger.ConsentLedger().Revoke(fixture.ctx, revocation); err != nil || len(revoked) == 0 {
|
|
t.Fatalf("Revoke(c2) = %v, %v, want the record", revoked, err)
|
|
}
|
|
}
|
|
|
|
// loadPublication reads the stored setting with its ledger state the way a
|
|
// repository does and returns the closed default when there is no row.
|
|
func (fixture candidatePrivacyFixture) loadPublication(t *testing.T, userID uuid.UUID) domain.Publication {
|
|
t.Helper()
|
|
row, err := fixture.queries.ReadCandidatePublication(fixture.ctx, uuidParam(userID))
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
publication, err := domain.NewPublication(userID)
|
|
if err != nil {
|
|
t.Fatalf("NewPublication() error = %v", err)
|
|
}
|
|
return publication
|
|
}
|
|
if err != nil {
|
|
t.Fatalf("ReadCandidatePublication() error = %v", err)
|
|
}
|
|
publication, err := domain.RestorePublication(domain.StoredPublication{
|
|
UserID: userID, State: row.State, Fields: row.Fields, ConsentRecordID: row.ConsentRecordID.Bytes,
|
|
PublishedAt: row.PublishedAt.Time, ClosedAt: row.ClosedAt.Time, Version: row.Version, ConsentRevoked: row.ConsentRevokedAt.Valid,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("RestorePublication() error = %v", err)
|
|
}
|
|
return publication
|
|
}
|
|
|
|
// publish applies a publication request over expectedVersion with the given
|
|
// C2 record and stores the result the way a repository does.
|
|
func (fixture candidatePrivacyFixture) publish(t *testing.T, userID, consent uuid.UUID, expectedVersion int64, fields ...domain.CardField) domain.Publication {
|
|
t.Helper()
|
|
current := fixture.loadPublication(t, userID)
|
|
change, err := current.Apply(mustPublicationRequest(t, domain.PublicationPublished, fields...), expectedVersion, consent, fixture.now)
|
|
if err != nil || !change.Changed {
|
|
t.Fatalf("Apply(publish) = %+v, %v, want a change", change, err)
|
|
}
|
|
fixture.storePublication(t, change.Publication, expectedVersion)
|
|
fixture.recordPublicationEvent(t, change, fixture.now)
|
|
return fixture.loadPublication(t, userID)
|
|
}
|
|
|
|
func (fixture candidatePrivacyFixture) storePublication(t *testing.T, publication domain.Publication, expectedVersion int64) {
|
|
t.Helper()
|
|
closedAt := pgtype.Timestamptz{}
|
|
if !publication.ClosedAt().IsZero() {
|
|
closedAt = timeParam(publication.ClosedAt())
|
|
}
|
|
if expectedVersion == 0 {
|
|
if _, err := fixture.queries.InsertCandidatePublication(fixture.ctx, sqlc.InsertCandidatePublicationParams{
|
|
UserID: uuidParam(publication.UserID()), State: string(publication.StoredState()), Fields: publication.StoredFields(),
|
|
ConsentRecordID: uuidParam(publication.ConsentRecordID()), PublishedAt: timeParam(publication.PublishedAt()), ClosedAt: closedAt, At: timeParam(fixture.now),
|
|
}); err != nil {
|
|
t.Fatalf("InsertCandidatePublication() error = %v", err)
|
|
}
|
|
return
|
|
}
|
|
if _, err := fixture.queries.UpdateCandidatePublication(fixture.ctx, sqlc.UpdateCandidatePublicationParams{
|
|
UserID: uuidParam(publication.UserID()), ExpectedVersion: expectedVersion, State: string(publication.StoredState()), Fields: publication.StoredFields(),
|
|
ConsentRecordID: uuidParam(publication.ConsentRecordID()), PublishedAt: timeParam(publication.PublishedAt()), ClosedAt: closedAt, At: timeParam(fixture.now),
|
|
}); err != nil {
|
|
t.Fatalf("UpdateCandidatePublication() error = %v", err)
|
|
}
|
|
}
|
|
|
|
func (fixture candidatePrivacyFixture) recordPublicationEvent(t *testing.T, change domain.PublicationChange, at time.Time) {
|
|
t.Helper()
|
|
event, err := domain.NewPublicationEvent(change, at)
|
|
if err != nil {
|
|
t.Fatalf("NewPublicationEvent() error = %v", err)
|
|
}
|
|
params := sqlc.InsertCandidatePrivacyEventParams{
|
|
ID: uuidParam(event.ID()), UserID: uuidParam(event.UserID()), Kind: string(event.Kind()), OccurredAt: timeParam(event.OccurredAt()),
|
|
}
|
|
if event.HasFieldSet() {
|
|
params.Fields = event.Fields().Codes()
|
|
}
|
|
if event.ConsentRecordID() != uuid.Nil {
|
|
params.ConsentRecordID = uuidParam(event.ConsentRecordID())
|
|
}
|
|
if err := fixture.queries.InsertCandidatePrivacyEvent(fixture.ctx, params); err != nil {
|
|
t.Fatalf("InsertCandidatePrivacyEvent() error = %v", err)
|
|
}
|
|
}
|
|
|
|
func (fixture candidatePrivacyFixture) loadSearchStatus(t *testing.T, userID uuid.UUID) domain.SearchStatus {
|
|
t.Helper()
|
|
row, err := fixture.queries.ReadCandidateSearchStatus(fixture.ctx, uuidParam(userID))
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
status, err := domain.NewSearchStatus(userID)
|
|
if err != nil {
|
|
t.Fatalf("NewSearchStatus() error = %v", err)
|
|
}
|
|
return status
|
|
}
|
|
if err != nil {
|
|
t.Fatalf("ReadCandidateSearchStatus() error = %v", err)
|
|
}
|
|
status, err := domain.RestoreSearchStatus(domain.StoredSearchStatus{
|
|
UserID: userID, Status: row.Status, ConfirmedAt: row.ConfirmedAt.Time, LapsesAt: row.LapsesAt.Time,
|
|
PolicyVersionID: domain.PolicyVersionID(row.PolicyVersionID.Bytes), Version: row.Version,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("RestoreSearchStatus() error = %v", err)
|
|
}
|
|
return status
|
|
}
|
|
|
|
// setSearchStatus applies a status request with the stored policy version and
|
|
// stores the result the way a repository does.
|
|
func (fixture candidatePrivacyFixture) setSearchStatus(t *testing.T, userID uuid.UUID, value domain.SearchStatusValue, expectedVersion int64, at time.Time) domain.SearchStatus {
|
|
t.Helper()
|
|
confirmation, err := domain.NewSearchStatusConfirmation(fixture.policy.ID(), fixture.policy.Policy().SearchStatus)
|
|
if err != nil {
|
|
t.Fatalf("NewSearchStatusConfirmation() error = %v", err)
|
|
}
|
|
change, err := fixture.loadSearchStatus(t, userID).Apply(value, expectedVersion, confirmation, at)
|
|
if err != nil || !change.Changed {
|
|
t.Fatalf("Apply(%s) = %+v, %v, want a change", value, change, err)
|
|
}
|
|
next := change.Status
|
|
confirmed, lapses, policyID := pgtype.Timestamptz{}, pgtype.Timestamptz{}, pgtype.UUID{}
|
|
if next.StoredValue() == domain.SearchStatusLooking {
|
|
confirmed, lapses, policyID = timeParam(next.ConfirmedAt()), timeParam(next.LapsesAt()), uuidParam(next.PolicyVersionID().UUID())
|
|
}
|
|
if expectedVersion == 0 {
|
|
_, err = fixture.queries.InsertCandidateSearchStatus(fixture.ctx, sqlc.InsertCandidateSearchStatusParams{
|
|
UserID: uuidParam(userID), Status: string(next.StoredValue()), ConfirmedAt: confirmed, LapsesAt: lapses, PolicyVersionID: policyID, At: timeParam(at),
|
|
})
|
|
} else {
|
|
_, err = fixture.queries.UpdateCandidateSearchStatus(fixture.ctx, sqlc.UpdateCandidateSearchStatusParams{
|
|
UserID: uuidParam(userID), ExpectedVersion: expectedVersion, Status: string(next.StoredValue()),
|
|
ConfirmedAt: confirmed, LapsesAt: lapses, PolicyVersionID: policyID, At: timeParam(at),
|
|
})
|
|
}
|
|
if err != nil {
|
|
t.Fatalf("store the search status: %v", err)
|
|
}
|
|
return fixture.loadSearchStatus(t, userID)
|
|
}
|
|
|
|
// hide stores a hiding and its history event the way a repository does.
|
|
func (fixture candidatePrivacyFixture) hide(t *testing.T, userID, organizationID uuid.UUID, at time.Time) {
|
|
t.Helper()
|
|
hidden, err := domain.NewHiddenOrganization(userID, organizationID, at)
|
|
if err != nil {
|
|
t.Fatalf("NewHiddenOrganization() error = %v", err)
|
|
}
|
|
if _, err := fixture.queries.InsertCandidateHiddenOrganization(fixture.ctx, sqlc.InsertCandidateHiddenOrganizationParams{
|
|
UserID: uuidParam(hidden.UserID()), OrganizationID: uuidParam(hidden.OrganizationID()), At: timeParam(hidden.HiddenAt()),
|
|
}); err != nil {
|
|
t.Fatalf("InsertCandidateHiddenOrganization() error = %v", err)
|
|
}
|
|
event, err := domain.NewOrganizationEvent(domain.PrivacyEventOrganizationHidden, userID, organizationID, at)
|
|
if err != nil {
|
|
t.Fatalf("NewOrganizationEvent() error = %v", err)
|
|
}
|
|
if err := fixture.queries.InsertCandidatePrivacyEvent(fixture.ctx, sqlc.InsertCandidatePrivacyEventParams{
|
|
ID: uuidParam(event.ID()), UserID: uuidParam(userID), Kind: string(event.Kind()), OccurredAt: timeParam(at),
|
|
OrganizationID: uuidParam(organizationID),
|
|
}); err != nil {
|
|
t.Fatalf("InsertCandidatePrivacyEvent() error = %v", err)
|
|
}
|
|
}
|
|
|
|
// The raw readers return a comparable text of the rows, so a test can prove
|
|
// that an operation left a table exactly as it was.
|
|
func (fixture candidatePrivacyFixture) rawPublication(t *testing.T, userID uuid.UUID) string {
|
|
t.Helper()
|
|
return fixture.rawRows(t, `SELECT coalesce(string_agg(p::text, ';'), '') FROM candidate_publications p WHERE user_id = $1`, userID)
|
|
}
|
|
|
|
func (fixture candidatePrivacyFixture) rawSearchStatus(t *testing.T, userID uuid.UUID) string {
|
|
t.Helper()
|
|
return fixture.rawRows(t, `SELECT coalesce(string_agg(s::text, ';'), '') FROM candidate_search_statuses s WHERE user_id = $1`, userID)
|
|
}
|
|
|
|
func (fixture candidatePrivacyFixture) rawHidden(t *testing.T, userID uuid.UUID) string {
|
|
t.Helper()
|
|
return fixture.rawRows(t, `SELECT coalesce(string_agg(h::text, ';' ORDER BY organization_id), '') FROM candidate_hidden_organizations h WHERE user_id = $1`, userID)
|
|
}
|
|
|
|
func (fixture candidatePrivacyFixture) rawConsentRecords(t *testing.T, userID uuid.UUID) string {
|
|
t.Helper()
|
|
return fixture.rawRows(t, `SELECT coalesce(string_agg(c::text, ';' ORDER BY id), '') FROM consent_records c WHERE subject_id = $1`, userID)
|
|
}
|
|
|
|
func (fixture candidatePrivacyFixture) rawRows(t *testing.T, query string, userID uuid.UUID) string {
|
|
t.Helper()
|
|
var text string
|
|
if err := fixture.pool.QueryRow(fixture.ctx, query, userID).Scan(&text); err != nil {
|
|
t.Fatalf("read raw rows: %v", err)
|
|
}
|
|
return text
|
|
}
|