Files
lincodex/backend/integration_test/registration_consent_migration_test.go
T

282 lines
13 KiB
Go

//go:build integration
package integration_test
import (
"context"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
)
const (
registrationConsentMigrationVersion = 16
registrationConsentMigrationName = "00016_bind_registration_consent.sql"
mailRetryMigrationName = "00017_retry_unknown_mail.sql"
)
func TestRegistrationConsentMigration(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
defer cancel()
t.Run("binds legacy C1 rows and survives down and up", func(t *testing.T) {
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("apply migrations before preparing legacy data: %v", err)
}
rollbackThroughRegistrationConsent(ctx, t, migrator)
assertRegistrationConsentColumn(ctx, t, pool, false)
const userID = "018f0000-0000-7000-8000-000000000001"
const registrationConsentID = "018f0000-0000-7000-8000-000000000002"
const settingsConsentID = "018f0000-0000-7000-8000-000000000003"
const otherConsentID = "018f0000-0000-7000-8000-000000000004"
const c1SettingsVersion = "c1-migration-settings"
createdAt := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
registrationAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
settingsAt := time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC)
seedRegistrationConsentFixture(ctx, t, pool, userID, createdAt, registrationAt, registrationConsentID, settingsConsentID, otherConsentID, c1SettingsVersion, settingsAt)
applied, err := migrator.Up(ctx)
if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName {
t.Fatalf("apply registration-consent and later migrations = %+v, %v", applied, err)
}
assertConsentRegistrationVersion(ctx, t, pool, registrationConsentID, 2)
assertConsentRegistrationVersionNull(ctx, t, pool, settingsConsentID, otherConsentID)
// Model a later registration after its former C1 was discarded. Old
// binaries omit registration_version; the insert trigger must bind the
// new C1 to the account version in effect at insert time.
if _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1::uuid`, registrationConsentID); err != nil {
t.Fatalf("remove the previous unverified registration C1: %v", err)
}
nextRegistrationAt := registrationAt.Add(24 * time.Hour)
if _, err := pool.Exec(ctx, `UPDATE users SET registration_version = 3, last_registered_at = $2, version = version + 1, updated_at = $2 WHERE id = $1::uuid`, userID, nextRegistrationAt); err != nil {
t.Fatalf("advance the synthetic registration: %v", err)
}
const compatibilityConsentID = "018f0000-0000-7000-8000-000000000005"
insertLegacyRegistrationC1(ctx, t, pool, compatibilityConsentID, userID, "c1-2026-10-01", nextRegistrationAt)
assertConsentRegistrationVersion(ctx, t, pool, compatibilityConsentID, 3)
beforeMismatch := countConsentRecords(ctx, t, pool)
const mismatchedConsentID = "018f0000-0000-7000-8000-000000000006"
_, err = pool.Exec(ctx, `
INSERT INTO consent_records (
id, subject_id, purpose, text_version, text_hash, source, granted_at, registration_version
)
SELECT $1::uuid, $2::uuid, text.purpose, text.version, text.body_sha256,
'registration', $3, 2
FROM consent_texts AS text
WHERE text.purpose = 'c1' AND text.version = 'c1-2026-10-01'`, mismatchedConsentID, userID, nextRegistrationAt)
assertSQLError(t, "registration C1 with an explicitly mismatched version", err, "23514", "consent_records_registration_version_matches_user")
if countConsentRecords(ctx, t, pool) != beforeMismatch {
t.Fatal("a registration C1 with a mismatched account version was inserted")
}
_, err = pool.Exec(ctx, `UPDATE consent_records
SET registration_version = 4, revoked_at = granted_at, revocation_source = 'support_request'
WHERE id = $1::uuid`, compatibilityConsentID)
assertSQLError(t, "changing a bound registration C1 version during revocation", err, "23000", "consent_records_immutable")
var version int64
var revokedAt *time.Time
if err := pool.QueryRow(ctx, `SELECT registration_version, revoked_at FROM consent_records WHERE id = $1::uuid`, compatibilityConsentID).Scan(&version, &revokedAt); err != nil {
t.Fatalf("read C1 after refused version change: %v", err)
}
if version != 3 || revokedAt != nil {
t.Fatal("a refused registration C1 version change altered its version or revocation state")
}
rollbackThroughRegistrationConsent(ctx, t, migrator)
assertRegistrationConsentColumn(ctx, t, pool, false)
if countConsentRecords(ctx, t, pool) != beforeMismatch {
t.Fatal("rolling back the registration-consent migration changed the consent ledger")
}
applied, err = migrator.Up(ctx)
if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName {
t.Fatalf("reapply registration-consent and later migrations = %+v, %v", applied, err)
}
assertRegistrationConsentColumn(ctx, t, pool, true)
assertConsentRegistrationVersion(ctx, t, pool, compatibilityConsentID, 3)
assertConsentRegistrationVersionNull(ctx, t, pool, settingsConsentID, otherConsentID)
})
t.Run("refuses stale legacy registration C1 without a partial migration", func(t *testing.T) {
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("apply migrations before preparing stale legacy data: %v", err)
}
rollbackThroughRegistrationConsent(ctx, t, migrator)
assertRegistrationConsentColumn(ctx, t, pool, false)
const userID = "018f0000-0000-7000-8000-000000000101"
const consentID = "018f0000-0000-7000-8000-000000000102"
createdAt := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
grantAt := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
lastRegisteredAt := grantAt.Add(24 * time.Hour)
seedRegistrationMigrationUser(ctx, t, pool, userID, createdAt, lastRegisteredAt, 1)
insertLegacyRegistrationC1(ctx, t, pool, consentID, userID, "c1-2026-10-01", grantAt)
if _, err := migrator.Up(ctx); err == nil {
t.Fatal("migration accepted a registration C1 older than the account's latest registration")
}
assertRegistrationConsentColumn(ctx, t, pool, false)
if countConsentRecords(ctx, t, pool) != 1 {
t.Fatal("a failed migration partially changed the legacy consent record")
}
statuses, err := migrator.Status(ctx)
if err != nil {
t.Fatalf("read migration status after failed migration: %v", err)
}
for _, status := range statuses {
if status.Name == registrationConsentMigrationName && status.Applied {
t.Fatal("failed migration was recorded as applied")
}
}
if _, err := pool.Exec(ctx, `UPDATE users SET last_registered_at = $2, updated_at = $2 WHERE id = $1::uuid`, userID, grantAt); err != nil {
t.Fatalf("correct the synthetic legacy registration timestamp: %v", err)
}
applied, err := migrator.Up(ctx)
if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName {
t.Fatalf("migrations did not succeed after the legacy data was corrected: %+v, %v", applied, err)
}
assertRegistrationConsentColumn(ctx, t, pool, true)
assertConsentRegistrationVersion(ctx, t, pool, consentID, 1)
})
}
// rollbackThroughRegistrationConsent removes later migrations as well, so
// each fixture is truly at the schema immediately before migration 00016.
func rollbackThroughRegistrationConsent(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) {
t.Helper()
for {
rolledBack, err := migrator.DownOne(ctx)
if err != nil {
t.Fatalf("roll back through registration-consent migration: %v", err)
}
if rolledBack.Version < registrationConsentMigrationVersion {
t.Fatalf("rolled back migration %d before reaching migration %d", rolledBack.Version, registrationConsentMigrationVersion)
}
if rolledBack.Version == registrationConsentMigrationVersion {
if rolledBack.Name != registrationConsentMigrationName {
t.Fatalf("rolled back migration %d named %q, want %q", rolledBack.Version, rolledBack.Name, registrationConsentMigrationName)
}
return
}
}
}
func seedRegistrationConsentFixture(
ctx context.Context,
t *testing.T,
pool *pgxpool.Pool,
userID string,
createdAt, registrationAt time.Time,
registrationConsentID, settingsConsentID, otherConsentID, c1SettingsVersion string,
settingsAt time.Time,
) {
t.Helper()
seedRegistrationMigrationUser(ctx, t, pool, userID, createdAt, registrationAt, 2)
if _, err := pool.Exec(ctx, `
INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at)
SELECT purpose, $1, body, sha256(convert_to(body, 'UTF8')), kind, $2
FROM consent_texts WHERE purpose = 'c1' AND version = 'c1-2026-10-01'`, c1SettingsVersion, createdAt.Add(24*time.Hour)); err != nil {
t.Fatalf("insert synthetic C1 text for a settings consent: %v", err)
}
insertLegacyRegistrationC1(ctx, t, pool, registrationConsentID, userID, "c1-2026-10-01", registrationAt)
insertLegacyConsent(ctx, t, pool, settingsConsentID, userID, "c1", c1SettingsVersion, "consent_settings", settingsAt)
insertLegacyConsent(ctx, t, pool, otherConsentID, userID, "c2", "c2-2026-10-01", "consent_settings", settingsAt)
}
func seedRegistrationMigrationUser(
ctx context.Context,
t *testing.T,
pool *pgxpool.Pool,
userID string,
createdAt, lastRegisteredAt time.Time,
registrationVersion int64,
) {
t.Helper()
const passwordHash = "$argon2id$v=19$m=1,t=1,p=1$c2FsdA$cGFzcw"
if _, err := pool.Exec(ctx, `
INSERT INTO users (
id, email, email_normalized, password_hash, scenario, onboarding_step,
registration_version, last_registered_at, version, created_at, updated_at
) VALUES ($1::uuid, 'migration.owner@example.test', 'migration.owner@example.test', $2,
'candidate', 'candidate_consents', $3, $4, 1, $5, $4)`,
userID, passwordHash, registrationVersion, lastRegisteredAt, createdAt); err != nil {
t.Fatalf("insert synthetic account before migration: %v", err)
}
}
func insertLegacyRegistrationC1(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID, userID, version string, grantedAt time.Time) {
t.Helper()
insertLegacyConsent(ctx, t, pool, consentID, userID, "c1", version, "registration", grantedAt)
}
func insertLegacyConsent(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID, userID, purpose, version, source string, grantedAt time.Time) {
t.Helper()
if _, err := pool.Exec(ctx, `
INSERT INTO consent_records (id, subject_id, purpose, text_version, text_hash, source, granted_at)
SELECT $1::uuid, $2::uuid, text.purpose, text.version, text.body_sha256, $5, $6
FROM consent_texts AS text WHERE text.purpose = $3 AND text.version = $4`,
consentID, userID, purpose, version, source, grantedAt); err != nil {
t.Fatalf("insert synthetic legacy consent: %v", err)
}
}
func assertRegistrationConsentColumn(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool) {
t.Helper()
var exists bool
if err := pool.QueryRow(ctx, `SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'consent_records' AND column_name = 'registration_version'
)`).Scan(&exists); err != nil {
t.Fatalf("check registration-version column: %v", err)
}
if exists != want {
t.Fatalf("registration-version column exists = %t, want %t", exists, want)
}
}
func assertConsentRegistrationVersion(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID string, want int64) {
t.Helper()
var got int64
if err := pool.QueryRow(ctx, `SELECT registration_version FROM consent_records WHERE id = $1::uuid`, consentID).Scan(&got); err != nil {
t.Fatalf("read bound consent version: %v", err)
}
if got != want {
t.Fatalf("consent registration version = %d, want %d", got, want)
}
}
func assertConsentRegistrationVersionNull(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentIDs ...string) {
t.Helper()
for _, consentID := range consentIDs {
var version *int64
if err := pool.QueryRow(ctx, `SELECT registration_version FROM consent_records WHERE id = $1::uuid`, consentID).Scan(&version); err != nil {
t.Fatalf("read unbound consent version: %v", err)
}
if version != nil {
t.Fatalf("non-registration consent has registration version %d", *version)
}
}
}
func countConsentRecords(ctx context.Context, t *testing.T, pool *pgxpool.Pool) int {
t.Helper()
var count int
if err := pool.QueryRow(ctx, `SELECT count(*)::integer FROM consent_records`).Scan(&count); err != nil {
t.Fatalf("count consent records: %v", err)
}
return count
}