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

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

No files matched your search

@@ -25,8 +25,8 @@ func TestCandidateCardAccessMigrationDownRetainsHistory(t *testing.T) {
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
rollBackToCandidateCardAccessVersion(ctx, t, migrator)
// The organization is created while the latest schema is in place: its creation
// needs the holdings table, which the rollback below removes.
now := time.Now().UTC().Truncate(time.Microsecond)
identity := identityFixture{
ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now,
@@ -38,6 +38,8 @@ func TestCandidateCardAccessMigrationDownRetainsHistory(t *testing.T) {
}
owner := organizationFixture.employer(t, "owner@example.com")
organization := organizationFixture.create(t, owner, organizationFixture.completeProfile(t, "Example Company"), now)
rollBackToCandidateCardAccessVersion(ctx, t, migrator)
if _, err := pool.Exec(ctx, `INSERT INTO candidate_card_access_events (
id, candidate_id, organization_id, actor_id, kind, field_codes, occurred_at
) VALUES ($1, $2, $3, $4, 'card_viewed', ARRAY['stack']::text[], $5)`,
@@ -416,8 +416,13 @@ func TestCandidatePrivacyStorage(t *testing.T) {
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, `
INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at)
SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1 FROM generate_series(1, $2::int) AS n`, now, limit+1); err != nil {
INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, $2)`, employer.ID, now); err != nil {
t.Fatalf("create holding: %v", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id)
SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1, (SELECT id FROM holdings WHERE founder_account_id = $3)
FROM generate_series(1, $2::int) AS n`, now, limit+1, employer.ID); err != nil {
t.Fatalf("create organizations: %v", err)
}
if _, err := tx.Exec(ctx, `
@@ -696,8 +701,13 @@ func TestCandidatePrivacyStorage(t *testing.T) {
t.Fatalf("begin: %v", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at)
SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1 FROM generate_series(1, $2::int) AS n`, now, limit-1+parallel); err != nil {
INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, $2)`, employer.ID, now); err != nil {
t.Fatalf("create holding: %v", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id)
SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1, (SELECT id FROM holdings WHERE founder_account_id = $3)
FROM generate_series(1, $2::int) AS n`, now, limit-1+parallel, employer.ID); err != nil {
t.Fatalf("create organizations: %v", err)
}
if _, err := tx.Exec(ctx, `
+26 -7
View File
@@ -38,11 +38,10 @@ type companyQuotaFixture struct {
invitationCandidate uuid.UUID
}
func TestCompanyQuota(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
// newCompanyQuotaFixture migrates the isolated database, publishes the demo
// product policy, and returns the fixture the quota tests share.
func newCompanyQuotaFixture(ctx context.Context, t *testing.T, databaseURL string) companyQuotaFixture {
t.Helper()
applyMigrations(ctx, t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
@@ -60,13 +59,20 @@ func TestCompanyQuota(t *testing.T) {
if err != nil {
t.Fatalf("GetEffective(product) error = %v", err)
}
fixture := companyQuotaFixture{
return companyQuotaFixture{
ctx: ctx, pool: pool, clock: clock, transactor: transactor,
service: companyquota.NewService(clock.Now), organizations: organizationFixture,
policies: policyStore.Policies(), version: version,
invitationAuthor: organizationFixture.employer(t, "quota-invitation-author@example.test").ID,
invitationCandidate: identity.createUser(t, "quota-invitation-candidate@example.test", domain.ScenarioCandidate, clock.Now().Add(-time.Hour)).ID,
}
}
func TestCompanyQuota(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout)
defer cancel()
fixture := newCompanyQuotaFixture(ctx, t, env.createIsolatedDatabase(ctx, t))
t.Run("E0 shares limits across requests and concurrent final reservations", func(t *testing.T) {
organization, _ := fixture.newOrganization(t, "e0-boundary", domain.OrganizationVerificationE0)
@@ -381,6 +387,19 @@ func (fixture companyQuotaFixture) newOrganization(
) (domain.Organization, domain.User) {
t.Helper()
owner := fixture.organizations.employer(t, fmt.Sprintf("quota-%s-%s@example.test", name, uuid.NewString()))
return fixture.organizationOf(t, owner, name, level), owner
}
// organizationOf stores an organization of owner at the given verification
// level and returns it as read back from storage. Several organizations of one
// owner belong to one holding.
func (fixture companyQuotaFixture) organizationOf(
t *testing.T,
owner domain.User,
name string,
level domain.OrganizationVerificationLevel,
) domain.Organization {
t.Helper()
organization := fixture.organizations.create(t, owner, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Quota " + name}), fixture.clock.Now().Add(-time.Minute))
if level != domain.OrganizationVerificationE0 {
basis := domain.OrganizationBasisCorporateDomain
@@ -401,7 +420,7 @@ func (fixture companyQuotaFixture) newOrganization(
if err != nil {
t.Fatalf("read %s organization: %v", level, err)
}
return stored, owner
return stored
}
// newInvitationID stores a draft of the organization and returns its
@@ -0,0 +1,193 @@
//go:build integration
package integration_test
import (
"context"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
)
// holdingsMigrationVersion creates the holdings table and organizations.holding_id.
const holdingsMigrationVersion = 41
// legacyMembership is a membership row written without the application.
type legacyMembership struct {
userID uuid.UUID
role string
createdAt time.Time
}
// TestHoldingsMigrationBackfillsFoundersAndGuardsRollback runs the migration on
// organizations that were created before holdings existed. The backfill must
// give one holding per founder, and the rollback must refuse while a holding
// groups several organizations.
func TestHoldingsMigrationBackfillsFoundersAndGuardsRollback(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
// The schema before holdings: the organizations are written without them.
rollBackAboveMigration(ctx, t, migrator, holdingsMigrationVersion-1)
now := time.Now().UTC().Truncate(time.Microsecond).Add(-24 * time.Hour)
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
founderA := identity.createUser(t, "holding-backfill-first@example.test", domain.ScenarioEmployer, now.Add(-time.Hour))
founderB := identity.createUser(t, "holding-backfill-other@example.test", domain.ScenarioEmployer, now.Add(-time.Hour))
cofounder := identity.createUser(t, "holding-backfill-cofounder@example.test", domain.ScenarioEmployer, now.Add(-time.Hour))
first := insertLegacyOrganization(ctx, t, pool, "Legacy first", now,
legacyMembership{userID: founderA.ID, role: "owner", createdAt: now})
second := insertLegacyOrganization(ctx, t, pool, "Legacy second", now.Add(time.Hour),
legacyMembership{userID: founderA.ID, role: "owner", createdAt: now.Add(time.Hour)},
// A later owner does not change the founder: the earliest membership does.
legacyMembership{userID: cofounder.ID, role: "owner", createdAt: now.Add(2 * time.Hour)})
other := insertLegacyOrganization(ctx, t, pool, "Legacy other", now.Add(30*time.Minute),
legacyMembership{userID: founderB.ID, role: "owner", createdAt: now.Add(30 * time.Minute)})
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() with the holdings migration error = %v", err)
}
t.Run("backfill gives each founder one holding dated by its first organization", func(t *testing.T) {
firstHolding := legacyHolding(ctx, t, pool, first)
if got := legacyHolding(ctx, t, pool, second); got != firstHolding {
t.Fatalf("holding of the second organization = %s, want the founder's holding %s", got, firstHolding)
}
if got := legacyHolding(ctx, t, pool, other); got == firstHolding {
t.Fatal("two founders share one holding")
}
assertLegacyHoldingFounder(ctx, t, pool, firstHolding, founderA.ID, now)
assertLegacyHoldingFounder(ctx, t, pool, legacyHolding(ctx, t, pool, other), founderB.ID, now.Add(30*time.Minute))
var count int64
if err := pool.QueryRow(ctx, `SELECT count(*) FROM holdings`).Scan(&count); err != nil {
t.Fatalf("count holdings: %v", err)
}
if count != 2 {
t.Fatalf("holdings = %d, want one per founder (2)", count)
}
})
t.Run("rollback refuses while a holding groups several organizations", func(t *testing.T) {
_, err := migrator.DownOne(ctx)
assertPgError(t, "DownOne() with a grouped holding", err, privacyIntegrityViolation, "organizations_holding_grouped")
if got := legacyHolding(ctx, t, pool, first); got != legacyHolding(ctx, t, pool, second) {
t.Fatal("refused rollback changed the grouping")
}
})
t.Run("rollback succeeds once every holding has one organization", func(t *testing.T) {
split := uuid.Must(uuid.NewV7())
if _, err := pool.Exec(ctx, `
INSERT INTO holdings (id, founder_account_id, created_at) VALUES ($1, $2, $3)`,
split, cofounder.ID, now); err != nil {
t.Fatalf("insert the holding of the split organization: %v", err)
}
if _, err := pool.Exec(ctx, `UPDATE organizations SET holding_id = $2 WHERE id = $1`, second, split); err != nil {
t.Fatalf("move the second organization to its own holding: %v", err)
}
if _, err := migrator.DownOne(ctx); err != nil {
t.Fatalf("DownOne() with single-organization holdings error = %v", err)
}
var holdingsGone, columnGone bool
var organizations int64
if err := pool.QueryRow(ctx, `
SELECT
to_regclass('public.holdings') IS NULL,
NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'organizations' AND column_name = 'holding_id'),
(SELECT count(*) FROM organizations)`).Scan(&holdingsGone, &columnGone, &organizations); err != nil {
t.Fatalf("read the rolled-back schema: %v", err)
}
if !holdingsGone || !columnGone {
t.Fatalf("rollback left holdings table gone = %t, holding_id column gone = %t", holdingsGone, columnGone)
}
if organizations != 3 {
t.Fatalf("organizations after rollback = %d, want the 3 that were created", organizations)
}
// Applying the migration again backfills the same grouping from the
// memberships, so the founders get one holding each.
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() after the rollback error = %v", err)
}
if got := legacyHolding(ctx, t, pool, second); got != legacyHolding(ctx, t, pool, first) {
t.Fatal("reapplied backfill does not group the founder's organizations")
}
})
}
// insertLegacyOrganization stores an organization and its memberships in one
// transaction, as creation did before holdings. The owner membership keeps the
// deferred constraint satisfied at commit.
func insertLegacyOrganization(
ctx context.Context,
t *testing.T,
pool *pgxpool.Pool,
name string,
createdAt time.Time,
memberships ...legacyMembership,
) uuid.UUID {
t.Helper()
organizationID := uuid.Must(uuid.NewV7())
tx, err := pool.Begin(ctx)
if err != nil {
t.Fatalf("begin legacy organization transaction: %v", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, `
INSERT INTO organizations (
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at
) VALUES ($1, $2, 'e0', 'confirmed_email', $3, 1, $3, $3)`, organizationID, name, createdAt); err != nil {
t.Fatalf("insert legacy organization: %v", err)
}
for _, membership := range memberships {
if _, err := tx.Exec(ctx, `
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
VALUES ($1, $2, $3, $4, 'active', $5, $5)`,
uuid.Must(uuid.NewV7()), organizationID, membership.userID, membership.role, membership.createdAt); err != nil {
t.Fatalf("insert legacy membership: %v", err)
}
}
if err := tx.Commit(ctx); err != nil {
t.Fatalf("commit legacy organization: %v", err)
}
return organizationID
}
func legacyHolding(ctx context.Context, t *testing.T, pool *pgxpool.Pool, organizationID uuid.UUID) uuid.UUID {
t.Helper()
var holdingID uuid.UUID
if err := pool.QueryRow(ctx, `SELECT holding_id FROM organizations WHERE id = $1`, organizationID).Scan(&holdingID); err != nil {
t.Fatalf("read holding of organization: %v", err)
}
return holdingID
}
func assertLegacyHoldingFounder(ctx context.Context, t *testing.T, pool *pgxpool.Pool, holdingID, founderID uuid.UUID, createdAt time.Time) {
t.Helper()
var gotFounder uuid.UUID
var gotCreatedAt time.Time
if err := pool.QueryRow(ctx, `
SELECT founder_account_id, created_at FROM holdings WHERE id = $1`, holdingID).Scan(&gotFounder, &gotCreatedAt); err != nil {
t.Fatalf("read holding: %v", err)
}
if gotFounder != founderID {
t.Fatalf("holding founder = %s, want %s", gotFounder, founderID)
}
if !gotCreatedAt.Equal(createdAt) {
t.Fatalf("holding created_at = %s, want %s", gotCreatedAt, createdAt)
}
}
+418
View File
@@ -0,0 +1,418 @@
//go:build integration
package integration_test
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// holdingConcurrentConns sizes the pool of the concurrency subtests, so that
// every goroutine of one subtest holds a connection at the same time.
const holdingConcurrentConns = 8
// TestHoldings covers the E0 quota pools that the organizations of one holding
// share, the isolation of accounts, and the creation of holdings.
func TestHoldings(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
fixture := newCompanyQuotaFixture(ctx, t, databaseURL)
t.Run("organizations of one account share the E0 pools and keep the E1 pools apart", func(t *testing.T) {
owner := fixture.organizations.employer(t, uniqueHoldingEmail("shared-owner"))
first := fixture.organizationOf(t, owner, "shared-first", domain.OrganizationVerificationE0)
second := fixture.organizationOf(t, owner, "shared-second", domain.OrganizationVerificationE0)
verified := fixture.organizationOf(t, owner, "shared-verified", domain.OrganizationVerificationE1)
fixture.assertSameHolding(t, owner.ID, first.ID(), second.ID(), verified.ID())
// The verified organization draws on its own pool, and its usage does
// not count toward the E0 pool that follows.
for range 3 {
fixture.reserveInvitationAllowed(t, verified, fixture.newInvitationID(t, verified))
fixture.reserveCardViewAllowed(t, verified, fixture.newCandidateID(t))
}
for range 6 {
fixture.reserveInvitationAllowed(t, first, fixture.newInvitationID(t, first))
}
for range 4 {
fixture.reserveInvitationAllowed(t, second, fixture.newInvitationID(t, second))
}
fixture.assertInvitationDenied(t, first, fixture.clock.Now().Add(7*24*time.Hour))
fixture.assertInvitationDenied(t, second, fixture.clock.Now().Add(7*24*time.Hour))
fixture.assertQuotaRowCounts(t, first.ID(), 6, 0)
fixture.assertQuotaRowCounts(t, second.ID(), 4, 0)
fixture.assertQuotaRowCounts(t, verified.ID(), 3, 3)
for range 30 {
fixture.reserveCardViewAllowed(t, first, fixture.newCandidateID(t))
}
for range 20 {
fixture.reserveCardViewAllowed(t, second, fixture.newCandidateID(t))
}
fixture.assertCardViewDenied(t, first, fixture.clock.Now().Add(24*time.Hour))
fixture.assertCardViewDenied(t, second, fixture.clock.Now().Add(24*time.Hour))
fixture.assertQuotaRowCounts(t, first.ID(), 6, 30)
fixture.assertQuotaRowCounts(t, second.ID(), 4, 20)
// The verified organization keeps its own pool: it still has room.
fixture.reserveInvitationAllowed(t, verified, fixture.newInvitationID(t, verified))
fixture.reserveCardViewAllowed(t, verified, fixture.newCandidateID(t))
})
t.Run("a second account forms its own holding and pool", func(t *testing.T) {
owner := fixture.organizations.employer(t, uniqueHoldingEmail("other-owner"))
other := fixture.organizationOf(t, owner, "other-first", domain.OrganizationVerificationE0)
for range 10 {
fixture.reserveInvitationAllowed(t, other, fixture.newInvitationID(t, other))
}
fixture.assertInvitationDenied(t, other, fixture.clock.Now().Add(7*24*time.Hour))
neighbour := fixture.organizations.employer(t, uniqueHoldingEmail("neighbour-owner"))
separate := fixture.organizationOf(t, neighbour, "neighbour-first", domain.OrganizationVerificationE0)
if fixture.holdingOf(t, separate.ID()) == fixture.holdingOf(t, other.ID()) {
t.Fatal("organizations of two accounts share one holding")
}
fixture.reserveInvitationAllowed(t, separate, fixture.newInvitationID(t, separate))
fixture.reserveCardViewAllowed(t, separate, fixture.newCandidateID(t))
})
t.Run("usage leaves the E0 pool with its organization", func(t *testing.T) {
owner := fixture.organizations.employer(t, uniqueHoldingEmail("leave-owner"))
raised := fixture.organizationOf(t, owner, "leave-raised", domain.OrganizationVerificationE0)
sibling := fixture.organizationOf(t, owner, "leave-sibling", domain.OrganizationVerificationE0)
for range 6 {
fixture.reserveInvitationAllowed(t, raised, fixture.newInvitationID(t, raised))
}
if _, err := fixture.pool.Exec(fixture.ctx, `
UPDATE organizations
SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2
WHERE id = $1`, raised.ID(), fixture.clock.Now().Add(-30*time.Second)); err != nil {
t.Fatalf("raise organization to E1: %v", err)
}
raisedNow, _, err := fixture.organizations.read(owner.ID, raised.ID())
if err != nil {
t.Fatalf("read raised organization: %v", err)
}
// The six invitations stay stored, but they no longer count toward the
// E0 pool, which the sibling can use in full.
for range 10 {
fixture.reserveInvitationAllowed(t, sibling, fixture.newInvitationID(t, sibling))
}
fixture.assertInvitationDenied(t, sibling, fixture.clock.Now().Add(7*24*time.Hour))
fixture.assertQuotaRowCounts(t, raised.ID(), 6, 0)
fixture.reserveInvitationAllowed(t, raisedNow, fixture.newInvitationID(t, raisedNow))
})
t.Run("concurrent reservations of one E0 pool never exceed its limits", func(t *testing.T) {
owner := fixture.organizations.employer(t, uniqueHoldingEmail("race-owner"))
first := fixture.organizationOf(t, owner, "race-first", domain.OrganizationVerificationE0)
second := fixture.organizationOf(t, owner, "race-second", domain.OrganizationVerificationE0)
concurrent := newConcurrentTransactor(ctx, t, databaseURL)
for range 5 {
fixture.reserveInvitationAllowed(t, first, fixture.newInvitationID(t, first))
}
for range 4 {
fixture.reserveInvitationAllowed(t, second, fixture.newInvitationID(t, second))
}
// Nine of the ten invitations are used. Four reservations race for the
// last place, two from each organization.
racers := []domain.Organization{first, second, first, second}
invitationIDs := make([]uuid.UUID, len(racers))
for index, organization := range racers {
invitationIDs[index] = fixture.newInvitationID(t, organization)
}
decisions := make([]outbound.CompanyQuotaDecision, len(racers))
runConcurrently(t, len(racers), func(index int) error {
decision, err := fixture.reserveInvitationLocked(concurrent, racers[index], invitationIDs[index])
decisions[index] = decision
return err
})
fixture.assertOneAllowed(t, decisions, fixture.clock.Now().Add(7*24*time.Hour))
fixture.assertInvitationRowsOf(t, 10, first.ID(), second.ID())
viewCandidates := make([]uuid.UUID, 0, 49)
for range 49 {
viewCandidates = append(viewCandidates, fixture.newCandidateID(t))
}
for index, candidateID := range viewCandidates {
organization := first
if index%2 == 1 {
organization = second
}
fixture.reserveCardViewAllowed(t, organization, candidateID)
}
viewRacers := make([]uuid.UUID, len(racers))
for index := range racers {
viewRacers[index] = fixture.newCandidateID(t)
}
viewDecisions := make([]outbound.CompanyQuotaDecision, len(racers))
runConcurrently(t, len(racers), func(index int) error {
decision, err := fixture.reserveCardViewLocked(concurrent, racers[index], viewRacers[index])
viewDecisions[index] = decision
return err
})
fixture.assertOneAllowed(t, viewDecisions, fixture.clock.Now().Add(24*time.Hour))
fixture.assertCardViewRowsOf(t, 50, first.ID(), second.ID())
})
t.Run("concurrent creations by one account end in one holding", func(t *testing.T) {
owner := fixture.organizations.employer(t, uniqueHoldingEmail("create-owner"))
concurrent := newConcurrentTransactor(ctx, t, databaseURL)
const creations = holdingConcurrentConns
at := fixture.clock.Now().Add(-time.Minute)
organizationIDs := make([]uuid.UUID, creations)
runConcurrently(t, creations, func(index int) error {
profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{Name: fmt.Sprintf("Concurrent company %d", index)})
if err != nil {
return fmt.Errorf("profile: %w", err)
}
company, err := domain.NewOrganization(profile, at)
if err != nil {
return fmt.Errorf("organization: %w", err)
}
membership, err := domain.NewOwnerMembership(company.ID(), owner.ID, at)
if err != nil {
return fmt.Errorf("owner membership: %w", err)
}
organizationIDs[index] = company.ID()
return concurrent.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Organizations().CreateWithOwner(ctx, company, membership)
})
})
fixture.assertSameHolding(t, owner.ID, organizationIDs...)
if got := fixture.holdingCount(t, owner.ID); got != 1 {
t.Fatalf("holdings of the founder = %d, want 1", got)
}
})
t.Run("an unknown founder stores no holding", func(t *testing.T) {
before := fixture.totalHoldings(t)
unknown := uuid.New()
profile := mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Orphan company"})
company, err := domain.NewOrganization(profile, fixture.clock.Now().Add(-time.Minute))
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
membership, err := domain.NewOwnerMembership(company.ID(), unknown, company.CreatedAt())
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Organizations().CreateWithOwner(ctx, company, membership)
})
if !errors.Is(err, outbound.ErrUserNotFound) {
t.Fatalf("CreateWithOwner(unknown founder) error = %v, want ErrUserNotFound", err)
}
if after := fixture.totalHoldings(t); after != before {
t.Fatalf("holdings = %d after the refused creation, want %d", after, before)
}
})
}
// uniqueHoldingEmail returns a fresh address so that every subtest creates its
// own account and therefore its own holding.
func uniqueHoldingEmail(prefix string) string {
return fmt.Sprintf("holding-%s-%s@example.test", prefix, uuid.NewString())
}
// newConcurrentTransactor opens a pool of the isolated database that lets every
// goroutine of a subtest run its transaction at the same time.
func newConcurrentTransactor(ctx context.Context, t *testing.T, databaseURL string) *postgresadapter.Transactor {
t.Helper()
poolConfig, err := pgxpool.ParseConfig(databaseURL)
if err != nil {
t.Fatalf("parse isolated database URL: %v", err)
}
poolConfig.MaxConns = holdingConcurrentConns
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
t.Fatalf("create concurrent PostgreSQL pool: %v", err)
}
t.Cleanup(pool.Close)
return postgresadapter.NewTransactor(pool)
}
// runConcurrently calls work for every index at once, after all goroutines
// have started, and fails the test on the first error. work must not call
// testing methods that stop the test goroutine.
func runConcurrently(t *testing.T, count int, work func(index int) error) {
t.Helper()
errs := make([]error, count)
start := make(chan struct{})
done := make(chan struct{}, count)
for index := range count {
go func() {
defer func() { done <- struct{}{} }()
<-start
errs[index] = work(index)
}()
}
close(start)
for range count {
<-done
}
for index, err := range errs {
if err != nil {
t.Fatalf("concurrent call %d error = %v", index, err)
}
}
}
// reserveInvitationLocked reserves one invitation the way the production
// callers do: the organization lock first, then the reservation, in one
// transaction.
func (fixture companyQuotaFixture) reserveInvitationLocked(
transactor *postgresadapter.Transactor,
organization domain.Organization,
invitationID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
var decision outbound.CompanyQuotaDecision
err := transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.CompanyQuotas().LockOrganization(ctx, organization.ID()); err != nil {
return err
}
var err error
decision, err = fixture.service.ReserveInvitation(ctx, unit, organization, invitationID)
return err
})
return decision, err
}
// reserveCardViewLocked is reserveInvitationLocked for a distinct card view.
func (fixture companyQuotaFixture) reserveCardViewLocked(
transactor *postgresadapter.Transactor,
organization domain.Organization,
candidateID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
var decision outbound.CompanyQuotaDecision
err := transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.CompanyQuotas().LockOrganization(ctx, organization.ID()); err != nil {
return err
}
var err error
decision, err = fixture.service.ReserveCardView(ctx, unit, organization, candidateID)
return err
})
return decision, err
}
// assertSameHolding checks that every organization is in the holding of the
// owner and that the owner has exactly one holding.
func (fixture companyQuotaFixture) assertSameHolding(t *testing.T, founderID uuid.UUID, organizationIDs ...uuid.UUID) {
t.Helper()
if got := fixture.holdingCount(t, founderID); got != 1 {
t.Fatalf("holdings of the founder = %d, want 1", got)
}
want := fixture.holdingOf(t, organizationIDs[0])
for _, organizationID := range organizationIDs {
if got := fixture.holdingOf(t, organizationID); got != want {
t.Fatalf("organization %s is in holding %s, want %s", organizationID, got, want)
}
}
}
func (fixture companyQuotaFixture) holdingOf(t *testing.T, organizationID uuid.UUID) uuid.UUID {
t.Helper()
var holdingID uuid.UUID
if err := fixture.pool.QueryRow(fixture.ctx, `SELECT holding_id FROM organizations WHERE id = $1`, organizationID).Scan(&holdingID); err != nil {
t.Fatalf("read holding of organization: %v", err)
}
return holdingID
}
func (fixture companyQuotaFixture) holdingCount(t *testing.T, founderID uuid.UUID) int64 {
t.Helper()
var count int64
if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM holdings WHERE founder_account_id = $1`, founderID).Scan(&count); err != nil {
t.Fatalf("count holdings of founder: %v", err)
}
return count
}
func (fixture companyQuotaFixture) totalHoldings(t *testing.T) int64 {
t.Helper()
var count int64
if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM holdings`).Scan(&count); err != nil {
t.Fatalf("count holdings: %v", err)
}
return count
}
// assertInvitationDenied checks that the organization cannot reserve a new
// invitation and that the denial retries at retryAt.
func (fixture companyQuotaFixture) assertInvitationDenied(t *testing.T, organization domain.Organization, retryAt time.Time) {
t.Helper()
decision, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization))
if err != nil || decision.Allowed || !decision.RetryAt.Equal(retryAt) {
t.Fatalf("ReserveInvitation() = %+v, %v; want a denial that retries at %s", decision, err, retryAt)
}
}
// assertCardViewDenied is assertInvitationDenied for a distinct card view.
func (fixture companyQuotaFixture) assertCardViewDenied(t *testing.T, organization domain.Organization, retryAt time.Time) {
t.Helper()
decision, err := fixture.reserveCardView(organization, fixture.newCandidateID(t))
if err != nil || decision.Allowed || !decision.RetryAt.Equal(retryAt) {
t.Fatalf("ReserveCardView() = %+v, %v; want a denial that retries at %s", decision, err, retryAt)
}
}
// assertOneAllowed checks that exactly one of the decisions was allowed and
// that the others were denied with the given retry time.
func (fixture companyQuotaFixture) assertOneAllowed(t *testing.T, decisions []outbound.CompanyQuotaDecision, retryAt time.Time) {
t.Helper()
allowed := 0
for _, decision := range decisions {
switch {
case decision.Allowed && decision.RetryAt.IsZero() && !decision.Reused:
allowed++
case !decision.Allowed && decision.RetryAt.Equal(retryAt):
default:
t.Fatalf("unexpected concurrent decision %+v, want retry at %s", decision, retryAt)
}
}
if allowed != 1 {
t.Fatalf("allowed concurrent reservations = %d, want exactly 1 of %d", allowed, len(decisions))
}
}
// assertInvitationRowsOf checks the invitation usage stored for the given
// organizations together, which is the count of the shared pool.
func (fixture companyQuotaFixture) assertInvitationRowsOf(t *testing.T, want int64, organizationIDs ...uuid.UUID) {
t.Helper()
var got int64
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = ANY($1)`, organizationIDs).Scan(&got); err != nil {
t.Fatalf("count invitation usage rows: %v", err)
}
if got != want {
t.Fatalf("invitation usage rows of the pool = %d, want %d", got, want)
}
}
// assertCardViewRowsOf is assertInvitationRowsOf for distinct card views.
func (fixture companyQuotaFixture) assertCardViewRowsOf(t *testing.T, want int64, organizationIDs ...uuid.UUID) {
t.Helper()
var got int64
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = ANY($1)`, organizationIDs).Scan(&got); err != nil {
t.Fatalf("count card-view usage rows: %v", err)
}
if got != want {
t.Fatalf("card-view usage rows of the pool = %d, want %d", got, want)
}
}
@@ -0,0 +1,579 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/policy"
)
const (
// invitationAcceptMigrationVersion adds the acceptance: its audit event, the
// contact grant, and the outcomes kept under the keys.
invitationAcceptMigrationVersion = 40
invitationAcceptancesRetained = "invitation_acceptances_retained"
acceptTextVersion = "c4-2026-10-01"
)
// candidateContactGrantHTTP is the contact grant as the candidate reads it.
type candidateContactGrantHTTP struct {
ID uuid.UUID `json:"id"`
Fields []string `json:"fields"`
Status string `json:"status"`
Readable bool `json:"readable"`
BlockedBy *string `json:"blocked_by"`
TermsVersion int64 `json:"terms_version"`
ConsentTextVersion string `json:"consent_text_version"`
GrantedAt string `json:"granted_at"`
RevokedAt *string `json:"revoked_at"`
RevocationReason *string `json:"revocation_reason"`
}
func decodeContactGrantHTTP(t *testing.T, body candidateInvitationHTTPBody) candidateContactGrantHTTP {
t.Helper()
var grant candidateContactGrantHTTP
if err := json.Unmarshal(body.ContactGrant, &grant); err != nil {
t.Fatalf("decode contact grant %s: %v", body.ContactGrant, err)
}
return grant
}
// invitationAcceptCounts are the rows that acceptances write for one
// invitation, the C4 consents of its candidate, and the outcomes kept under
// the keys.
type invitationAcceptCounts struct {
acceptedEvents, grants, c4Consents, outcomes int
}
func readInvitationAcceptCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationAcceptCounts {
t.Helper()
var counts invitationAcceptCounts
if err := harness.pool.QueryRow(ctx, `
SELECT
(SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'accepted'),
(SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1),
(SELECT count(*) FROM consent_records WHERE subject_id = $2 AND purpose = 'c4'),
(SELECT count(*) FROM invitation_accept_results WHERE invitation_id = $1)`,
invitationID, candidateID).Scan(&counts.acceptedEvents, &counts.grants, &counts.c4Consents, &counts.outcomes); err != nil {
t.Fatalf("count the rows of an acceptance: %v", err)
}
return counts
}
// parallelAcceptRequests sends every acceptance at once, each under its own
// key, and returns the responses in the order of the bodies.
func parallelAcceptRequests(
t *testing.T,
harness *invitationHTTPHarness,
path, origin string,
session organizationHTTPSession,
bodies, keys []string,
) []*httptest.ResponseRecorder {
t.Helper()
responses := make([]*httptest.ResponseRecorder, len(bodies))
var group sync.WaitGroup
start := make(chan struct{})
for index := range bodies {
group.Go(func() {
<-start
responses[index] = organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, path, bodies[index], origin, session, keys[index])
})
}
close(start)
group.Wait()
return responses
}
// firstAcceptance is the acceptance that later cases of the test repeat.
type firstAcceptance struct {
candidate domain.User
invitation invitationHTTPBody
key string
body string
}
func TestCandidateInvitationAcceptOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolated := *env
isolated.Config.DatabaseURL = databaseURL
setupPool := newPoolFor(ctx, t, databaseURL)
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
}
harness := newInvitationHTTPHarness(ctx, t, &isolated)
harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second))
origin := env.Config.AppPublicURL
now := harness.clock.Now()
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
account := func(email string, scenario domain.Scenario) domain.User {
return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now)
}
owner := account("accept-owner@example.test", domain.ScenarioEmployer)
sessionOwner := loginOrganizationHTTP(t, harness.sessionHTTPHarness, owner.Email.Address())
orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwner, "accept-company")
var nameA string
if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, orgA).Scan(&nameA); err != nil {
t.Fatalf("read organization name: %v", err)
}
identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now}
privacy := candidatePrivacyFixture{
ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture,
organizations: organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture, transactor: postgresadapter.NewTransactor(harness.pool), now: now},
ledger: postgresadapter.NewConsentStore(harness.pool), now: now,
}
profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: privacy.queries, identity: identityFixture, now: now}
// Every candidate publishes the card and holds a name, an email, and a phone
// number. Telegram is held by none of them.
publishCandidate := func(candidate domain.User) {
consent := privacy.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now)
privacy.publish(t, candidate.ID, consent.ID(), 0,
domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience,
domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility)
profiles.save(t, candidate.ID, domain.CandidateProfileInput{
FullName: confirmedDecision(invitationCandidateName), Email: confirmedDecision(invitationCandidateContact),
Phone: confirmedDecision("+70000000000"),
Stack: privacyCohortConfirmedItems("go"),
Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}),
Experience: privacyCohortConfirmedItems(domain.ProfileExperience{
EmployerName: invitationCandidateMarker, Specialization: domain.SpecializationBackend,
StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private summary",
}),
SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 777_000, TaxBasis: domain.ProfileTaxNet}),
}, 0)
if _, err := privacy.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{
UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now),
}); err != nil {
t.Fatalf("InsertCandidateQuestionnaire() error = %v", err)
}
}
// Seven published candidates form the visible cohort. Each case uses its own
// candidate, so the cases do not share the state of an invitation.
var candidates []domain.User
for index := range 7 {
candidate := account(fmt.Sprintf("accept-candidate-%d@example.test", index), domain.ScenarioCandidate)
candidates = append(candidates, candidate)
publishCandidate(candidate)
}
login := func(candidate domain.User) organizationHTTPSession {
return loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address())
}
request := func(method, path, body string, session organizationHTTPSession, key string) *httptest.ResponseRecorder {
t.Helper()
return organizationHTTPRequest(t, harness.sessionHTTPHarness, method, path, body, origin, session, key)
}
var keySequence int
nextKey := func() string {
keySequence++
return fmt.Sprintf("invitation-accept-key-%d", keySequence)
}
deliver := func(candidate domain.User) invitationHTTPBody {
t.Helper()
handle, err := harness.key.ForOrganization(orgA, candidate.ID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
draft := decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", orgA),
invitationCreateJSON(t, handle, nil), sessionOwner, nextKey()), http.StatusCreated)
return decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/send", orgA, draft.ID),
fmt.Sprintf(`{"expected_version":%d}`, draft.Version), sessionOwner, nextKey()), http.StatusOK)
}
myPath := func(invitationID uuid.UUID) string { return "/api/v1/me/invitations/" + invitationID.String() }
acceptBody := func(version, terms int64, text string, fields ...string) string {
encoded, err := json.Marshal(map[string]any{
"expected_version": version, "terms_version": terms,
"consent_c4": map[string]any{"text_version": text, "accepted": true, "fields": fields},
})
if err != nil {
t.Fatalf("marshal acceptance: %v", err)
}
return string(encoded)
}
accept := func(candidate domain.User, invitationID uuid.UUID, body, key string) *httptest.ResponseRecorder {
t.Helper()
return request(http.MethodPost, myPath(invitationID)+"/accept", body, login(candidate), key)
}
// raiseTerms stores the next terms version the way a later raise does, with
// a higher salary, and advances the invitation version by one.
raiseTerms := func(invitationID uuid.UUID) int64 {
t.Helper()
if _, err := harness.pool.Exec(ctx, `
INSERT INTO invitation_terms_versions (invitation_id, organization_id, version, terms, salary_from, salary_to,
salary_currency, salary_period, salary_tax_basis, created_at)
SELECT invitation_id, organization_id, 2,
jsonb_set(jsonb_set(terms, '{salary,salary_from}', '120000'::jsonb), '{salary,salary_to}', '160000'::jsonb),
120000, 160000, salary_currency, salary_period, salary_tax_basis, $2
FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, invitationID, harness.clock.Now()); err != nil {
t.Fatalf("store the raised terms: %v", err)
}
var version int64
if err := harness.pool.QueryRow(ctx, `
UPDATE invitations SET terms_version = 2, version = version + 1, updated_at = $2
WHERE id = $1 RETURNING version`, invitationID, harness.clock.Now()).Scan(&version); err != nil {
t.Fatalf("raise the invitation: %v", err)
}
return version
}
candidateMarkers := []string{invitationCandidateName, invitationCandidateContact, invitationCandidateMarker}
for _, candidate := range candidates {
candidateMarkers = append(candidateMarkers, candidate.ID.String(), candidate.Email.Address())
}
requireNoCandidateData := func(label, text string) {
t.Helper()
for _, marker := range candidateMarkers {
if strings.Contains(text, marker) {
t.Errorf("%s contains the private marker %q: %s", label, marker, text)
}
}
for _, field := range []string{"candidate_id", "candidate_handle", "salary_fit", "salary_minimum", "full_name", "telegram", "email", "phone"} {
if strings.Contains(text, `"`+field+`":`) {
t.Errorf("%s contains the key %q: %s", label, field, text)
}
}
}
var first firstAcceptance
t.Run("an email-only acceptance stores one grant of that field and one consent", func(t *testing.T) {
candidate := candidates[0]
sent := deliver(candidate)
key := nextKey()
body := acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email")
response := accept(candidate, sent.ID, body, key)
accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK)
requireNoCandidateData("accept response", response.Body.String())
grant := decodeContactGrantHTTP(t, accepted)
if accepted.State != "accepted" || accepted.Version != sent.Version+1 || accepted.TermsVersion != sent.TermsVersion ||
accepted.RespondedAt == nil || accepted.Decline != nil || string(accepted.ContactConsent) != "null" ||
accepted.ResponseDeadlineAt != *sent.ResponseDeadlineAt || accepted.Organization.Name != nameA {
t.Fatalf("accepted = %+v, want the accepted invitation with its deadline and no offer", accepted)
}
if !slices.Equal(grant.Fields, []string{"email"}) || grant.Status != "active" || grant.ConsentTextVersion != acceptTextVersion ||
grant.TermsVersion != sent.TermsVersion || grant.RevokedAt != nil || grant.RevocationReason != nil {
t.Fatalf("grant = %+v, want the email only, active, under the current text", grant)
}
// The published profile is not hidden, so the grant is readable now.
if !grant.Readable || grant.BlockedBy != nil {
t.Fatalf("grant = %+v, want readable while the organization may read the profile", grant)
}
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 1}) {
t.Fatalf("acceptance stored %+v, want one event, one grant, one C4 consent, and one outcome", counts)
}
// The grant names the one selected kind, although the profile holds the
// phone number too, and the consent names the same kind.
var fields, consentFields []string
if err := harness.pool.QueryRow(ctx, `
SELECT grant_row.fields, record.field_set
FROM contact_grants AS grant_row
JOIN consent_records AS record ON record.id = grant_row.consent_record_id
WHERE grant_row.source_invitation_id = $1`, sent.ID).Scan(&fields, &consentFields); err != nil {
t.Fatalf("read the grant and its consent: %v", err)
}
if !slices.Equal(fields, []string{"email"}) || !slices.Equal(consentFields, []string{"email"}) {
t.Fatalf("stored grant fields = %v and consent fields = %v, want the email only", fields, consentFields)
}
reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK)
if decodeContactGrantHTTP(t, reread).ID != grant.ID || reread.Version != accepted.Version {
t.Fatalf("reread = %+v, want the same grant and version", reread)
}
first = firstAcceptance{candidate: candidate, invitation: sent, key: key, body: body}
})
t.Run("repeats replay the answer and a different choice is a state conflict", func(t *testing.T) {
if first.invitation.ID == uuid.Nil {
t.Fatal("the first acceptance did not run")
}
original := accept(first.candidate, first.invitation.ID, first.body, first.key)
if original.Code != http.StatusOK {
t.Fatalf("replay = %d %s, want the original 200", original.Code, original.Body.String())
}
// The same request under a new key, with the older expected version,
// answers the accepted invitation without a second grant or event.
again := accept(first.candidate, first.invitation.ID, first.body, nextKey())
if again.Code != http.StatusOK || again.Body.String() != original.Body.String() {
t.Fatalf("repeat = %d %s, want the same answer %s", again.Code, again.Body.String(), original.Body.String())
}
// Another field set is a different acceptance that the grant refuses.
requireSessionProblem(t, accept(first.candidate, first.invitation.ID,
acceptBody(first.invitation.Version, first.invitation.TermsVersion, acceptTextVersion, "email", "phone"), nextKey()),
http.StatusConflict, "state_conflict")
// A reused key with another body is refused and stores nothing.
requireSessionProblem(t, accept(first.candidate, first.invitation.ID,
acceptBody(first.invitation.Version, first.invitation.TermsVersion, acceptTextVersion, "phone"), first.key),
http.StatusUnprocessableEntity, "idempotency_key_reused")
// Three outcomes: the first acceptance, the repeat, and the refused field set.
if counts := readInvitationAcceptCounts(ctx, t, harness, first.invitation.ID, first.candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 3}) {
t.Fatalf("repeats stored %+v, want the first acceptance, its repeat, and the refusal", counts)
}
})
t.Run("a stale terms version is refused and nothing is stored, and the raised terms are accepted", func(t *testing.T) {
candidate := candidates[1]
sent := deliver(candidate)
raisedVersion := raiseTerms(sent.ID)
// The candidate read the terms of version 1: 412, nothing stored.
requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(raisedVersion, sent.TermsVersion, acceptTextVersion, "email"), nextKey()),
http.StatusPreconditionFailed, "version_conflict")
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{}) {
t.Fatalf("a stale terms version stored %+v", counts)
}
read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK)
if read.TermsVersion != 2 || read.Version != raisedVersion || read.State != "delivered" {
t.Fatalf("read after the raise = %+v, want the new terms and the delivered state", read)
}
accepted := decodeCandidateInvitationHTTP(t, accept(candidate, sent.ID, acceptBody(raisedVersion, 2, acceptTextVersion, "email"), nextKey()), http.StatusOK)
if accepted.State != "accepted" || accepted.TermsVersion != 2 || decodeContactGrantHTTP(t, accepted).TermsVersion != 2 {
t.Fatalf("accepted = %+v, want the raised terms version accepted", accepted)
}
// The old terms version is a different acceptance once the grant exists.
requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(raisedVersion, sent.TermsVersion, acceptTextVersion, "email"), nextKey()),
http.StatusConflict, "state_conflict")
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 2}) {
t.Fatalf("raised acceptance stored %+v, want one acceptance, one grant, one consent, and the refusal", counts)
}
})
t.Run("concurrent acceptances make one transition and one grant", func(t *testing.T) {
candidate := candidates[2]
sent := deliver(candidate)
session := login(candidate)
path := myPath(sent.ID) + "/accept"
body := acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email")
responses := parallelAcceptRequests(t, harness, path, origin, session,
[]string{body, body, body}, []string{nextKey(), nextKey(), nextKey()})
var answers []string
for _, response := range responses {
accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK)
if accepted.State != "accepted" {
t.Fatalf("concurrent answer = %+v, want accepted", accepted)
}
answers = append(answers, response.Body.String())
}
if !slices.Equal(answers[1:], answers[:len(answers)-1]) {
t.Fatalf("concurrent answers differ: %v", answers)
}
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 3}) {
t.Fatalf("concurrent acceptances stored %+v, want one transition, one grant, one consent", counts)
}
// Two different field sets race: one transition, the other a conflict.
other := candidates[3]
raced := deliver(other)
responses = parallelAcceptRequests(t, harness, myPath(raced.ID)+"/accept", origin, login(other),
[]string{
acceptBody(raced.Version, raced.TermsVersion, acceptTextVersion, "email"),
acceptBody(raced.Version, raced.TermsVersion, acceptTextVersion, "phone"),
}, []string{nextKey(), nextKey()})
statuses := []int{responses[0].Code, responses[1].Code}
slices.Sort(statuses)
if !slices.Equal(statuses, []int{http.StatusOK, http.StatusConflict}) {
t.Fatalf("raced acceptances = %v, want one 200 and one 409 state_conflict", statuses)
}
if counts := readInvitationAcceptCounts(ctx, t, harness, raced.ID, other.ID); counts.acceptedEvents != 1 || counts.grants != 1 || counts.c4Consents != 1 {
t.Fatalf("raced acceptances stored %+v, want one transition, one grant, one consent", counts)
}
})
t.Run("a hidden organization accepts without changing the publication or the hiding", func(t *testing.T) {
candidate := candidates[4]
sent := deliver(candidate)
privacy.hide(t, candidate.ID, orgA, harness.clock.Now())
publication := privacy.rawPublication(t, candidate.ID)
hidden := privacy.rawHidden(t, candidate.ID)
response := accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email"), nextKey())
accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK)
grant := decodeContactGrantHTTP(t, accepted)
if grant.Readable || grant.BlockedBy == nil || *grant.BlockedBy != "visibility" || len(grant.Fields) != 1 {
t.Fatalf("grant while hidden = %+v, want stored and blocked by visibility", grant)
}
if after := privacy.rawPublication(t, candidate.ID); after != publication {
t.Fatalf("the acceptance changed the publication: %s became %s", publication, after)
}
if after := privacy.rawHidden(t, candidate.ID); after != hidden {
t.Fatalf("the acceptance changed the hiding: %s became %s", hidden, after)
}
// The candidate removes the hiding; the same grant becomes readable.
if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1 AND organization_id = $2`,
candidate.ID, orgA); err != nil {
t.Fatalf("unhide the organization: %v", err)
}
reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK)
if grantRead := decodeContactGrantHTTP(t, reread); grantRead.ID != grant.ID || !grantRead.Readable || grantRead.BlockedBy != nil {
t.Fatalf("grant after unhiding = %+v, want the same grant readable", grantRead)
}
})
t.Run("a late acceptance is refused under its key whatever the version", func(t *testing.T) {
candidate := candidates[5]
sent := deliver(candidate)
var deadline time.Time
if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, sent.ID).Scan(&deadline); err != nil {
t.Fatalf("read the deadline: %v", err)
}
harness.clock.Set(deadline.UTC())
key := nextKey()
for range 2 {
requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(sent.Version+5, sent.TermsVersion, acceptTextVersion, "email"), key),
http.StatusConflict, "state_conflict")
}
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{outcomes: 1}) {
t.Fatalf("late acceptances stored %+v, want one state_conflict outcome and nothing else", counts)
}
})
t.Run("the consent text and the held kinds are checked before anything is stored", func(t *testing.T) {
// The late case moved the clock to a deadline, which ends the owner session.
sessionOwner = loginOrganizationHTTP(t, harness.sessionHTTPHarness, owner.Email.Address())
candidate := candidates[6]
sent := deliver(candidate)
requireInvitationValidation(t, accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, "c4-2025-01-01", "email"), nextKey()),
"/consent_c4/text_version", "")
requireInvitationValidation(t, accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email", "telegram"), nextKey()),
"/consent_c4/fields/1", "")
if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{}) {
t.Fatalf("refused consent stored %+v", counts)
}
read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK)
if read.State != "delivered" || string(read.ContactGrant) != "null" {
t.Fatalf("read after the refusals = %+v, want the delivered invitation without a grant", read)
}
})
t.Run("the acceptance answers stay out of the server log", func(t *testing.T) {
requireNoCandidateData("server log", harness.logs.String())
})
}
func TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
// The fixture creates an organization with the schema of the current head.
fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL)
// Migrations added after this one are not part of this guard: the test
// rolls them back, so that this migration is the one rolled back below.
rollBackAboveVersion(ctx, t, migrator, invitationAcceptMigrationVersion)
store := func(t *testing.T, work func(context.Context, outbound.UnitOfWork) error) error {
t.Helper()
return fixture.transactor.WithinTransaction(ctx, work)
}
deliverDraft := func(t *testing.T) domain.Invitation {
t.Helper()
draft := fixture.draft(t)
delivered, err := draft.Deliver(draft.UpdatedAt().Add(time.Minute))
if err != nil {
t.Fatalf("Deliver() error = %v", err)
}
event, err := delivered.DeliveryEvent(fixture.owner.ID)
if err != nil {
t.Fatalf("DeliveryEvent() error = %v", err)
}
if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event)
}); err != nil {
t.Fatalf("Deliver() through the repository error = %v", err)
}
return delivered
}
delivered := deliverDraft(t)
acceptedAt := delivered.UpdatedAt().Add(time.Minute)
accepted, err := delivered.Accept(delivered.TermsVersion(), acceptedAt)
if err != nil {
t.Fatalf("Accept() error = %v", err)
}
acceptEvent, err := accepted.AnswerEvent(fixture.candidate.ID)
if err != nil {
t.Fatalf("AnswerEvent() error = %v", err)
}
fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail)
if err != nil {
t.Fatalf("NewContactFieldSet() error = %v", err)
}
consents := consent.NewService(fixture.transactor, func() time.Time { return acceptedAt })
if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.Invitations().Accept(ctx, delivered.Version(), accepted, acceptEvent); err != nil {
return err
}
granted, err := consents.GrantContact(ctx, unit, consent.ContactGrantInput{
SubjectID: fixture.candidate.ID, OrganizationID: fixture.organization.ID(), OrganizationName: fixture.organization.Profile().Name(),
Fields: fields, InvitationID: delivered.ID(), InvitationTermsVersion: delivered.TermsVersion(), TextVersion: acceptTextVersion,
})
if err != nil {
return err
}
grant, err := domain.NewContactGrant(granted.Record, accepted)
if err != nil {
return err
}
return unit.ContactGrants().Create(ctx, grant)
}); err != nil {
t.Fatalf("accept through the repositories error = %v", err)
}
// The database guards the acceptance and its grant against other writers.
_, err = pool.Exec(ctx, `UPDATE invitations SET state = 'delivered', responded_at = NULL, version = version + 1 WHERE id = $1`, delivered.ID())
assertPgError(t, "leave the acceptance", err, privacyIntegrityViolation, "invitations_answer_immutable")
_, err = pool.Exec(ctx, `UPDATE contact_grants SET fields = '{phone}' WHERE source_invitation_id = $1`, delivered.ID())
assertPgError(t, "change the grant", err, privacyIntegrityViolation, "contact_grants_immutable")
_, err = pool.Exec(ctx, `DELETE FROM contact_grants WHERE source_invitation_id = $1`, delivered.ID())
assertPgError(t, "delete the grant", err, privacyIntegrityViolation, "contact_grants_immutable")
_, err = pool.Exec(ctx, `INSERT INTO invitation_events (id, invitation_id, organization_id, version, terms_version, kind, actor_id, changed_fields, occurred_at)
SELECT $1, id, organization_id, version + 1, terms_version, 'accepted', created_by, ARRAY['terms'], now() FROM invitations WHERE id = $2`, uuid.New(), delivered.ID())
assertPgError(t, "accepted event with a field", err, privacyCheckViolation, "invitation_events_answer_changes_no_field")
// An acceptance without its grant cannot commit.
other := deliverDraft(t)
_, err = pool.Exec(ctx, `UPDATE invitations SET state = 'accepted', responded_at = delivered_at + interval '1 minute',
updated_at = delivered_at + interval '1 minute', version = version + 1 WHERE id = $1`, other.ID())
assertPgError(t, "accepted without a grant", err, privacyIntegrityViolation, "invitations_acceptance_recorded")
_, err = migrator.DownOne(ctx)
assertPgError(t, "DownOne() with an accepted invitation", err, privacyIntegrityViolation, invitationAcceptancesRetained)
// The database is isolated to this test: CASCADE also clears the tables that
// refer to the consent ledger, such as the publication history of C2.
if _, err := pool.Exec(ctx, `TRUNCATE consent_records, invitations, invitation_accept_results, invitation_decline_results,
invitation_send_results, invitation_creation_results CASCADE`); err != nil {
t.Fatalf("clear the invitation tables: %v", err)
}
result, err := migrator.DownOne(ctx)
if err != nil || result.Version != invitationAcceptMigrationVersion {
t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationAcceptMigrationVersion)
}
var remaining int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name IN ('contact_grants', 'invitation_accept_results')`).Scan(&remaining); err != nil || remaining != 0 {
t.Fatalf("acceptance tables left after the rollback: %d, %v", remaining, err)
}
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() after the rollback error = %v", err)
}
}
@@ -9,6 +9,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"time"
@@ -254,9 +255,25 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) {
read := request(http.MethodGet, myPath(sent.ID), "", sessionTarget, "")
opened := decodeCandidateInvitationHTTP(t, read, http.StatusOK)
requireNoCandidateData("candidate read", read.Body.String())
// While an acceptance is possible the read offers the consent C4 with
// the kinds that the profile holds, and no grant exists yet.
var offer struct {
Text struct {
TextVersion string `json:"text_version"`
Text string `json:"text"`
} `json:"text"`
AvailableFields []string `json:"available_fields"`
}
if err := json.Unmarshal(opened.ContactConsent, &offer); err != nil {
t.Fatalf("decode contact consent %s: %v", opened.ContactConsent, err)
}
if strings.Contains(offer.Text.Text, "{organization}") || !strings.Contains(offer.Text.Text, nameA) ||
offer.Text.TextVersion != "c4-2026-10-01" || !slices.Equal(offer.AvailableFields, []string{"full_name", "email"}) {
t.Fatalf("contact consent = %+v, want the C4 text for the organization and the held kinds", offer)
}
if opened.State != "delivered" || opened.Version != sent.Version || opened.ViewedAt != nil || opened.Organization.ID != orgA ||
opened.Organization.Name != nameA || opened.ResponseDeadlineAt != *sent.ResponseDeadlineAt || opened.Decline != nil ||
string(opened.ContactConsent) != "null" || string(opened.ContactGrant) != "null" || len(opened.Terms) == 0 {
string(opened.ContactGrant) != "null" || len(opened.Terms) == 0 {
t.Fatalf("read = %+v, want the delivered invitation with its terms and no side effect", opened)
}
// A read records nothing: it is free of side effects by contract.
@@ -30,6 +30,7 @@ import (
"lincodex/backend/internal/usecase/anonymousprofile"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/companyquota"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
invitationusecase "lincodex/backend/internal/usecase/invitation"
@@ -119,7 +120,7 @@ func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnviro
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
return quota.ReserveInvitation(ctx, unit, organization, invitationID)
},
Notifier: notifier, Clock: clock.Now,
Notifier: notifier, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now,
})
if err != nil {
t.Fatalf("invitation.NewService() error = %v", err)
@@ -1078,13 +1078,15 @@ func TestMatchSearchOverHTTP(t *testing.T) {
})
t.Run("the allowance of an organization ends the output and the group limit cuts it, without a total", func(t *testing.T) {
orgC := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization C"), now)
// Organizations of one owner share the E0 pool, so this one gets an owner of its own.
ownerC := client.employer(t, "match-employer-c@example.test")
orgC := organizations.create(t, domain.User{ID: ownerC.id}, organizations.completeProfile(t, "Match organization C"), now)
bounded := func(product *domain.ProductPolicy) {
product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8
}
publishPolicy(bounded)
searchC := func() (matchSearchBody, string) {
result, response := search(employer, orgC.ID(), `{"filters":{}}`)
result, response := search(ownerC, orgC.ID(), `{"filters":{}}`)
if response.Code != http.StatusOK {
t.Fatalf("search of organization C = %d %s", response.Code, response.Body.String())
}
@@ -1119,7 +1121,7 @@ func TestMatchSearchOverHTTP(t *testing.T) {
cardPath := func(handle string) string {
return fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgC.ID(), handle)
}
if got := harness.request(t, http.MethodGet, cardPath(first.Groups.Main[0].CandidateHandle), "", "", employer.cookie, "", client.remote()); got.Code != http.StatusOK ||
if got := harness.request(t, http.MethodGet, cardPath(first.Groups.Main[0].CandidateHandle), "", "", ownerC.cookie, "", client.remote()); got.Code != http.StatusOK ||
revealedBy(orgC.ID()) != 8 {
t.Fatalf("card of a paid candidate = %d, paid %d, want 200 and no new charge", got.Code, revealedBy(orgC.ID()))
}
@@ -1131,7 +1133,7 @@ func TestMatchSearchOverHTTP(t *testing.T) {
}
}
}
if got := harness.request(t, http.MethodGet, cardPath(unpaid), "", "", employer.cookie, "", client.remote()); got.Code != http.StatusTooManyRequests {
if got := harness.request(t, http.MethodGet, cardPath(unpaid), "", "", ownerC.cookie, "", client.remote()); got.Code != http.StatusTooManyRequests {
t.Fatalf("card of an unpaid candidate = %d, want 429 from the same allowance", got.Code)
}
// The organizations pay independently of each other.
@@ -1176,7 +1178,8 @@ func TestMatchSearchOverHTTP(t *testing.T) {
})
t.Run("two concurrent searches of one organization never charge beyond the allowance", func(t *testing.T) {
orgD := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization D"), now)
ownerD := client.employer(t, "match-employer-d@example.test")
orgD := organizations.create(t, domain.User{ID: ownerD.id}, organizations.completeProfile(t, "Match organization D"), now)
publishPolicy(func(product *domain.ProductPolicy) { product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8 })
type outcome struct {
status int
@@ -1193,7 +1196,7 @@ func TestMatchSearchOverHTTP(t *testing.T) {
group.Add(1)
go func() {
defer group.Done()
response := harness.request(t, http.MethodPost, searchPath(orgD.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, employer.cookie, employer.csrf, remote)
response := harness.request(t, http.MethodPost, searchPath(orgD.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, ownerD.cookie, ownerD.csrf, remote)
outcomes <- outcome{status: response.Code, body: response.Body.String()}
}()
}
@@ -1238,7 +1241,8 @@ func TestMatchSearchOverHTTP(t *testing.T) {
})
t.Run("concurrent card reads, evidence reads, and searches of one organization neither deadlock nor overcharge", func(t *testing.T) {
orgF := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization F"), now)
ownerF := client.employer(t, "match-employer-f@example.test")
orgF := organizations.create(t, domain.User{ID: ownerF.id}, organizations.completeProfile(t, "Match organization F"), now)
visible := make([]categoryHTTPCandidate, 0, 17)
for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} {
visible = append(visible, group...)
@@ -1269,14 +1273,14 @@ func TestMatchSearchOverHTTP(t *testing.T) {
remote := client.remote()
path := fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s%s", orgF.ID(), aliasIn(orgF.ID(), member.id), suffix)
return func() outcome {
response := harness.request(t, http.MethodGet, path, "", "", employer.cookie, "", remote)
response := harness.request(t, http.MethodGet, path, "", "", ownerF.cookie, "", remote)
return outcome{what: "card" + suffix, status: response.Code}
}
}
searchJob := func() func() outcome {
remote := client.remote()
return func() outcome {
response := harness.request(t, http.MethodPost, searchPath(orgF.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, employer.cookie, employer.csrf, remote)
response := harness.request(t, http.MethodPost, searchPath(orgF.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, ownerF.cookie, ownerF.csrf, remote)
return outcome{what: "search", status: response.Code}
}
}
+7 -5
View File
@@ -367,9 +367,8 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
t.Fatalf("apply migrations to rollback test database: %v", err)
}
// The preflight belongs to the migration that created the replay table, so
// the migrations added after it are rolled back first. The database holds
// no data yet, which keeps their own guarded rollbacks out of this test.
rollBackAboveMigration(ctx, t, migrator, needCreationResultMigrationVersion)
// the migrations added after it are rolled back first. The one organization
// below has its own holding, so their guarded rollbacks do not refuse.
pool := newPoolFor(ctx, t, databaseURL)
now := time.Now().UTC().Truncate(time.Microsecond)
fixture := organizationFixture{
@@ -377,6 +376,11 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now},
transactor: postgresadapter.NewTransactor(pool), now: now,
}
// The organization is created while the latest schema is in place: its
// creation needs the holdings table, which the rollback below removes.
owner := fixture.employer(t, "need-migration-owner@example.test")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now)
rollBackAboveMigration(ctx, t, migrator, needCreationResultMigrationVersion)
scope := []byte(strings.Repeat("s", outbound.IdempotencyDigestSize))
fingerprint := []byte(strings.Repeat("f", outbound.IdempotencyDigestSize))
if _, err := pool.Exec(ctx, `
@@ -400,8 +404,6 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
now.Add(-outbound.IdempotencyRetention-time.Second), now.Add(-time.Second), scope); err != nil {
t.Fatalf("expire idempotency replay before checking historical bounds: %v", err)
}
owner := fixture.employer(t, "need-migration-owner@example.test")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now)
need := newIntegrationNeed(t, organization.ID(), "Bounded rollback fixture", now.Add(time.Minute))
encoded, err := json.Marshal(need.Snapshot())
if err != nil {
@@ -31,8 +31,8 @@ func TestSyntheticNotificationMigrationAllowlistAndGuardedRollback(t *testing.T)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion)
// The candidate and the organization are created while the latest schema is in
// place: their creation needs the holdings table, which the rollback removes.
now := time.Now().UTC().Truncate(time.Microsecond)
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
candidate := identity.createUser(t, "inbox-migration@example.com", domain.ScenarioCandidate, now.Add(-time.Hour))
@@ -42,6 +42,8 @@ func TestSyntheticNotificationMigrationAllowlistAndGuardedRollback(t *testing.T)
owner := organizations.employer(t, "inbox-migration-owner@example.com")
organization := organizations.create(t, owner, organizations.completeProfile(t, "Example Company"), now)
rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion)
insert := func(eventType, sourceType string, schemaVersion int) error {
_, err := pool.Exec(ctx, `INSERT INTO notification_inbox_events (
recipient_user_id, event_id, organization_id, event_type, schema_version, source_type, source_id, occurred_at
+15 -5
View File
@@ -41,11 +41,13 @@ var (
organizationTables = []pgx.Identifier{
{"candidate_card_access_events"},
{"invitation_creation_results"}, {"invitation_send_results"}, {"invitation_decline_results"}, {"invitation_declines"},
{"invitation_events"}, {"invitation_terms_versions"}, {"invitations"},
{"invitation_events"}, {"invitation_terms_versions"}, {"invitation_accept_results"}, {"contact_grants"}, {"invitations"},
{"organization_need_versions"}, {"organization_needs"},
{"organization_need_creation_results"},
{"company_invitation_quota_usage"}, {"company_card_view_quota_usage"},
organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable,
// holdings reference users and are referenced by organizations.
{"holdings"},
}
candidateQuestionnaireTables = []pgx.Identifier{
{"candidate_questionnaire_specializations"}, {"candidate_questionnaires"},
@@ -260,10 +262,16 @@ func TestOrganizationsAndMemberships(t *testing.T) {
reset(t)
member := fixture.employer(t, "member@example.com")
insertOrganization := func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error {
if _, err := tx.Exec(ctx, `
INSERT INTO holdings (id, founder_account_id, created_at) VALUES ($1, $2, $3)
ON CONFLICT (founder_account_id) DO NOTHING`, uuid.New(), member.ID, now); err != nil {
return err
}
_, err := tx.Exec(ctx, `
INSERT INTO organizations (
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at
) VALUES ($1, 'ООО Без владельца', 'e0', 'confirmed_email', $2, 1, $2, $2)`, id, now)
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id
) VALUES ($1, 'ООО Без владельца', 'e0', 'confirmed_email', $2, 1, $2, $2,
(SELECT id FROM holdings WHERE founder_account_id = $3))`, id, now, member.ID)
return err
}
insertMember := func(ctx context.Context, tx pgx.Tx, organizationID uuid.UUID, role, state string) error {
@@ -692,10 +700,12 @@ func TestOrganizationsAndMemberships(t *testing.T) {
user := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, user, fixture.completeProfile(t, "ООО Пример"), now)
insertOrganization := func(name, verificationLevel, basis string, version int) error {
// The holding of the owner exists, so only the checked columns can fail.
_, err := pool.Exec(ctx, `
INSERT INTO organizations (
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at
) VALUES ($1, $2, $3, $4, $5, $6, $5, $5)`, uuid.New(), name, verificationLevel, basis, now, version)
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id
) VALUES ($1, $2, $3, $4, $5, $6, $5, $5,
(SELECT id FROM holdings WHERE founder_account_id = $7))`, uuid.New(), name, verificationLevel, basis, now, version, user.ID)
return err
}
for _, test := range []struct {
+1 -1
View File
@@ -252,7 +252,7 @@ func TestPolicyVersions(t *testing.T) {
assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks,
assessment_synthetic_category_reviews, candidate_assessment_categories,
skill_evidence_facts, skill_evidence_skills,
invitations, invitation_terms_versions, invitation_events, invitation_declines`},
invitations, invitation_terms_versions, invitation_events, invitation_declines, contact_grants`},
}
for _, statement := range statements {
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
@@ -807,6 +807,18 @@ func TestSkillEvidenceOverHTTP(t *testing.T) {
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE event_id = $1`, targetRun.id); err != nil {
t.Fatalf("hide the fact: %v", err)
}
// The rollback of the holdings migration refuses a holding that groups several
// organizations. The second organization moves to a holding of its own first;
// the evidence rollback under test does not depend on the grouping.
split := client.employer(t, "evidence-holding-split@example.test")
if _, err := harness.pool.Exec(ctx, `
INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, now())`, split.id); err != nil {
t.Fatalf("create the holding of the split organization: %v", err)
}
if _, err := harness.pool.Exec(ctx, `
UPDATE organizations SET holding_id = (SELECT id FROM holdings WHERE founder_account_id = $1) WHERE id = $2`, split.id, organizationB.ID()); err != nil {
t.Fatalf("move the second organization to its own holding: %v", err)
}
// Later migrations may exist; the rollback under test is the evidence one.
rollBackAboveMigration(ctx, t, migrator, skillEvidenceMigrationVersion)
_, err = migrator.DownOne(ctx)