diff --git a/backend/db/migrations/00002_create_identity_tables.sql b/backend/db/migrations/00002_create_identity_tables.sql new file mode 100644 index 0000000..7733be4 --- /dev/null +++ b/backend/db/migrations/00002_create_identity_tables.sql @@ -0,0 +1,167 @@ +-- +goose Up +-- Identity storage: accounts, one-time email tokens, and server-side sessions. +-- Passwords, raw email tokens, and raw session tokens are never stored; only +-- an Argon2id PHC string and SHA-256 digests are. Every timestamp comes from +-- the application clock, so expiry checks and the stored deadlines use one +-- clock. Enum-like columns are text with CHECK constraints rather than +-- PostgreSQL enum types: a new value then changes one constraint in a later +-- migration, which can also be rolled back, while an enum value cannot be +-- removed and cannot be used in the transaction that adds it. +CREATE TABLE users ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + -- Delivery form: trimmed ASCII, letter case as typed. + email text NOT NULL, + -- Comparison key computed in Go: the delivery form with A-Z lowercased. + email_normalized text NOT NULL, + -- Argon2id PHC string; never the password. + password_hash text NOT NULL, + scenario text NOT NULL, + onboarding_step text NOT NULL, + email_verified_at timestamptz, + -- Advanced on every registration of the unverified email. Email tokens + -- are bound to the version they were issued for. + registration_version bigint NOT NULL, + -- Time of the latest registration; the planned cleanup of unverified + -- accounts counts its deadline from here. + last_registered_at timestamptz NOT NULL, + -- Optimistic concurrency version, advanced on every update. + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT users_pkey PRIMARY KEY (id), + CONSTRAINT users_email_normalized_key UNIQUE (email_normalized), + -- Addresses are ASCII until the mailer supports SMTPUTF8: one byte per + -- character in the UTF-8 database encoding. + CONSTRAINT users_email_ascii CHECK ( + char_length(email) BETWEEN 3 AND 254 + AND octet_length(email) = char_length(email) + ), + -- translate() maps A-Z by code point, independent of the collation, + -- unlike lower(). + CONSTRAINT users_email_normalized_rule CHECK ( + email_normalized = translate( + email, + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'abcdefghijklmnopqrstuvwxyz' + ) + ), + CONSTRAINT users_password_hash_format CHECK ( + char_length(password_hash) <= 512 + AND password_hash + ~ '^\$argon2id\$v=19\$m=[0-9]+,t=[0-9]+,p=[0-9]+\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$' + ), + CONSTRAINT users_scenario_onboarding_step CHECK ( + ( + scenario = 'candidate' + AND onboarding_step IN ( + 'candidate_consents', + 'candidate_profile', + 'candidate_questionnaire', + 'candidate_assessment', + 'completed' + ) + ) + OR ( + scenario = 'employer' + AND onboarding_step IN ('employer_company', 'completed') + ) + ), + CONSTRAINT users_registration_version_positive CHECK ( + registration_version > 0 + ), + CONSTRAINT users_version_positive CHECK (version > 0), + CONSTRAINT users_timestamps_after_creation CHECK ( + updated_at >= created_at + AND last_registered_at >= created_at + AND (email_verified_at IS NULL OR email_verified_at >= created_at) + ) +); + +-- Supports the planned cleanup of accounts that stay unverified after their +-- latest registration. Verified accounts are not indexed. +CREATE INDEX users_unverified_last_registered_at_idx +ON users (last_registered_at) +WHERE email_verified_at IS NULL; + +CREATE TABLE email_tokens ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + user_id uuid NOT NULL, + purpose text NOT NULL, + -- SHA-256 of the raw token as 32 raw bytes: half the size of hex text, + -- with an exact length check and no letter-case or encoding variants. + token_hash bytea NOT NULL, + registration_version bigint NOT NULL, + created_at timestamptz NOT NULL, + expires_at timestamptz NOT NULL, + consumed_at timestamptz, + -- Set when a re-registration or a resend replaces the token. + invalidated_at timestamptz, + CONSTRAINT email_tokens_pkey PRIMARY KEY (id), + CONSTRAINT email_tokens_token_hash_key UNIQUE (token_hash), + CONSTRAINT email_tokens_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT email_tokens_purpose_known CHECK ( + purpose IN ('email_verification') + ), + CONSTRAINT email_tokens_token_hash_sha256 CHECK ( + octet_length(token_hash) = 32 + ), + CONSTRAINT email_tokens_registration_version_positive CHECK ( + registration_version > 0 + ), + CONSTRAINT email_tokens_expiry_after_creation CHECK ( + expires_at > created_at + ), + -- A token ends at most once: either consumed or invalidated. + CONSTRAINT email_tokens_single_outcome CHECK ( + consumed_at IS NULL OR invalidated_at IS NULL + ), + CONSTRAINT email_tokens_outcome_after_creation CHECK ( + (consumed_at IS NULL OR consumed_at >= created_at) + AND (invalidated_at IS NULL OR invalidated_at >= created_at) + ) +); + +-- Serves invalidation of a user's tokens for one purpose and the cascade +-- delete of a user's tokens. +CREATE INDEX email_tokens_user_id_purpose_idx +ON email_tokens (user_id, purpose); + +CREATE TABLE sessions ( + -- UUIDv7 generated in Go; internal only, never sent to the client. + id uuid NOT NULL, + user_id uuid NOT NULL, + -- SHA-256 of the raw session token that the cookie carries. + token_hash bytea NOT NULL, + created_at timestamptz NOT NULL, + -- The idle timeout counts from here. + last_seen_at timestamptz NOT NULL, + -- Absolute deadline fixed at creation. + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + CONSTRAINT sessions_pkey PRIMARY KEY (id), + CONSTRAINT sessions_token_hash_key UNIQUE (token_hash), + CONSTRAINT sessions_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT sessions_token_hash_sha256 CHECK ( + octet_length(token_hash) = 32 + ), + CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at), + CONSTRAINT sessions_last_seen_after_creation CHECK ( + last_seen_at >= created_at + ), + CONSTRAINT sessions_revoked_after_creation CHECK ( + revoked_at IS NULL OR revoked_at >= created_at + ) +); + +-- Serves revocation of all of a user's sessions and the cascade delete. +CREATE INDEX sessions_user_id_idx +ON sessions (user_id); + +-- +goose Down +DROP TABLE sessions; +DROP TABLE email_tokens; +DROP TABLE users; diff --git a/backend/db/queries/identity.sql b/backend/db/queries/identity.sql new file mode 100644 index 0000000..d3e86ce --- /dev/null +++ b/backend/db/queries/identity.sql @@ -0,0 +1,333 @@ +-- name: InsertUser :exec +INSERT INTO users ( + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(email), + sqlc.arg(email_normalized), + sqlc.arg(password_hash), + sqlc.arg(scenario), + sqlc.arg(onboarding_step), + sqlc.narg(email_verified_at), + sqlc.arg(registration_version), + sqlc.arg(last_registered_at), + sqlc.arg(version), + sqlc.arg(created_at), + sqlc.arg(updated_at) +); + +-- name: GetUserByID :one +SELECT + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +FROM users +WHERE id = sqlc.arg(id); + +-- name: GetUserByEmailNormalized :one +SELECT + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +FROM users +WHERE email_normalized = sqlc.arg(email_normalized); + +-- Replaces the registration of an unverified account and advances the +-- registration version in the same statement, so no caller can choose it. +-- The version check rejects a writer that read an older row; a verified +-- account never changes. +-- name: UpdateUserRegistration :one +UPDATE users +SET + email = sqlc.arg(email), + password_hash = sqlc.arg(password_hash), + scenario = sqlc.arg(scenario), + onboarding_step = sqlc.arg(onboarding_step), + registration_version = registration_version + 1, + last_registered_at = sqlc.arg(last_registered_at), + updated_at = sqlc.arg(updated_at), + version = version + 1 +WHERE + id = sqlc.arg(id) + AND version = sqlc.arg(expected_version) + AND email_verified_at IS NULL +RETURNING + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at; + +-- Verifies the email only for the registration version the consumed token +-- was issued for. +-- name: MarkUserEmailVerified :one +UPDATE users +SET + email_verified_at = sqlc.arg(verified_at), + updated_at = sqlc.arg(verified_at), + version = version + 1 +WHERE + id = sqlc.arg(id) + AND registration_version = sqlc.arg(registration_version) + AND email_verified_at IS NULL +RETURNING + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at; + +-- Deletes one batch of accounts that stayed unverified since before cutoff, +-- oldest first, with their tokens and sessions. Every lock is taken with SKIP +-- LOCKED, so the statement never waits: an account whose row is locked, for +-- example by a re-registration or a token insert, is skipped, and so is an +-- account with any token or session row locked, for example by a +-- confirmation that consumed a token. Skipped accounts stay for the next run. +-- Taking the account lock before the token locks is the reverse of the +-- documented order, which is safe only because no lock here waits. +-- name: DeleteUnverifiedUsersRegisteredBefore :execrows +WITH candidate AS ( + SELECT stale.id + FROM users AS stale + WHERE + stale.email_verified_at IS NULL + AND stale.last_registered_at < sqlc.arg(cutoff) + ORDER BY stale.last_registered_at + LIMIT sqlc.arg(batch_limit) + FOR UPDATE SKIP LOCKED +), + +locked_token AS ( + SELECT token.user_id + FROM email_tokens AS token + WHERE token.user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +locked_session AS ( + SELECT session.user_id + FROM sessions AS session + WHERE session.user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +-- An account qualifies only when every token and session row visible to the +-- statement was locked above. +deletable AS ( + SELECT candidate.id + FROM candidate + WHERE + ( + SELECT count(*) FROM email_tokens AS token + WHERE token.user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_token + WHERE locked_token.user_id = candidate.id + ) + AND ( + SELECT count(*) FROM sessions AS session + WHERE session.user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_session + WHERE locked_session.user_id = candidate.id + ) +) + +DELETE FROM users +USING deletable +WHERE users.id = deletable.id; + +-- name: InsertEmailToken :exec +INSERT INTO email_tokens ( + id, + user_id, + purpose, + token_hash, + registration_version, + created_at, + expires_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(user_id), + sqlc.arg(purpose), + sqlc.arg(token_hash), + sqlc.arg(registration_version), + sqlc.arg(created_at), + sqlc.arg(expires_at) +); + +-- name: InvalidateActiveEmailTokens :execrows +UPDATE email_tokens +SET invalidated_at = sqlc.arg(invalidated_at) +WHERE + user_id = sqlc.arg(user_id) + AND purpose = sqlc.arg(purpose) + AND consumed_at IS NULL + AND invalidated_at IS NULL; + +-- Consumes a token in one statement. Concurrent callers queue on the token +-- row lock; under READ COMMITTED each waiter re-checks the WHERE clause +-- against the committed row, so exactly one of them updates it. The join +-- compares the registration version with the account row as the statement +-- reads it, without locking that row, so it rejects a token from an earlier +-- registration that already committed but not one that commits afterwards. +-- The confirmation guarantee therefore needs MarkUserEmailVerified with the +-- returned registration version in the same transaction, rolled back when it +-- matches no row. +-- name: ConsumeEmailToken :one +UPDATE email_tokens AS token +SET consumed_at = sqlc.arg(consumed_at) +FROM users AS owner +WHERE + token.token_hash = sqlc.arg(token_hash) + AND token.purpose = sqlc.arg(purpose) + AND token.consumed_at IS NULL + AND token.invalidated_at IS NULL + AND token.expires_at > sqlc.arg(consumed_at) + AND owner.id = token.user_id + AND owner.registration_version = token.registration_version +RETURNING + token.id, + token.user_id, + token.purpose, + token.token_hash, + token.registration_version, + token.created_at, + token.expires_at, + token.consumed_at, + token.invalidated_at; + +-- Explains why ConsumeEmailToken matched no row. +-- name: GetEmailTokenState :one +SELECT + token.consumed_at, + token.invalidated_at, + token.expires_at, + owner.registration_version = token.registration_version AS current_registration +FROM email_tokens AS token +INNER JOIN users AS owner ON token.user_id = owner.id +WHERE + token.token_hash = sqlc.arg(token_hash) + AND token.purpose = sqlc.arg(purpose); + +-- name: InsertSession :exec +INSERT INTO sessions ( + id, + user_id, + token_hash, + created_at, + last_seen_at, + expires_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(user_id), + sqlc.arg(token_hash), + sqlc.arg(created_at), + sqlc.arg(last_seen_at), + sqlc.arg(expires_at) +); + +-- name: GetActiveSessionByTokenHash :one +SELECT + id, + user_id, + token_hash, + created_at, + last_seen_at, + expires_at, + revoked_at +FROM sessions +WHERE + token_hash = sqlc.arg(token_hash) + AND revoked_at IS NULL + AND expires_at > sqlc.arg(at) + AND last_seen_at > sqlc.arg(idle_cutoff); + +-- Records activity on an active session and reports whether it is active. +-- The row is written only when last_seen_at is older than touch_cutoff, so +-- frequent requests do not rewrite it. last_seen_at never moves back, and a +-- revoked, expired, or idle session is not revived; the update re-checks +-- those conditions against a concurrent change. +-- name: TouchSession :one +WITH active_session AS ( + SELECT candidate.id + FROM sessions AS candidate + WHERE + candidate.id = sqlc.arg(id) + AND candidate.revoked_at IS NULL + AND candidate.expires_at > sqlc.arg(at) + AND candidate.last_seen_at > sqlc.arg(idle_cutoff) +), + +touched AS ( + UPDATE sessions + SET last_seen_at = sqlc.arg(at) + WHERE + sessions.id = sqlc.arg(id) + AND sessions.revoked_at IS NULL + AND sessions.expires_at > sqlc.arg(at) + AND sessions.last_seen_at > sqlc.arg(idle_cutoff) + AND sessions.last_seen_at < sqlc.arg(touch_cutoff) + RETURNING sessions.id +) + +SELECT + exists(SELECT 1 FROM active_session) AS active, + exists(SELECT 1 FROM touched) AS touched; + +-- name: RevokeSession :execrows +UPDATE sessions +SET revoked_at = sqlc.arg(revoked_at) +WHERE + id = sqlc.arg(id) + AND revoked_at IS NULL; + +-- name: RevokeUserSessions :execrows +UPDATE sessions +SET revoked_at = sqlc.arg(revoked_at) +WHERE + user_id = sqlc.arg(user_id) + AND revoked_at IS NULL; diff --git a/backend/integration_test/identity_test.go b/backend/integration_test/identity_test.go new file mode 100644 index 0000000..b75e683 --- /dev/null +++ b/backend/integration_test/identity_test.go @@ -0,0 +1,1214 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + identityTestTimeout = 2 * time.Minute + parallelConsumers = 10 + tokenLifetime = 24 * time.Hour + sessionLifetime = 7 * 24 * time.Hour + sessionIdleTimeout = 24 * time.Hour + signedInSessions = 3 + staleAccounts = 3 + cleanupBatch = 2 + cleanupLockTimeout = 200 * time.Millisecond + // heldTransactionConns covers a held transaction, a contender, and a spare. + heldTransactionConns = 3 + // A syntactically valid Argon2id PHC string; the tests never hash a password. + identityTestPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA" +) + +var ( + usersTable = pgx.Identifier{"users"} + emailTokensTable = pgx.Identifier{"email_tokens"} + sessionsTable = pgx.Identifier{"sessions"} + identityTables = []pgx.Identifier{usersTable, emailTokensTable, sessionsTable} +) + +type identityFixture struct { + ctx context.Context + pool *pgxpool.Pool + store *postgresadapter.IdentityStore + // now is truncated to microseconds, the precision PostgreSQL stores. + now time.Time +} + +func TestIdentityRepositories(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), identityTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + transactor := postgresadapter.NewTransactor(pool) + fixture := identityFixture{ + ctx: ctx, + pool: pool, + store: postgresadapter.NewIdentityStore(pool), + now: time.Now().UTC().Truncate(time.Microsecond), + } + + // Subtests share tables and run sequentially; each starts from empty tables. + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, identityTables...) + } + + t.Run("stores an account and finds it by ID and by any case of its email", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "Alice.Smith@Example.com", domain.ScenarioCandidate, fixture.now) + lookup := mustEmail(t, " alice.smith@EXAMPLE.COM ") + byEmail, err := fixture.store.Users().GetByEmail(ctx, lookup) + if err != nil { + t.Fatalf("GetByEmail() error = %v", err) + } + assertSameUser(t, byEmail, user) + if byEmail.Email.Address() != "Alice.Smith@Example.com" { + t.Fatalf("stored delivery address = %q, want the registered form", byEmail.Email.Address()) + } + byID, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + assertSameUser(t, byID, user) + + if _, err := fixture.store.Users().GetByID(ctx, uuid.New()); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(unknown) error = %v, want ErrUserNotFound", err) + } + if _, err := fixture.store.Users().GetByEmail(ctx, mustEmail(t, "nobody@example.com")); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByEmail(unknown) error = %v, want ErrUserNotFound", err) + } + }) + + t.Run("letter-case variants of an email conflict", func(t *testing.T) { + reset(t) + fixture.createUser(t, "Jose@Example.com", domain.ScenarioCandidate, fixture.now) + for _, variant := range []string{"jose@example.com", "JOSE@EXAMPLE.COM"} { + duplicate := fixture.newUser(t, variant, domain.ScenarioEmployer, fixture.now) + err := fixture.store.Users().Create(ctx, duplicate) + if !errors.Is(err, outbound.ErrEmailTaken) { + t.Fatalf("Create(%q) error = %v, want ErrEmailTaken", variant, err) + } + if !strings.Contains(err.Error(), "users_email_normalized_key") { + t.Fatalf("Create(%q) error = %v, want the constraint name", variant, err) + } + } + assertRowCount(ctx, t, pool, usersTable, 1) + }) + + t.Run("stores only hashes of email and session tokens", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "hashes@example.com", domain.ScenarioCandidate, fixture.now) + rawEmailToken, emailToken := fixture.issueToken(t, user, fixture.now, tokenLifetime) + rawSessionToken, session := fixture.startSession(t, user, fixture.now) + + for _, check := range []struct { + table pgx.Identifier + id uuid.UUID + raw domain.SecretToken + }{ + {table: emailTokensTable, id: emailToken.ID, raw: rawEmailToken}, + {table: sessionsTable, id: session.ID, raw: rawSessionToken}, + } { + var rowText string + var storedHash []byte + err := pool.QueryRow(ctx, fmt.Sprintf(` + SELECT row_to_json(stored)::text, stored.token_hash + FROM %s AS stored WHERE stored.id = $1`, check.table.Sanitize()), check.id).Scan(&rowText, &storedHash) + if err != nil { + t.Fatalf("read %s row: %v", check.table.Sanitize(), err) + } + if strings.Contains(rowText, check.raw.Reveal()) { + t.Fatalf("%s row contains the raw token", check.table.Sanitize()) + } + if want := sha256.Sum256([]byte(check.raw.Reveal())); string(storedHash) != string(want[:]) { + t.Fatalf("%s token_hash is not the SHA-256 digest of the raw token", check.table.Sanitize()) + } + } + for _, raw := range []domain.SecretToken{rawEmailToken, rawSessionToken} { + var matches int + err := pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM users AS u WHERE strpos(row_to_json(u)::text, $1) > 0) + + (SELECT count(*) FROM email_tokens AS e WHERE strpos(row_to_json(e)::text, $1) > 0) + + (SELECT count(*) FROM sessions AS s WHERE strpos(row_to_json(s)::text, $1) > 0)`, + raw.Reveal()).Scan(&matches) + if err != nil { + t.Fatalf("search identity tables for a raw token: %v", err) + } + if matches != 0 { + t.Fatalf("%d identity rows contain a raw token", matches) + } + } + + // Every secret-bearing column in the identity schema is a hash. + rows, err := pool.Query(ctx, ` + SELECT table_name || '.' || column_name FROM information_schema.columns + WHERE table_schema = 'public' + AND table_name IN ('users', 'email_tokens', 'sessions') + AND (column_name LIKE '%password%' OR column_name LIKE '%token%' OR column_name LIKE '%secret%') + AND column_name NOT LIKE '%\_hash' + ORDER BY 1`) + if err != nil { + t.Fatalf("list secret-bearing columns: %v", err) + } + unhashed, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + t.Fatalf("read secret-bearing columns: %v", err) + } + if len(unhashed) != 0 { + t.Fatalf("identity columns store secrets without hashing: %v", unhashed) + } + }) + + t.Run("re-registration advances versions and rejects a stale writer or a verified account", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "rereg@example.com", domain.ScenarioCandidate, fixture.now) + later := fixture.now.Add(time.Hour) + changed, err := user.ReRegister(fixture.registration(t, "ReReg@Example.com", domain.ScenarioEmployer, later)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + stored, err := fixture.store.Users().UpdateRegistration(ctx, changed) + if err != nil { + t.Fatalf("UpdateRegistration() error = %v", err) + } + if stored.Version != 2 || stored.RegistrationVersion != 2 || stored.Scenario != domain.ScenarioEmployer || + stored.OnboardingStep != domain.OnboardingStepEmployerCompany || stored.Email.Address() != "ReReg@Example.com" || + !stored.LastRegisteredAt.Equal(later) || !stored.CreatedAt.Equal(fixture.now) { + t.Fatalf("UpdateRegistration() = %+v", stored) + } + + // A writer that still holds version 1 must not overwrite version 2. + stale, err := user.ReRegister(fixture.registration(t, "rereg@example.com", domain.ScenarioCandidate, later)) + if err != nil { + t.Fatalf("ReRegister(stale) error = %v", err) + } + if _, err := fixture.store.Users().UpdateRegistration(ctx, stale); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("UpdateRegistration(stale) error = %v, want ErrUserVersionConflict", err) + } + + verified, err := fixture.store.Users().MarkEmailVerified(ctx, user.ID, stored.RegistrationVersion, later) + if err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + // The stored row is verified even if a caller still holds the unverified view. + unverifiedView := verified + unverifiedView.EmailVerifiedAt = nil + afterVerification, err := unverifiedView.ReRegister(fixture.registration(t, "rereg@example.com", domain.ScenarioCandidate, later)) + if err != nil { + t.Fatalf("ReRegister(unverified view) error = %v", err) + } + if _, err := fixture.store.Users().UpdateRegistration(ctx, afterVerification); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("UpdateRegistration(verified account) error = %v, want ErrUserVersionConflict", err) + } + current, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + assertSameUser(t, current, verified) + }) + + t.Run("verification requires the current registration version and happens once", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "verify@example.com", domain.ScenarioCandidate, fixture.now) + users := fixture.store.Users() + if _, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion+1, fixture.now); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("MarkEmailVerified(other registration version) error = %v, want ErrUserVersionConflict", err) + } + verified, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, fixture.now) + if err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + if !verified.EmailVerified() || !verified.EmailVerifiedAt.Equal(fixture.now) || verified.Version != user.Version+1 { + t.Fatalf("MarkEmailVerified() = %+v", verified) + } + if _, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, fixture.now); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("second MarkEmailVerified() error = %v, want ErrUserVersionConflict", err) + } + }) + + t.Run("parallel confirmations consume a token exactly once", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "parallel@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + // One connection per confirmation plus a spare, so nothing queues in the pool. + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, parallelConsumers+1)) + at := fixture.now.Add(time.Minute) + + errs := make([]error, parallelConsumers) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range parallelConsumers { + group.Go(func() { + <-start + errs[index] = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + token, err := unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, at) + if err != nil { + return err + } + _, err = unit.Users().MarkEmailVerified(ctx, token.UserID, token.RegistrationVersion, at) + return err + }) + }) + } + close(start) + group.Wait() + + successes := 0 + for index, err := range errs { + switch { + case err == nil: + successes++ + case errors.Is(err, outbound.ErrEmailTokenConsumed): + default: + t.Fatalf("confirmation %d error = %v, want nil or ErrEmailTokenConsumed", index, err) + } + } + if successes != 1 { + t.Fatalf("%d confirmations succeeded, want exactly 1", successes) + } + verified, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + if !verified.EmailVerified() || verified.Version != user.Version+1 { + t.Fatalf("account after confirmations = %+v, want verified once", verified) + } + }) + + t.Run("parallel consumes outside a transaction succeed exactly once", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "autocommit@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + concurrentStore := postgresadapter.NewIdentityStore(env.newPoolWithMaxConns(ctx, t, parallelConsumers+1)) + errs := make([]error, parallelConsumers) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range parallelConsumers { + group.Go(func() { + <-start + _, errs[index] = concurrentStore.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, fixture.now) + }) + } + close(start) + group.Wait() + successes := 0 + for index, err := range errs { + switch { + case err == nil: + successes++ + case errors.Is(err, outbound.ErrEmailTokenConsumed): + default: + t.Fatalf("consume %d error = %v, want nil or ErrEmailTokenConsumed", index, err) + } + } + if successes != 1 { + t.Fatalf("%d consumes succeeded, want exactly 1", successes) + } + }) + + t.Run("expired, invalidated, superseded, unknown, and wrong-purpose tokens are not consumable", func(t *testing.T) { + reset(t) + tokens := fixture.store.EmailTokens() + purpose := domain.EmailTokenPurposeEmailVerification + user := fixture.createUser(t, "states@example.com", domain.ScenarioCandidate, fixture.now) + other := fixture.createUser(t, "other@example.com", domain.ScenarioEmployer, fixture.now) + + expired, _ := fixture.issueToken(t, user, fixture.now.Add(-2*time.Hour), time.Hour) + assertConsumeError(ctx, t, tokens, expired, fixture.now, outbound.ErrEmailTokenExpired) + // The deadline itself is already past. + atDeadline, deadlineToken := fixture.issueToken(t, user, fixture.now, time.Hour) + assertConsumeError(ctx, t, tokens, atDeadline, deadlineToken.ExpiresAt, outbound.ErrEmailTokenExpired) + + unknown, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + assertConsumeError(ctx, t, tokens, unknown, fixture.now, outbound.ErrEmailTokenNotFound) + if _, err := tokens.Consume(ctx, atDeadline.Hash(), "password_reset", fixture.now); !errors.Is(err, outbound.ErrEmailTokenNotFound) { + t.Fatalf("Consume(wrong purpose) error = %v, want ErrEmailTokenNotFound", err) + } + + consumed, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + if _, err := tokens.Consume(ctx, consumed.Hash(), purpose, fixture.now); err != nil { + t.Fatalf("Consume() error = %v", err) + } + // A consumed token stays consumed after its deadline. + assertConsumeError(ctx, t, tokens, consumed, fixture.now.Add(2*tokenLifetime), outbound.ErrEmailTokenConsumed) + + first, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + second, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + otherToken, _ := fixture.issueToken(t, other, fixture.now, tokenLifetime) + // The two active tokens and the expired, unmarked ones are invalidated; + // the consumed token and the other user's token are not. + invalidated, err := tokens.InvalidateActive(ctx, user.ID, purpose, fixture.now) + if err != nil { + t.Fatalf("InvalidateActive() error = %v", err) + } + if invalidated != 4 { + t.Fatalf("InvalidateActive() = %d, want 4", invalidated) + } + assertConsumeError(ctx, t, tokens, first, fixture.now, outbound.ErrEmailTokenInvalidated) + assertConsumeError(ctx, t, tokens, second, fixture.now, outbound.ErrEmailTokenInvalidated) + assertConsumeError(ctx, t, tokens, consumed, fixture.now, outbound.ErrEmailTokenConsumed) + if again, err := tokens.InvalidateActive(ctx, user.ID, purpose, fixture.now); err != nil || again != 0 { + t.Fatalf("second InvalidateActive() = %d, %v, want 0", again, err) + } + // A token issued after the invalidation works. + fresh, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + if _, err := tokens.Consume(ctx, fresh.Hash(), purpose, fixture.now); err != nil { + t.Fatalf("Consume(fresh) error = %v", err) + } + if _, err := tokens.Consume(ctx, otherToken.Hash(), purpose, fixture.now); err != nil { + t.Fatalf("Consume(other user's token) error = %v", err) + } + + // A token bound to an earlier registration version never confirms the + // newer registration, even when nobody invalidated it. + superseded, _ := fixture.issueToken(t, other, fixture.now, tokenLifetime) + reRegistered, err := other.ReRegister(fixture.registration(t, "other@example.com", domain.ScenarioCandidate, fixture.now)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + if _, err := fixture.store.Users().UpdateRegistration(ctx, reRegistered); err != nil { + t.Fatalf("UpdateRegistration() error = %v", err) + } + assertConsumeError(ctx, t, tokens, superseded, fixture.now, outbound.ErrEmailTokenInvalidated) + }) + + t.Run("tokens and sessions for a missing account report ErrUserNotFound", func(t *testing.T) { + reset(t) + missing := uuid.New() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: missing, Purpose: domain.EmailTokenPurposeEmailVerification, TokenHash: raw.Hash(), + RegistrationVersion: 1, IssuedAt: fixture.now, Lifetime: tokenLifetime, + }) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + if err := fixture.store.EmailTokens().Insert(ctx, token); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("Insert(missing user) error = %v, want ErrUserNotFound", err) + } + session, err := domain.NewSession(domain.NewSessionInput{ + UserID: missing, TokenHash: raw.Hash(), StartedAt: fixture.now, AbsoluteLifetime: sessionLifetime, + }) + if err != nil { + t.Fatalf("NewSession() error = %v", err) + } + if err := fixture.store.Sessions().Create(ctx, session); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("Create(missing user) error = %v, want ErrUserNotFound", err) + } + }) + + t.Run("duplicate token hashes are rejected", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "duplicate@example.com", domain.ScenarioCandidate, fixture.now) + _, first := fixture.issueToken(t, user, fixture.now, tokenLifetime) + second := first + second.ID = uuid.New() + if err := fixture.store.EmailTokens().Insert(ctx, second); !errors.Is(err, outbound.ErrTokenHashConflict) { + t.Fatalf("Insert(duplicate hash) error = %v, want ErrTokenHashConflict", err) + } + _, session := fixture.startSession(t, user, fixture.now) + duplicateSession := session + duplicateSession.ID = uuid.New() + if err := fixture.store.Sessions().Create(ctx, duplicateSession); !errors.Is(err, outbound.ErrTokenHashConflict) { + t.Fatalf("Create(duplicate session hash) error = %v, want ErrTokenHashConflict", err) + } + }) + + t.Run("sessions are found while active and stop at idle, absolute, and revocation limits", func(t *testing.T) { + reset(t) + sessions := fixture.store.Sessions() + user := fixture.createUser(t, "session@example.com", domain.ScenarioCandidate, fixture.now) + raw, session := fixture.startSession(t, user, fixture.now) + + found, err := sessions.FindActive(ctx, raw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout) + if err != nil { + t.Fatalf("FindActive() error = %v", err) + } + assertSameSession(t, found, session) + + touchedAt := fixture.now.Add(23 * time.Hour) + if err := sessions.Touch(ctx, session.ID, touchedAt, sessionIdleTimeout); err != nil { + t.Fatalf("Touch() error = %v", err) + } + // An older activity time does not move last_seen_at back. + if err := sessions.Touch(ctx, session.ID, fixture.now.Add(time.Hour), sessionIdleTimeout); err != nil { + t.Fatalf("Touch(older) error = %v", err) + } + found, err = sessions.FindActive(ctx, raw.Hash(), touchedAt.Add(sessionIdleTimeout-time.Second), sessionIdleTimeout) + if err != nil { + t.Fatalf("FindActive(before idle deadline) error = %v", err) + } + if !found.LastSeenAt.Equal(touchedAt) { + t.Fatalf("LastSeenAt = %v, want %v", found.LastSeenAt, touchedAt) + } + idleAt := touchedAt.Add(sessionIdleTimeout) + if _, err := sessions.FindActive(ctx, raw.Hash(), idleAt, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(idle) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Touch(ctx, session.ID, idleAt, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(idle) error = %v, want ErrSessionNotFound", err) + } + + // Activity never extends the absolute deadline. + if _, err := sessions.FindActive(ctx, raw.Hash(), session.ExpiresAt, sessionLifetime); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(at absolute deadline) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Touch(ctx, session.ID, session.ExpiresAt, sessionLifetime); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(at absolute deadline) error = %v, want ErrSessionNotFound", err) + } + + unknown, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + if _, err := sessions.FindActive(ctx, unknown.Hash(), fixture.now, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(unknown) error = %v, want ErrSessionNotFound", err) + } + + revokedRaw, revokedSession := fixture.startSession(t, user, fixture.now) + if err := sessions.Revoke(ctx, revokedSession.ID, fixture.now.Add(time.Minute)); err != nil { + t.Fatalf("Revoke() error = %v", err) + } + if _, err := sessions.FindActive(ctx, revokedRaw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(revoked) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Touch(ctx, revokedSession.ID, fixture.now.Add(time.Minute), sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(revoked) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Revoke(ctx, revokedSession.ID, fixture.now.Add(time.Minute)); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("second Revoke() error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Revoke(ctx, uuid.New(), fixture.now); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Revoke(unknown) error = %v, want ErrSessionNotFound", err) + } + }) + + t.Run("revoking all of a user's sessions leaves other users signed in", func(t *testing.T) { + reset(t) + sessions := fixture.store.Sessions() + user := fixture.createUser(t, "everywhere@example.com", domain.ScenarioCandidate, fixture.now) + other := fixture.createUser(t, "bystander@example.com", domain.ScenarioEmployer, fixture.now) + userTokens := make([]domain.SecretToken, 0, signedInSessions) + for range signedInSessions { + raw, _ := fixture.startSession(t, user, fixture.now) + userTokens = append(userTokens, raw) + } + _, alreadyRevoked := fixture.startSession(t, user, fixture.now) + if err := sessions.Revoke(ctx, alreadyRevoked.ID, fixture.now); err != nil { + t.Fatalf("Revoke() error = %v", err) + } + otherRaw, _ := fixture.startSession(t, other, fixture.now) + + revoked, err := sessions.RevokeAllForUser(ctx, user.ID, fixture.now.Add(time.Minute)) + if err != nil { + t.Fatalf("RevokeAllForUser() error = %v", err) + } + if revoked != int64(len(userTokens)) { + t.Fatalf("RevokeAllForUser() = %d, want %d", revoked, len(userTokens)) + } + for _, raw := range userTokens { + if _, err := sessions.FindActive(ctx, raw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(revoked by RevokeAllForUser) error = %v, want ErrSessionNotFound", err) + } + } + if _, err := sessions.FindActive(ctx, otherRaw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout); err != nil { + t.Fatalf("FindActive(other user) error = %v", err) + } + }) + + t.Run("cleanup deletes stale unverified accounts in batches with their tokens and sessions", func(t *testing.T) { + reset(t) + users := fixture.store.Users() + cutoff := fixture.now.Add(-7 * 24 * time.Hour) + stale := make([]domain.User, 0, staleAccounts) + for index := range staleAccounts { + registeredAt := cutoff.Add(-time.Duration(staleAccounts-index) * time.Hour) + user := fixture.createUser(t, fmt.Sprintf("stale%d@example.com", index), domain.ScenarioCandidate, registeredAt) + fixture.issueToken(t, user, registeredAt, tokenLifetime) + fixture.startSession(t, user, registeredAt) + stale = append(stale, user) + } + recent := fixture.createUser(t, "recent@example.com", domain.ScenarioCandidate, cutoff.Add(time.Hour)) + verified := fixture.createUser(t, "verified@example.com", domain.ScenarioCandidate, cutoff.Add(-24*time.Hour)) + if _, err := users.MarkEmailVerified(ctx, verified.ID, verified.RegistrationVersion, cutoff.Add(-23*time.Hour)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + fixture.startSession(t, verified, fixture.now) + + deleted, err := users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, cleanupBatch) + if err != nil || deleted != cleanupBatch { + t.Fatalf("first DeleteUnverifiedRegisteredBefore() = %d, %v, want 2", deleted, err) + } + // The oldest go first. + for _, user := range stale[:cleanupBatch] { + if _, err := users.GetByID(ctx, user.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(deleted) error = %v, want ErrUserNotFound", err) + } + } + deleted, err = users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, cleanupBatch) + if err != nil || deleted != staleAccounts-cleanupBatch { + t.Fatalf("second DeleteUnverifiedRegisteredBefore() = %d, %v, want 1", deleted, err) + } + for _, kept := range []domain.User{recent, verified} { + if _, err := users.GetByID(ctx, kept.ID); err != nil { + t.Fatalf("GetByID(kept) error = %v", err) + } + } + assertRowCount(ctx, t, pool, usersTable, 2) + assertRowCount(ctx, t, pool, emailTokensTable, 0) + assertRowCount(ctx, t, pool, sessionsTable, 1) + }) + + t.Run("deleting an account cascades to its tokens and sessions", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "cascade@example.com", domain.ScenarioCandidate, fixture.now) + other := fixture.createUser(t, "survivor@example.com", domain.ScenarioCandidate, fixture.now) + for _, owner := range []domain.User{user, other} { + fixture.issueToken(t, owner, fixture.now, tokenLifetime) + fixture.startSession(t, owner, fixture.now) + } + if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, user.ID); err != nil { + t.Fatalf("delete user: %v", err) + } + assertRowCount(ctx, t, pool, emailTokensTable, 1) + assertRowCount(ctx, t, pool, sessionsTable, 1) + var orphans int + err := pool.QueryRow(ctx, ` + SELECT (SELECT count(*) FROM email_tokens WHERE user_id = $1) + + (SELECT count(*) FROM sessions WHERE user_id = $1)`, user.ID).Scan(&orphans) + if err != nil || orphans != 0 { + t.Fatalf("rows of the deleted user = %d, %v, want 0", orphans, err) + } + }) + + t.Run("repositories commit and roll back with the surrounding transaction", func(t *testing.T) { + reset(t) + writeAll := func(user domain.User) func(context.Context, outbound.UnitOfWork) error { + return func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Users().Create(ctx, user); err != nil { + return err + } + _, token := fixture.newToken(t, user, fixture.now, tokenLifetime) + if err := unit.EmailTokens().Insert(ctx, token); err != nil { + return err + } + _, session := fixture.newSession(t, user, fixture.now) + if err := unit.Sessions().Create(ctx, session); err != nil { + return err + } + // Reads inside the transaction see its own writes. + if _, err := unit.Users().GetByID(ctx, user.ID); err != nil { + return err + } + return nil + } + } + + rolledBack := fixture.newUser(t, "rollback@example.com", domain.ScenarioCandidate, fixture.now) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := writeAll(rolledBack)(ctx, unit); err != nil { + return err + } + return errForcedRollback + }) + if !errors.Is(err, errForcedRollback) { + t.Fatalf("WithinTransaction() error = %v, want the callback error", err) + } + for _, table := range identityTables { + assertRowCount(ctx, t, pool, table, 0) + } + + committed := fixture.newUser(t, "commit@example.com", domain.ScenarioCandidate, fixture.now) + if err := transactor.WithinTransaction(ctx, writeAll(committed)); err != nil { + t.Fatalf("WithinTransaction() error = %v", err) + } + for _, table := range identityTables { + assertRowCount(ctx, t, pool, table, 1) + } + + // A failed statement aborts the transaction: the duplicate email rolls + // back the account written before it. + first := fixture.newUser(t, "first@example.com", domain.ScenarioCandidate, fixture.now) + duplicate := fixture.newUser(t, "COMMIT@example.com", domain.ScenarioCandidate, fixture.now) + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Users().Create(ctx, first); err != nil { + return err + } + return unit.Users().Create(ctx, duplicate) + }) + if !errors.Is(err, outbound.ErrEmailTaken) { + t.Fatalf("WithinTransaction(duplicate) error = %v, want ErrEmailTaken", err) + } + if _, err := fixture.store.Users().GetByID(ctx, first.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(rolled back) error = %v, want ErrUserNotFound", err) + } + assertNoBusyConnections(t, pool) + }) + + t.Run("touch writes at most once per interval and reports inactive sessions", func(t *testing.T) { + reset(t) + sessions := fixture.store.Sessions() + user := fixture.createUser(t, "throttle@example.com", domain.ScenarioCandidate, fixture.now) + raw, session := fixture.startSession(t, user, fixture.now) + lastSeen := func(at time.Time) time.Time { + t.Helper() + found, err := sessions.FindActive(ctx, raw.Hash(), at, sessionIdleTimeout) + if err != nil { + t.Fatalf("FindActive() error = %v", err) + } + return found.LastSeenAt + } + soon := fixture.now.Add(30 * time.Second) + if err := sessions.Touch(ctx, session.ID, soon, sessionIdleTimeout); err != nil { + t.Fatalf("Touch(within interval) error = %v", err) + } + if got := lastSeen(soon); !got.Equal(fixture.now) { + t.Fatalf("LastSeenAt after a touch within the interval = %v, want the unchanged %v", got, fixture.now) + } + later := fixture.now.Add(2 * time.Minute) + if err := sessions.Touch(ctx, session.ID, later, sessionIdleTimeout); err != nil { + t.Fatalf("Touch(after interval) error = %v", err) + } + if got := lastSeen(later); !got.Equal(later) { + t.Fatalf("LastSeenAt after a touch past the interval = %v, want %v", got, later) + } + if err := sessions.Touch(ctx, uuid.New(), later, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(unknown) error = %v, want ErrSessionNotFound", err) + } + }) + + t.Run("a waiting consume fails after the holder commits and succeeds after it rolls back", func(t *testing.T) { + for _, variant := range []struct { + name string + commitFirst bool + wantSecond error + }{ + {name: "commit", commitFirst: true, wantSecond: outbound.ErrEmailTokenConsumed}, + {name: "rollback", commitFirst: false, wantSecond: nil}, + } { + t.Run(variant.name, func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "lockwait@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + applicationName := "identity_consume_waiter_" + variant.name + holder := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, fixture.now) + return err + }, variant.commitFirst) + holder.awaitHeld(ctx, t) + + var waiterErr error + waiterDone := make(chan struct{}) + go func() { + defer close(waiterDone) + waiterErr = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + // Label the session so the test can observe its lock wait. + if _, err := integrationTx(t, unit).Exec(ctx, "SET LOCAL application_name = '"+applicationName+"'"); err != nil { + return fmt.Errorf("label waiter: %w", err) + } + _, err := unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, fixture.now) + return err + }) + }() + waitEvent, observed := waitForLockWait(ctx, pool, applicationName) + holderErr := holder.finish() + <-waiterDone + if !observed { + t.Fatalf("the second consume was not observed waiting on a lock (last wait event %q)", waitEvent) + } + t.Logf("observed the second consume waiting on a lock: wait_event=%s", waitEvent) + if variant.commitFirst && holderErr != nil { + t.Fatalf("holder error = %v, want a commit", holderErr) + } + if !variant.commitFirst && !errors.Is(holderErr, errForcedRollback) { + t.Fatalf("holder error = %v, want the forced rollback", holderErr) + } + if (variant.wantSecond == nil && waiterErr != nil) || !errors.Is(waiterErr, variant.wantSecond) { + t.Fatalf("second consume error = %v, want %v", waiterErr, variant.wantSecond) + } + var consumed int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM email_tokens WHERE consumed_at IS NOT NULL`).Scan(&consumed); err != nil || consumed != 1 { + t.Fatalf("consumed tokens = %d, %v, want exactly 1", consumed, err) + } + }) + } + }) + + t.Run("a token issued before a concurrent re-registration cannot verify the new credentials", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "race@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + at := fixture.now.Add(time.Minute) + + // The confirmation consumes the token, holds its transaction open, and + // verifies the account with the token's registration version on finish. + var token domain.EmailToken + confirmation := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + token, err = unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, at) + return err + }, true) + confirmation.afterRelease = func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.Users().MarkEmailVerified(ctx, token.UserID, token.RegistrationVersion, at) + return err + } + confirmation.awaitHeld(ctx, t) + + // The re-registration commits between Consume and MarkEmailVerified. It + // skips InvalidateActive on purpose, so only the version check in + // MarkEmailVerified stands between the old token and the new password. + reRegistered, err := user.ReRegister(fixture.registration(t, "race@example.com", domain.ScenarioEmployer, at)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + stored, err := fixture.store.Users().UpdateRegistration(ctx, reRegistered) + if err != nil { + t.Fatalf("UpdateRegistration() error = %v", err) + } + if err := confirmation.finish(); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("confirmation error = %v, want ErrUserVersionConflict", err) + } + current, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + if current.EmailVerified() || current.RegistrationVersion != stored.RegistrationVersion || current.Scenario != domain.ScenarioEmployer { + t.Fatalf("account after the race = %+v, want the unverified re-registration", current) + } + // The rollback restored the token, which is now superseded. + assertConsumeError(ctx, t, fixture.store.EmailTokens(), raw, at, outbound.ErrEmailTokenInvalidated) + }) + + t.Run("cleanup skips accounts locked by open transactions without waiting", func(t *testing.T) { + reset(t) + cutoff := fixture.now.Add(-7 * 24 * time.Hour) + registeredAt := cutoff.Add(-time.Hour) + reRegistering := fixture.createUser(t, "reregistering@example.com", domain.ScenarioCandidate, registeredAt) + confirming := fixture.createUser(t, "confirming@example.com", domain.ScenarioCandidate, registeredAt) + idle := fixture.createUser(t, "idle@example.com", domain.ScenarioCandidate, registeredAt) + confirmingToken, _ := fixture.issueToken(t, confirming, registeredAt, tokenLifetime) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + + // One transaction holds the account row, the other only a token row. + changed, err := reRegistering.ReRegister(fixture.registration(t, "reregistering@example.com", domain.ScenarioEmployer, fixture.now)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + accountHolder := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.Users().UpdateRegistration(ctx, changed) + return err + }, false) + accountHolder.awaitHeld(ctx, t) + tokenHolder := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.EmailTokens().Consume(ctx, confirmingToken.Hash(), domain.EmailTokenPurposeEmailVerification, registeredAt.Add(time.Minute)) + return err + }, false) + tokenHolder.awaitHeld(ctx, t) + + // A lock wait longer than the timeout would fail the statement. + impatientPool := env.newPoolWithLockTimeout(ctx, t, cleanupLockTimeout) + var lockTimeout string + if err := impatientPool.QueryRow(ctx, "SHOW lock_timeout").Scan(&lockTimeout); err != nil || lockTimeout != fmt.Sprintf("%dms", cleanupLockTimeout.Milliseconds()) { + t.Fatalf("cleanup session lock_timeout = %q, %v, want %s", lockTimeout, err, cleanupLockTimeout) + } + impatientStore := postgresadapter.NewIdentityStore(impatientPool) + deleted, err := impatientStore.Users().DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil { + t.Fatalf("DeleteUnverifiedRegisteredBefore() with locked accounts error = %v", err) + } + if deleted != 1 { + t.Fatalf("DeleteUnverifiedRegisteredBefore() = %d, want only the unlocked account", deleted) + } + if _, err := fixture.store.Users().GetByID(ctx, idle.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(unlocked stale account) error = %v, want ErrUserNotFound", err) + } + if err := accountHolder.finish(); !errors.Is(err, errForcedRollback) { + t.Fatalf("account holder error = %v, want the forced rollback", err) + } + if err := tokenHolder.finish(); !errors.Is(err, errForcedRollback) { + t.Fatalf("token holder error = %v, want the forced rollback", err) + } + + // Once the locks are gone, the next run removes the skipped accounts. + deleted, err = impatientStore.Users().DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil || deleted != 2 { + t.Fatalf("second DeleteUnverifiedRegisteredBefore() = %d, %v, want 2", deleted, err) + } + for _, table := range identityTables { + assertRowCount(ctx, t, pool, table, 0) + } + }) + + t.Run("pool repositories refuse a transaction context", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "nested@example.com", domain.ScenarioCandidate, fixture.now) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, _ outbound.UnitOfWork) error { + _, err := fixture.store.Users().GetByID(ctx, user.ID) + return err + }) + if !errors.Is(err, outbound.ErrNestedTransaction) { + t.Fatalf("IdentityStore inside WithinTransaction error = %v, want ErrNestedTransaction", err) + } + }) + + t.Run("the transactor reports a deadlock as a retryable conflict", func(t *testing.T) { + reset(t) + first := fixture.createUser(t, "deadlock1@example.com", domain.ScenarioCandidate, fixture.now) + second := fixture.createUser(t, "deadlock2@example.com", domain.ScenarioCandidate, fixture.now) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + // Each transaction locks one account and then the other's. + crossLock := func(own, other uuid.UUID, locked chan<- struct{}, otherLocked <-chan struct{}) transactionFn { + return func(ctx context.Context, unit outbound.UnitOfWork) error { + update := `UPDATE users SET updated_at = updated_at WHERE id = $1` + if _, err := integrationTx(t, unit).Exec(ctx, update, own); err != nil { + return err + } + close(locked) + <-otherLocked + _, err := integrationTx(t, unit).Exec(ctx, update, other) + return err + } + } + firstLocked, secondLocked := make(chan struct{}), make(chan struct{}) + errs := make([]error, 2) + var group sync.WaitGroup + group.Go(func() { + errs[0] = concurrentTransactor.WithinTransaction(ctx, crossLock(first.ID, second.ID, firstLocked, secondLocked)) + }) + group.Go(func() { + errs[1] = concurrentTransactor.WithinTransaction(ctx, crossLock(second.ID, first.ID, secondLocked, firstLocked)) + }) + group.Wait() + conflicts := 0 + for index, err := range errs { + switch { + case err == nil: + case errors.Is(err, outbound.ErrTransactionConflict): + conflicts++ + default: + t.Fatalf("transaction %d error = %v, want nil or ErrTransactionConflict", index, err) + } + } + if conflicts != 1 { + t.Fatalf("%d transactions reported a conflict, want exactly 1: %v", conflicts, errs) + } + }) + + t.Run("database constraints back the domain rules", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "constraints@example.com", domain.ScenarioCandidate, fixture.now) + tests := []struct { + constraint string + statement string + args []any + }{ + { + constraint: "users_scenario_onboarding_step", + statement: `UPDATE users SET onboarding_step = 'employer_company' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_scenario_onboarding_step", + statement: `UPDATE users SET scenario = 'admin' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_password_hash_format", + statement: `UPDATE users SET password_hash = 'correct horse battery staple' WHERE id = $1`, + args: []any{user.ID}, + }, + { + // The key matches the address, so only the ASCII rule fails. + constraint: "users_email_ascii", + statement: "UPDATE users SET email = 'Jos\u00e9@example.com', email_normalized = 'jos\u00e9@example.com' WHERE id = $1", + args: []any{user.ID}, + }, + { + constraint: "users_email_normalized_rule", + statement: `UPDATE users SET email_normalized = 'CONSTRAINTS@example.com' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_timestamps_after_creation", + statement: `UPDATE users SET email_verified_at = created_at - interval '1 second' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "email_tokens_outcome_after_creation", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at, consumed_at) + VALUES ($1, $2, 'email_verification', $3, 1, $4, $5, $6)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour), fixture.now.Add(-time.Second)}, + }, + { + constraint: "sessions_revoked_after_creation", + statement: `INSERT INTO sessions (id, user_id, token_hash, created_at, last_seen_at, expires_at, revoked_at) + VALUES ($1, $2, $3, $4, $4, $5, $6)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour), fixture.now.Add(-time.Second)}, + }, + { + constraint: "email_tokens_token_hash_sha256", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at) + VALUES ($1, $2, 'email_verification', $3, 1, $4, $5)`, + args: []any{uuid.New(), user.ID, []byte("raw-token-is-not-a-digest"), fixture.now, fixture.now.Add(time.Hour)}, + }, + { + constraint: "email_tokens_purpose_known", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at) + VALUES ($1, $2, 'magic_link', $3, 1, $4, $5)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour)}, + }, + { + constraint: "email_tokens_single_outcome", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at, consumed_at, invalidated_at) + VALUES ($1, $2, 'email_verification', $3, 1, $4, $5, $4, $4)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour)}, + }, + { + constraint: "sessions_expiry_after_creation", + statement: `INSERT INTO sessions (id, user_id, token_hash, created_at, last_seen_at, expires_at) + VALUES ($1, $2, $3, $4, $4, $4)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now}, + }, + } + for _, test := range tests { + _, err := pool.Exec(ctx, test.statement, test.args...) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != checkViolationCode || pgError.ConstraintName != test.constraint { + t.Fatalf("statement violating %s error = %v, want a check violation", test.constraint, err) + } + } + }) +} + +func (fixture identityFixture) registration(t *testing.T, rawEmail string, scenario domain.Scenario, at time.Time) domain.Registration { + t.Helper() + passwordHash, err := domain.NewPasswordHash(identityTestPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + return domain.Registration{Email: mustEmail(t, rawEmail), PasswordHash: passwordHash, Scenario: scenario, RegisteredAt: at} +} + +func (fixture identityFixture) newUser(t *testing.T, rawEmail string, scenario domain.Scenario, at time.Time) domain.User { + t.Helper() + user, err := domain.NewUser(fixture.registration(t, rawEmail, scenario, at)) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + return user +} + +func (fixture identityFixture) createUser(t *testing.T, rawEmail string, scenario domain.Scenario, at time.Time) domain.User { + t.Helper() + user := fixture.newUser(t, rawEmail, scenario, at) + if err := fixture.store.Users().Create(fixture.ctx, user); err != nil { + t.Fatalf("Create(%s) error = %v", rawEmail, err) + } + return user +} + +func (fixture identityFixture) newToken(t *testing.T, user domain.User, at time.Time, lifetime time.Duration) (domain.SecretToken, domain.EmailToken) { + t.Helper() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: user.ID, Purpose: domain.EmailTokenPurposeEmailVerification, TokenHash: raw.Hash(), + RegistrationVersion: user.RegistrationVersion, IssuedAt: at, Lifetime: lifetime, + }) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + return raw, token +} + +func (fixture identityFixture) issueToken(t *testing.T, user domain.User, at time.Time, lifetime time.Duration) (domain.SecretToken, domain.EmailToken) { + t.Helper() + raw, token := fixture.newToken(t, user, at, lifetime) + if err := fixture.store.EmailTokens().Insert(fixture.ctx, token); err != nil { + t.Fatalf("Insert() error = %v", err) + } + return raw, token +} + +func (fixture identityFixture) newSession(t *testing.T, user domain.User, at time.Time) (domain.SecretToken, domain.Session) { + t.Helper() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + session, err := domain.NewSession(domain.NewSessionInput{ + UserID: user.ID, TokenHash: raw.Hash(), StartedAt: at, AbsoluteLifetime: sessionLifetime, + }) + if err != nil { + t.Fatalf("NewSession() error = %v", err) + } + return raw, session +} + +func (fixture identityFixture) startSession(t *testing.T, user domain.User, at time.Time) (domain.SecretToken, domain.Session) { + t.Helper() + raw, session := fixture.newSession(t, user, at) + if err := fixture.store.Sessions().Create(fixture.ctx, session); err != nil { + t.Fatalf("Create(session) error = %v", err) + } + return raw, session +} + +func mustEmail(t *testing.T, raw string) domain.EmailAddress { + t.Helper() + email, err := domain.NewEmailAddress(raw) + if err != nil { + t.Fatalf("NewEmailAddress(%q) error = %v", raw, err) + } + return email +} + +func assertConsumeError( + ctx context.Context, + t *testing.T, + tokens outbound.EmailTokenRepository, + raw domain.SecretToken, + at time.Time, + want error, +) { + t.Helper() + if _, err := tokens.Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, at); !errors.Is(err, want) { + t.Fatalf("Consume() error = %v, want %v", err, want) + } +} + +func assertSameUser(t *testing.T, got, want domain.User) { + t.Helper() + sameVerification := (got.EmailVerifiedAt == nil) == (want.EmailVerifiedAt == nil) && + (got.EmailVerifiedAt == nil || got.EmailVerifiedAt.Equal(*want.EmailVerifiedAt)) + if got.ID != want.ID || got.Email != want.Email || got.PasswordHash.PHC() != want.PasswordHash.PHC() || + got.Scenario != want.Scenario || got.OnboardingStep != want.OnboardingStep || !sameVerification || + got.RegistrationVersion != want.RegistrationVersion || !got.LastRegisteredAt.Equal(want.LastRegisteredAt) || + got.Version != want.Version || !got.CreatedAt.Equal(want.CreatedAt) || !got.UpdatedAt.Equal(want.UpdatedAt) { + t.Fatalf("user = %+v, want %+v", got, want) + } +} + +func assertSameSession(t *testing.T, got, want domain.Session) { + t.Helper() + if got.ID != want.ID || got.UserID != want.UserID || got.TokenHash != want.TokenHash || + !got.CreatedAt.Equal(want.CreatedAt) || !got.LastSeenAt.Equal(want.LastSeenAt) || + !got.ExpiresAt.Equal(want.ExpiresAt) || got.RevokedAt != nil { + t.Fatalf("session = %+v, want %+v", got, want) + } +} + +func assertRowCount(ctx context.Context, t *testing.T, pool *pgxpool.Pool, table pgx.Identifier, want int) { + t.Helper() + var count int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM "+table.Sanitize()).Scan(&count); err != nil { + t.Fatalf("count rows in %s: %v", table.Sanitize(), err) + } + if count != want { + t.Fatalf("%s has %d rows, want %d", table.Sanitize(), count, want) + } +} + +// heldTransaction runs work in a transaction and keeps the transaction open +// until finish, so a test can act while its locks are held. +type heldTransaction struct { + held chan struct{} + release chan struct{} + finished chan struct{} + once sync.Once + err error + // afterRelease, when set before awaitHeld returns, runs in the same + // transaction after finish releases it. + afterRelease transactionFn +} + +// startHeldTransaction runs work in a transaction and then holds it open. +// After finish, the transaction runs afterRelease and commits when commit is +// true, or rolls back with errForcedRollback otherwise. +func startHeldTransaction( + ctx context.Context, + t *testing.T, + transactor outbound.Transactor, + work transactionFn, + commit bool, +) *heldTransaction { + t.Helper() + holder := &heldTransaction{ + held: make(chan struct{}), + release: make(chan struct{}), + finished: make(chan struct{}), + } + t.Cleanup(func() { _ = holder.finish() }) + go func() { + defer close(holder.finished) + holder.err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := work(ctx, unit); err != nil { + return err + } + close(holder.held) + select { + case <-holder.release: + case <-ctx.Done(): + return ctx.Err() + } + if holder.afterRelease != nil { + if err := holder.afterRelease(ctx, unit); err != nil { + return err + } + } + if !commit { + return errForcedRollback + } + return nil + }) + }() + return holder +} + +func (holder *heldTransaction) awaitHeld(ctx context.Context, t *testing.T) { + t.Helper() + select { + case <-holder.held: + case <-holder.finished: + t.Fatalf("held transaction finished before holding its locks: %v", holder.err) + case <-ctx.Done(): + t.Fatalf("wait for the held transaction: %v", ctx.Err()) + } +} + +// finish releases the transaction and returns its result. +func (holder *heldTransaction) finish() error { + holder.once.Do(func() { close(holder.release) }) + <-holder.finished + return holder.err +} diff --git a/backend/integration_test/postgres_helpers_test.go b/backend/integration_test/postgres_helpers_test.go index bfb9970..d66dcec 100644 --- a/backend/integration_test/postgres_helpers_test.go +++ b/backend/integration_test/postgres_helpers_test.go @@ -7,8 +7,10 @@ import ( "crypto/rand" "io/fs" "net/url" + "strconv" "strings" "testing" + "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" @@ -95,6 +97,23 @@ func (env *testEnvironment) newPoolWithMaxConns(ctx context.Context, t *testing. return pool } +// newPoolWithLockTimeout opens a pool whose sessions fail a lock wait after +// timeout, so a test can prove that a statement never waits for a lock. +func (env *testEnvironment) newPoolWithLockTimeout(ctx context.Context, t *testing.T, timeout time.Duration) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + poolConfig.ConnConfig.RuntimeParams["lock_timeout"] = strconv.FormatInt(timeout.Milliseconds(), 10) + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create PostgreSQL pool with a lock timeout: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + // createIsolatedDatabase creates an empty database in the bootstrap container // for tests that must change the whole schema, and drops it with t. func (env *testEnvironment) createIsolatedDatabase(ctx context.Context, t *testing.T) string { diff --git a/backend/integration_test/postgres_migrations_test.go b/backend/integration_test/postgres_migrations_test.go index 137fef2..9e18b5d 100644 --- a/backend/integration_test/postgres_migrations_test.go +++ b/backend/integration_test/postgres_migrations_test.go @@ -19,6 +19,15 @@ const ( concurrentMigrators = 4 ) +// identityMigrationVersion creates identityTableNames. +const identityMigrationVersion = 2 + +var ( + // Tables created by 00001 and by 00002. + outboxTables = []string{"outbox_events"} + identityTableNames = []string{"users", "email_tokens", "sessions"} +) + func TestPostgresMigrations(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) @@ -41,10 +50,12 @@ func TestPostgresMigrations(t *testing.T) { if len(applied) != total { t.Fatalf("first Up() applied %d migrations, want %d", len(applied), total) } - assertOutboxTableExists(ctx, t, pool, true) + assertTablesExist(ctx, t, pool, true, outboxTables...) + assertTablesExist(ctx, t, pool, true, identityTableNames...) + identityRolledBack := false for rolledBack := 0; ; rolledBack++ { - _, err := migrator.DownOne(ctx) + result, err := migrator.DownOne(ctx) if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) { if rolledBack != total { t.Fatalf("rolled back %d migrations, want %d", rolledBack, total) @@ -54,8 +65,19 @@ func TestPostgresMigrations(t *testing.T) { if err != nil { t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err) } + if result.Version == identityMigrationVersion { + // The identity migration rolls back on its own and leaves the + // outbox migration before it. + assertTablesExist(ctx, t, pool, false, identityTableNames...) + assertTablesExist(ctx, t, pool, true, outboxTables...) + identityRolledBack = true + } } - assertOutboxTableExists(ctx, t, pool, false) + if !identityRolledBack { + t.Fatalf("migration %d was not rolled back", identityMigrationVersion) + } + assertTablesExist(ctx, t, pool, false, outboxTables...) + assertTablesExist(ctx, t, pool, false, identityTableNames...) var leftovers int err = pool.QueryRow(ctx, ` SELECT count(*) FROM pg_catalog.pg_class AS c @@ -75,7 +97,8 @@ func TestPostgresMigrations(t *testing.T) { if len(applied) != total { t.Fatalf("second Up() applied %d migrations, want %d", len(applied), total) } - assertOutboxTableExists(ctx, t, pool, true) + assertTablesExist(ctx, t, pool, true, outboxTables...) + assertTablesExist(ctx, t, pool, true, identityTableNames...) assertAllApplied(ctx, t, migrator, total) }) @@ -129,13 +152,15 @@ func assertAllApplied(ctx context.Context, t *testing.T, migrator *postgresadapt } } -func assertOutboxTableExists(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool) { +func assertTablesExist(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool, tables ...string) { t.Helper() - var exists bool - if err := pool.QueryRow(ctx, `SELECT to_regclass('public.outbox_events') IS NOT NULL`).Scan(&exists); err != nil { - t.Fatalf("check outbox table: %v", err) - } - if exists != want { - t.Fatalf("outbox_events exists = %t, want %t", exists, want) + for _, table := range tables { + var exists bool + if err := pool.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, "public."+table).Scan(&exists); err != nil { + t.Fatalf("check table %s: %v", table, err) + } + if exists != want { + t.Fatalf("%s exists = %t, want %t", table, exists, want) + } } } diff --git a/backend/internal/adapter/secondary/postgres/database_error.go b/backend/internal/adapter/secondary/postgres/database_error.go new file mode 100644 index 0000000..7fe352f --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/database_error.go @@ -0,0 +1,54 @@ +package postgres + +import ( + "errors" + "fmt" + + "lincodex/backend/internal/port/outbound" +) + +const ( + deadlockDetectedCode = "40P01" + serializationFailureCode = "40001" +) + +// databaseError keeps only the SQLSTATE and constraint name of a PostgreSQL +// error. The message and detail of a pgconn.PgError can quote row values, such +// as an email address or a password hash, so repositories that handle +// personal data return this type instead. +type databaseError struct { + code string + constraint string +} + +func (err *databaseError) Error() string { + if err.constraint == "" { + return "PostgreSQL error SQLSTATE " + err.code + } + return "PostgreSQL error SQLSTATE " + err.code + " on constraint " + err.constraint +} + +// SQLState matches the method of pgconn.PgError, so callers can read the code +// from either type. +func (err *databaseError) SQLState() string { return err.code } + +// sqlStateError is implemented by pgconn.PgError and databaseError. +type sqlStateError interface { + error + SQLState() string +} + +// markTransactionConflict makes a deadlock or serialization failure also +// match outbound.ErrTransactionConflict and returns other errors unchanged. +func markTransactionConflict(err error) error { + var stateError sqlStateError + if err == nil || errors.Is(err, outbound.ErrTransactionConflict) || !errors.As(err, &stateError) { + return err + } + switch code := stateError.SQLState(); code { + case deadlockDetectedCode, serializationFailureCode: + return fmt.Errorf("postgres.markTransactionConflict - SQLSTATE %s: %w: %w", code, outbound.ErrTransactionConflict, err) + default: + return err + } +} diff --git a/backend/internal/adapter/secondary/postgres/identity.go b/backend/internal/adapter/secondary/postgres/identity.go new file mode 100644 index 0000000..f2234a9 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/identity.go @@ -0,0 +1,566 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "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" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// PostgreSQL stores timestamps with microsecond precision, so a stored time +// is the written time truncated to microseconds. + +const ( + foreignKeyViolationCode = "23503" + + // sessionTouchInterval is the minimum age of last_seen_at before Touch + // writes it again. It bounds session writes to one per minute per session + // at the cost of ending an idle session up to a minute early. + sessionTouchInterval = time.Minute +) + +type constraintViolation struct { + code string + constraint string +} + +// identityConstraintErrors maps the identity constraints whose violation is a +// caller-visible outcome to port sentinels. Matching uses SQLSTATE and the +// constraint name from the migration, never the error text. +var identityConstraintErrors = map[constraintViolation]error{ + {uniqueViolationCode, "users_email_normalized_key"}: outbound.ErrEmailTaken, + {uniqueViolationCode, "email_tokens_token_hash_key"}: outbound.ErrTokenHashConflict, + {uniqueViolationCode, "sessions_token_hash_key"}: outbound.ErrTokenHashConflict, + {foreignKeyViolationCode, "email_tokens_user_id_fkey"}: outbound.ErrUserNotFound, + {foreignKeyViolationCode, "sessions_user_id_fkey"}: outbound.ErrUserNotFound, +} + +// mapIdentityError turns a known identity constraint violation into its port +// sentinel and keeps the constraint name. Any other PostgreSQL error is +// replaced by its SQLSTATE and constraint name, because its message and +// detail can quote row values such as an email address or a password hash. +// Deadlocks and serialization failures also match ErrTransactionConflict. +// Errors that do not come from PostgreSQL pass through. +func mapIdentityError(err error) error { + var pgError *pgconn.PgError + if !errors.As(err, &pgError) { + return err + } + if sentinel, ok := identityConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok { + return fmt.Errorf("postgres.mapIdentityError - violate constraint %s: %w", pgError.ConstraintName, sentinel) + } + return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}) +} + +// IdentityStore provides the identity repositories outside a transaction. +// Every call runs as its own statement on a pool connection. A call with a +// context that belongs to a Transactor callback fails with +// outbound.ErrNestedTransaction instead of committing independently of that +// transaction; use the UnitOfWork accessors there. +type IdentityStore struct { + queries *sqlc.Queries +} + +func NewIdentityStore(pool *pgxpool.Pool) *IdentityStore { + return &IdentityStore{queries: sqlc.New(standaloneDB{pool: pool})} +} + +var ( + _ outbound.IdentityRepositories = (*IdentityStore)(nil) + _ outbound.IdentityRepositories = (*UnitOfWork)(nil) +) + +func (store *IdentityStore) Users() outbound.UserRepository { + return userRepository{queries: store.queries} +} + +func (store *IdentityStore) EmailTokens() outbound.EmailTokenRepository { + return emailTokenRepository{queries: store.queries} +} + +func (store *IdentityStore) Sessions() outbound.SessionRepository { + return sessionRepository{queries: store.queries} +} + +func (unit *UnitOfWork) Users() outbound.UserRepository { + return userRepository{queries: unit.queries} +} + +func (unit *UnitOfWork) EmailTokens() outbound.EmailTokenRepository { + return emailTokenRepository{queries: unit.queries} +} + +func (unit *UnitOfWork) Sessions() outbound.SessionRepository { + return sessionRepository{queries: unit.queries} +} + +// standaloneDB runs statements on the pool and refuses a context that belongs +// to a Transactor callback, where a pool statement would silently bypass the +// surrounding transaction. +type standaloneDB struct { + pool *pgxpool.Pool +} + +func (db standaloneDB) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { + if err := refuseTransactionContext(ctx); err != nil { + return pgconn.CommandTag{}, err + } + return db.pool.Exec(ctx, sql, arguments...) +} + +func (db standaloneDB) Query(ctx context.Context, sql string, arguments ...any) (pgx.Rows, error) { + if err := refuseTransactionContext(ctx); err != nil { + return nil, err + } + return db.pool.Query(ctx, sql, arguments...) +} + +func (db standaloneDB) QueryRow(ctx context.Context, sql string, arguments ...any) pgx.Row { + if err := refuseTransactionContext(ctx); err != nil { + return errorRow{err: err} + } + return db.pool.QueryRow(ctx, sql, arguments...) +} + +func refuseTransactionContext(ctx context.Context) error { + if ctx.Value(transactionContextKey{}) != nil { + return fmt.Errorf("postgres.refuseTransactionContext - run a pool statement inside a transaction callback: %w", outbound.ErrNestedTransaction) + } + return nil +} + +// errorRow reports err from Scan, as pgx does for a failed QueryRow. +type errorRow struct { + err error +} + +func (row errorRow) Scan(...any) error { return row.err } + +// requireTime rejects the zero time, which would make every deadline check +// pass or fail silently. +func requireTime(location string, at time.Time, sentinel error) error { + if at.IsZero() { + return fmt.Errorf("%s - time must be set: %w", location, sentinel) + } + return nil +} + +type userRepository struct { + queries *sqlc.Queries +} + +func (repository userRepository) Create(ctx context.Context, user domain.User) error { + if user.ID == uuid.Nil || user.Email.IsZero() || user.PasswordHash.IsZero() { + return fmt.Errorf("userRepository.Create - user was not built by domain.NewUser: %w", domain.ErrInvalidUser) + } + err := repository.queries.InsertUser(ctx, sqlc.InsertUserParams{ + ID: pgUUID(user.ID), + Email: user.Email.Address(), + EmailNormalized: user.Email.Normalized(), + PasswordHash: user.PasswordHash.PHC(), + Scenario: string(user.Scenario), + OnboardingStep: string(user.OnboardingStep), + EmailVerifiedAt: pgOptionalTime(user.EmailVerifiedAt), + RegistrationVersion: user.RegistrationVersion, + LastRegisteredAt: pgTime(user.LastRegisteredAt), + Version: user.Version, + CreatedAt: pgTime(user.CreatedAt), + UpdatedAt: pgTime(user.UpdatedAt), + }) + if err != nil { + return fmt.Errorf("userRepository.Create - insert user: %w", mapIdentityError(err)) + } + return nil +} + +func (repository userRepository) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) { + row, err := repository.queries.GetUserByID(ctx, pgUUID(id)) + if err != nil { + return domain.User{}, fmt.Errorf("userRepository.GetByID - select user: %w", mapNoRows(err, outbound.ErrUserNotFound)) + } + return userFromRow(row) +} + +func (repository userRepository) GetByEmail(ctx context.Context, email domain.EmailAddress) (domain.User, error) { + row, err := repository.queries.GetUserByEmailNormalized(ctx, email.Normalized()) + if err != nil { + return domain.User{}, fmt.Errorf("userRepository.GetByEmail - select user: %w", mapNoRows(err, outbound.ErrUserNotFound)) + } + return userFromRow(row) +} + +func (repository userRepository) UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error) { + if err := requireTime("userRepository.UpdateRegistration", user.LastRegisteredAt, domain.ErrInvalidUser); err != nil { + return domain.User{}, err + } + row, err := repository.queries.UpdateUserRegistration(ctx, sqlc.UpdateUserRegistrationParams{ + ID: pgUUID(user.ID), + ExpectedVersion: user.Version, + Email: user.Email.Address(), + PasswordHash: user.PasswordHash.PHC(), + Scenario: string(user.Scenario), + OnboardingStep: string(user.OnboardingStep), + LastRegisteredAt: pgTime(user.LastRegisteredAt), + UpdatedAt: pgTime(user.UpdatedAt), + }) + if err != nil { + return domain.User{}, fmt.Errorf("userRepository.UpdateRegistration - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict)) + } + return userFromRow(row) +} + +func (repository userRepository) MarkEmailVerified( + ctx context.Context, + id uuid.UUID, + registrationVersion int64, + at time.Time, +) (domain.User, error) { + if err := requireTime("userRepository.MarkEmailVerified", at, domain.ErrInvalidUser); err != nil { + return domain.User{}, err + } + row, err := repository.queries.MarkUserEmailVerified(ctx, sqlc.MarkUserEmailVerifiedParams{ + ID: pgUUID(id), + RegistrationVersion: registrationVersion, + VerifiedAt: pgTime(at), + }) + if err != nil { + return domain.User{}, fmt.Errorf("userRepository.MarkEmailVerified - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict)) + } + return userFromRow(row) +} + +func (repository userRepository) DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error) { + if err := requireTime("userRepository.DeleteUnverifiedRegisteredBefore", cutoff, domain.ErrInvalidUser); err != nil { + return 0, err + } + if limit <= 0 { + return 0, errors.New("userRepository.DeleteUnverifiedRegisteredBefore - limit must be positive") + } + deleted, err := repository.queries.DeleteUnverifiedUsersRegisteredBefore(ctx, sqlc.DeleteUnverifiedUsersRegisteredBeforeParams{ + Cutoff: pgTime(cutoff), + BatchLimit: limit, + }) + if err != nil { + return 0, fmt.Errorf("userRepository.DeleteUnverifiedRegisteredBefore - delete users: %w", mapIdentityError(err)) + } + return deleted, nil +} + +func userFromRow(row sqlc.User) (domain.User, error) { + email, err := domain.RestoreEmailAddress(row.Email, row.EmailNormalized) + if err != nil { + return domain.User{}, fmt.Errorf("postgres.userFromRow - decode email: %w", err) + } + passwordHash, err := domain.NewPasswordHash(row.PasswordHash) + if err != nil { + return domain.User{}, fmt.Errorf("postgres.userFromRow - decode password hash: %w", err) + } + scenario, err := domain.ParseScenario(row.Scenario) + if err != nil { + return domain.User{}, fmt.Errorf("postgres.userFromRow - decode scenario: %w", err) + } + step, err := domain.ParseOnboardingStep(row.OnboardingStep) + if err != nil { + return domain.User{}, fmt.Errorf("postgres.userFromRow - decode onboarding step: %w", err) + } + return domain.User{ + ID: uuid.UUID(row.ID.Bytes), + Email: email, + PasswordHash: passwordHash, + Scenario: scenario, + OnboardingStep: step, + EmailVerifiedAt: optionalTime(row.EmailVerifiedAt), + RegistrationVersion: row.RegistrationVersion, + LastRegisteredAt: row.LastRegisteredAt.Time, + Version: row.Version, + CreatedAt: row.CreatedAt.Time, + UpdatedAt: row.UpdatedAt.Time, + }, nil +} + +type emailTokenRepository struct { + queries *sqlc.Queries +} + +func (repository emailTokenRepository) Insert(ctx context.Context, token domain.EmailToken) error { + if token.ID == uuid.Nil || token.TokenHash.IsZero() { + return fmt.Errorf("emailTokenRepository.Insert - token was not built by domain.NewEmailToken: %w", domain.ErrInvalidEmailToken) + } + err := repository.queries.InsertEmailToken(ctx, sqlc.InsertEmailTokenParams{ + ID: pgUUID(token.ID), + UserID: pgUUID(token.UserID), + Purpose: string(token.Purpose), + TokenHash: token.TokenHash[:], + RegistrationVersion: token.RegistrationVersion, + CreatedAt: pgTime(token.CreatedAt), + ExpiresAt: pgTime(token.ExpiresAt), + }) + if err != nil { + return fmt.Errorf("emailTokenRepository.Insert - insert email token: %w", mapIdentityError(err)) + } + return nil +} + +func (repository emailTokenRepository) InvalidateActive( + ctx context.Context, + userID uuid.UUID, + purpose domain.EmailTokenPurpose, + at time.Time, +) (int64, error) { + if err := requireTime("emailTokenRepository.InvalidateActive", at, domain.ErrInvalidEmailToken); err != nil { + return 0, err + } + invalidated, err := repository.queries.InvalidateActiveEmailTokens(ctx, sqlc.InvalidateActiveEmailTokensParams{ + UserID: pgUUID(userID), + Purpose: string(purpose), + InvalidatedAt: pgTime(at), + }) + if err != nil { + return 0, fmt.Errorf("emailTokenRepository.InvalidateActive - update email tokens: %w", mapIdentityError(err)) + } + return invalidated, nil +} + +func (repository emailTokenRepository) Consume( + ctx context.Context, + hash domain.SecretTokenHash, + purpose domain.EmailTokenPurpose, + at time.Time, +) (domain.EmailToken, error) { + if err := requireTime("emailTokenRepository.Consume", at, domain.ErrInvalidEmailToken); err != nil { + return domain.EmailToken{}, err + } + row, err := repository.queries.ConsumeEmailToken(ctx, sqlc.ConsumeEmailTokenParams{ + TokenHash: hash[:], + Purpose: string(purpose), + ConsumedAt: pgTime(at), + }) + if err == nil { + return emailTokenFromRow(row) + } + if !errors.Is(err, pgx.ErrNoRows) { + return domain.EmailToken{}, fmt.Errorf("emailTokenRepository.Consume - update email token: %w", mapIdentityError(err)) + } + if err := repository.explainUnconsumable(ctx, hash, purpose, at); err != nil { + return domain.EmailToken{}, fmt.Errorf("emailTokenRepository.Consume - consume email token: %w", err) + } + return domain.EmailToken{}, errors.New("emailTokenRepository.Consume - token became consumable after a failed attempt") +} + +// explainUnconsumable classifies a token that the atomic consume did not +// match. A nil result means the token is consumable again, which only a +// concurrent transaction that changed and then rolled back the row can cause. +func (repository emailTokenRepository) explainUnconsumable( + ctx context.Context, + hash domain.SecretTokenHash, + purpose domain.EmailTokenPurpose, + at time.Time, +) error { + state, err := repository.queries.GetEmailTokenState(ctx, sqlc.GetEmailTokenStateParams{ + TokenHash: hash[:], + Purpose: string(purpose), + }) + if err != nil { + return fmt.Errorf("emailTokenRepository.explainUnconsumable - select token state: %w", mapNoRows(err, outbound.ErrEmailTokenNotFound)) + } + switch { + case state.ConsumedAt.Valid: + return outbound.ErrEmailTokenConsumed + case state.InvalidatedAt.Valid || !state.CurrentRegistration: + return outbound.ErrEmailTokenInvalidated + case !state.ExpiresAt.Time.After(at): + return outbound.ErrEmailTokenExpired + default: + return nil + } +} + +func emailTokenFromRow(row sqlc.EmailToken) (domain.EmailToken, error) { + purpose, err := domain.ParseEmailTokenPurpose(row.Purpose) + if err != nil { + return domain.EmailToken{}, fmt.Errorf("postgres.emailTokenFromRow - decode purpose: %w", err) + } + hash, err := tokenHashFromBytes(row.TokenHash) + if err != nil { + return domain.EmailToken{}, err + } + return domain.EmailToken{ + ID: uuid.UUID(row.ID.Bytes), + UserID: uuid.UUID(row.UserID.Bytes), + Purpose: purpose, + TokenHash: hash, + RegistrationVersion: row.RegistrationVersion, + CreatedAt: row.CreatedAt.Time, + ExpiresAt: row.ExpiresAt.Time, + ConsumedAt: optionalTime(row.ConsumedAt), + InvalidatedAt: optionalTime(row.InvalidatedAt), + }, nil +} + +type sessionRepository struct { + queries *sqlc.Queries +} + +func (repository sessionRepository) Create(ctx context.Context, session domain.Session) error { + if session.ID == uuid.Nil || session.TokenHash.IsZero() { + return fmt.Errorf("sessionRepository.Create - session was not built by domain.NewSession: %w", domain.ErrInvalidSession) + } + err := repository.queries.InsertSession(ctx, sqlc.InsertSessionParams{ + ID: pgUUID(session.ID), + UserID: pgUUID(session.UserID), + TokenHash: session.TokenHash[:], + CreatedAt: pgTime(session.CreatedAt), + LastSeenAt: pgTime(session.LastSeenAt), + ExpiresAt: pgTime(session.ExpiresAt), + }) + if err != nil { + return fmt.Errorf("sessionRepository.Create - insert session: %w", mapIdentityError(err)) + } + return nil +} + +func (repository sessionRepository) FindActive( + ctx context.Context, + hash domain.SecretTokenHash, + at time.Time, + idleTimeout time.Duration, +) (domain.Session, error) { + if err := validateSessionCheck("sessionRepository.FindActive", at, idleTimeout); err != nil { + return domain.Session{}, err + } + row, err := repository.queries.GetActiveSessionByTokenHash(ctx, sqlc.GetActiveSessionByTokenHashParams{ + TokenHash: hash[:], + At: pgTime(at), + IdleCutoff: pgTime(at.Add(-idleTimeout)), + }) + if err != nil { + return domain.Session{}, fmt.Errorf("sessionRepository.FindActive - select session: %w", mapNoRows(err, outbound.ErrSessionNotFound)) + } + return sessionFromRow(row) +} + +func (repository sessionRepository) Touch(ctx context.Context, id uuid.UUID, at time.Time, idleTimeout time.Duration) error { + if err := validateSessionCheck("sessionRepository.Touch", at, idleTimeout); err != nil { + return err + } + result, err := repository.queries.TouchSession(ctx, sqlc.TouchSessionParams{ + ID: pgUUID(id), + At: pgTime(at), + IdleCutoff: pgTime(at.Add(-idleTimeout)), + TouchCutoff: pgTime(at.Add(-sessionTouchInterval)), + }) + if err != nil { + return fmt.Errorf("sessionRepository.Touch - update session: %w", mapIdentityError(err)) + } + if !result.Active { + return fmt.Errorf("sessionRepository.Touch - update session: %w", outbound.ErrSessionNotFound) + } + return nil +} + +func validateSessionCheck(location string, at time.Time, idleTimeout time.Duration) error { + if err := requireTime(location, at, domain.ErrInvalidSession); err != nil { + return err + } + if idleTimeout <= 0 { + return fmt.Errorf("%s - idle timeout must be positive: %w", location, domain.ErrInvalidSession) + } + return nil +} + +func (repository sessionRepository) Revoke(ctx context.Context, id uuid.UUID, at time.Time) error { + if err := requireTime("sessionRepository.Revoke", at, domain.ErrInvalidSession); err != nil { + return err + } + revoked, err := repository.queries.RevokeSession(ctx, sqlc.RevokeSessionParams{ + ID: pgUUID(id), + RevokedAt: pgTime(at), + }) + if err != nil { + return fmt.Errorf("sessionRepository.Revoke - update session: %w", mapIdentityError(err)) + } + if revoked == 0 { + return fmt.Errorf("sessionRepository.Revoke - update session: %w", outbound.ErrSessionNotFound) + } + return nil +} + +func (repository sessionRepository) RevokeAllForUser(ctx context.Context, userID uuid.UUID, at time.Time) (int64, error) { + if err := requireTime("sessionRepository.RevokeAllForUser", at, domain.ErrInvalidSession); err != nil { + return 0, err + } + revoked, err := repository.queries.RevokeUserSessions(ctx, sqlc.RevokeUserSessionsParams{ + UserID: pgUUID(userID), + RevokedAt: pgTime(at), + }) + if err != nil { + return 0, fmt.Errorf("sessionRepository.RevokeAllForUser - update sessions: %w", mapIdentityError(err)) + } + return revoked, nil +} + +func sessionFromRow(row sqlc.Session) (domain.Session, error) { + hash, err := tokenHashFromBytes(row.TokenHash) + if err != nil { + return domain.Session{}, err + } + return domain.Session{ + ID: uuid.UUID(row.ID.Bytes), + UserID: uuid.UUID(row.UserID.Bytes), + TokenHash: hash, + CreatedAt: row.CreatedAt.Time, + LastSeenAt: row.LastSeenAt.Time, + ExpiresAt: row.ExpiresAt.Time, + RevokedAt: optionalTime(row.RevokedAt), + }, nil +} + +func tokenHashFromBytes(stored []byte) (domain.SecretTokenHash, error) { + var hash domain.SecretTokenHash + if len(stored) != len(hash) { + return hash, errors.New("postgres.tokenHashFromBytes - stored token hash is not a SHA-256 digest") + } + copy(hash[:], stored) + return hash, nil +} + +// mapNoRows replaces pgx.ErrNoRows with the port sentinel for a missing or +// unmatched row and maps other errors with mapIdentityError. +func mapNoRows(err, sentinel error) error { + if errors.Is(err, pgx.ErrNoRows) { + return sentinel + } + return mapIdentityError(err) +} + +func pgUUID(id uuid.UUID) pgtype.UUID { + return pgtype.UUID{Bytes: id, Valid: true} +} + +func pgTime(value time.Time) pgtype.Timestamptz { + return pgtype.Timestamptz{Time: value, Valid: true} +} + +func pgOptionalTime(value *time.Time) pgtype.Timestamptz { + if value == nil { + return pgtype.Timestamptz{} + } + return pgTime(*value) +} + +func optionalTime(value pgtype.Timestamptz) *time.Time { + if !value.Valid { + return nil + } + return &value.Time +} diff --git a/backend/internal/adapter/secondary/postgres/identity_test.go b/backend/internal/adapter/secondary/postgres/identity_test.go new file mode 100644 index 0000000..3faa34f --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/identity_test.go @@ -0,0 +1,159 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestMapIdentityErrorRecognizesIdentityConstraints(t *testing.T) { + tests := []struct { + code string + constraint string + want error + }{ + {code: uniqueViolationCode, constraint: "users_email_normalized_key", want: outbound.ErrEmailTaken}, + {code: uniqueViolationCode, constraint: "email_tokens_token_hash_key", want: outbound.ErrTokenHashConflict}, + {code: uniqueViolationCode, constraint: "sessions_token_hash_key", want: outbound.ErrTokenHashConflict}, + {code: foreignKeyViolationCode, constraint: "email_tokens_user_id_fkey", want: outbound.ErrUserNotFound}, + {code: foreignKeyViolationCode, constraint: "sessions_user_id_fkey", want: outbound.ErrUserNotFound}, + } + for _, test := range tests { + err := mapIdentityError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: "Key (x)=(secret) already exists."}) + if !errors.Is(err, test.want) { + t.Fatalf("mapIdentityError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want) + } + if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "secret") { + t.Fatalf("mapIdentityError(%s) = %v, want the constraint name and no detail", test.constraint, err) + } + } +} + +func TestMapIdentityErrorDropsMessageAndDetailOfOtherPostgreSQLErrors(t *testing.T) { + original := fmt.Errorf("wrapped: %w", &pgconn.PgError{ + Code: "23514", + ConstraintName: "users_password_hash_format", + Message: `new row violates check constraint "users_password_hash_format" for value secret@example.com`, + Detail: "Failing row contains (secret@example.com, $argon2id$v=19$...).", + }) + err := mapIdentityError(original) + var pgError *pgconn.PgError + if errors.As(err, &pgError) { + t.Fatalf("mapIdentityError() kept the PgError: %v", err) + } + var stateError sqlStateError + if !errors.As(err, &stateError) || stateError.SQLState() != "23514" { + t.Fatalf("mapIdentityError() = %v, want SQLSTATE 23514", err) + } + if !strings.Contains(err.Error(), "users_password_hash_format") || + strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "argon2id") { + t.Fatalf("mapIdentityError() = %q, want only the code and constraint", err) + } +} + +func TestMapIdentityErrorKeepsNonPostgreSQLErrors(t *testing.T) { + for _, original := range []error{ + errors.New(`duplicate key value violates unique constraint "users_email_normalized_key"`), + pgx.ErrNoRows, + context.Canceled, + } { + if err := mapIdentityError(original); err != original { //nolint:errorlint // Identity is the property under test. + t.Fatalf("mapIdentityError(%v) = %v, want the original error", original, err) + } + } +} + +func TestMarkTransactionConflictClassifiesDeadlocksAndSerializationFailures(t *testing.T) { + for _, original := range []error{ + &pgconn.PgError{Code: deadlockDetectedCode}, + fmt.Errorf("statement: %w", &pgconn.PgError{Code: serializationFailureCode}), + &databaseError{code: deadlockDetectedCode}, + mapIdentityError(&pgconn.PgError{Code: serializationFailureCode}), + } { + err := markTransactionConflict(original) + if !errors.Is(err, outbound.ErrTransactionConflict) || !errors.Is(err, original) { + t.Fatalf("markTransactionConflict(%v) = %v, want ErrTransactionConflict wrapping the original", original, err) + } + if strings.Count(markTransactionConflict(err).Error(), "markTransactionConflict") != 1 { + t.Fatalf("markTransactionConflict() wrapped an already classified error again: %v", markTransactionConflict(err)) + } + } + for _, original := range []error{ + nil, + &pgconn.PgError{Code: uniqueViolationCode}, + &pgconn.PgError{Code: "55P03"}, + errors.New("connection reset"), + } { + if err := markTransactionConflict(original); err != original { //nolint:errorlint // Identity is the property under test. + t.Fatalf("markTransactionConflict(%v) = %v, want the original error", original, err) + } + } +} + +func TestIdentityStoreRefusesATransactionContext(t *testing.T) { + // A nil pool proves that the guard runs before any statement. + store := &IdentityStore{queries: sqlc.New(standaloneDB{})} + ctx := context.WithValue(t.Context(), transactionContextKey{}, true) + at := time.Now() + checks := map[string]error{ + "GetByID": errorOf(store.Users().GetByID(ctx, uuid.New())), + "DeleteUnverifiedRegisteredBefore": errorOf(store.Users().DeleteUnverifiedRegisteredBefore(ctx, at, 1)), + "Consume": errorOf(store.EmailTokens().Consume(ctx, domain.SecretTokenHash{1}, domain.EmailTokenPurposeEmailVerification, at)), + "InvalidateActive": errorOf(store.EmailTokens().InvalidateActive(ctx, uuid.New(), domain.EmailTokenPurposeEmailVerification, at)), + "Touch": store.Sessions().Touch(ctx, uuid.New(), at, time.Hour), + } + for name, err := range checks { + if !errors.Is(err, outbound.ErrNestedTransaction) { + t.Fatalf("%s() error = %v, want ErrNestedTransaction", name, err) + } + } +} + +// errorOf drops the value of a two-result call. +func errorOf[T any](_ T, err error) error { return err } + +func TestRepositoriesRejectInvalidInputBeforeTheDatabase(t *testing.T) { + // A nil query set proves that validation happens before any statement. + ctx := t.Context() + users, tokens, sessions := userRepository{}, emailTokenRepository{}, sessionRepository{} + now, id, hash := time.Now(), uuid.New(), domain.SecretTokenHash{1} + purpose := domain.EmailTokenPurposeEmailVerification + checks := []struct { + name string + err error + want error + }{ + {name: "Create(zero user)", err: users.Create(ctx, domain.User{}), want: domain.ErrInvalidUser}, + {name: "MarkEmailVerified(zero time)", err: errorOf(users.MarkEmailVerified(ctx, id, 1, time.Time{})), want: domain.ErrInvalidUser}, + {name: "DeleteUnverifiedRegisteredBefore(zero cutoff)", err: errorOf(users.DeleteUnverifiedRegisteredBefore(ctx, time.Time{}, 1)), want: domain.ErrInvalidUser}, + {name: "Insert(zero token)", err: tokens.Insert(ctx, domain.EmailToken{}), want: domain.ErrInvalidEmailToken}, + {name: "Consume(zero time)", err: errorOf(tokens.Consume(ctx, hash, purpose, time.Time{})), want: domain.ErrInvalidEmailToken}, + {name: "InvalidateActive(zero time)", err: errorOf(tokens.InvalidateActive(ctx, id, purpose, time.Time{})), want: domain.ErrInvalidEmailToken}, + {name: "Create(zero session)", err: sessions.Create(ctx, domain.Session{}), want: domain.ErrInvalidSession}, + {name: "FindActive(zero idle timeout)", err: errorOf(sessions.FindActive(ctx, hash, now, 0)), want: domain.ErrInvalidSession}, + {name: "FindActive(zero time)", err: errorOf(sessions.FindActive(ctx, hash, time.Time{}, time.Hour)), want: domain.ErrInvalidSession}, + {name: "Touch(negative idle timeout)", err: sessions.Touch(ctx, id, now, -time.Second), want: domain.ErrInvalidSession}, + {name: "Touch(zero time)", err: sessions.Touch(ctx, id, time.Time{}, time.Hour), want: domain.ErrInvalidSession}, + {name: "Revoke(zero time)", err: sessions.Revoke(ctx, id, time.Time{}), want: domain.ErrInvalidSession}, + {name: "RevokeAllForUser(zero time)", err: errorOf(sessions.RevokeAllForUser(ctx, id, time.Time{})), want: domain.ErrInvalidSession}, + } + for _, check := range checks { + if !errors.Is(check.err, check.want) { + t.Fatalf("%s error = %v, want %v", check.name, check.err, check.want) + } + } + if _, err := users.DeleteUnverifiedRegisteredBefore(ctx, now, 0); err == nil { + t.Fatal("DeleteUnverifiedRegisteredBefore(limit 0) error = nil, want an error") + } +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go new file mode 100644 index 0000000..efe2bd7 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go @@ -0,0 +1,689 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: identity.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const consumeEmailToken = `-- name: ConsumeEmailToken :one +UPDATE email_tokens AS token +SET consumed_at = $1 +FROM users AS owner +WHERE + token.token_hash = $2 + AND token.purpose = $3 + AND token.consumed_at IS NULL + AND token.invalidated_at IS NULL + AND token.expires_at > $1 + AND owner.id = token.user_id + AND owner.registration_version = token.registration_version +RETURNING + token.id, + token.user_id, + token.purpose, + token.token_hash, + token.registration_version, + token.created_at, + token.expires_at, + token.consumed_at, + token.invalidated_at +` + +type ConsumeEmailTokenParams struct { + ConsumedAt pgtype.Timestamptz + TokenHash []byte + Purpose string +} + +// Consumes a token in one statement. Concurrent callers queue on the token +// row lock; under READ COMMITTED each waiter re-checks the WHERE clause +// against the committed row, so exactly one of them updates it. The join +// compares the registration version with the account row as the statement +// reads it, without locking that row, so it rejects a token from an earlier +// registration that already committed but not one that commits afterwards. +// The confirmation guarantee therefore needs MarkUserEmailVerified with the +// returned registration version in the same transaction, rolled back when it +// matches no row. +func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error) { + row := q.db.QueryRow(ctx, consumeEmailToken, arg.ConsumedAt, arg.TokenHash, arg.Purpose) + var i EmailToken + err := row.Scan( + &i.ID, + &i.UserID, + &i.Purpose, + &i.TokenHash, + &i.RegistrationVersion, + &i.CreatedAt, + &i.ExpiresAt, + &i.ConsumedAt, + &i.InvalidatedAt, + ) + return i, err +} + +const deleteUnverifiedUsersRegisteredBefore = `-- name: DeleteUnverifiedUsersRegisteredBefore :execrows +WITH candidate AS ( + SELECT stale.id + FROM users AS stale + WHERE + stale.email_verified_at IS NULL + AND stale.last_registered_at < $1 + ORDER BY stale.last_registered_at + LIMIT $2 + FOR UPDATE SKIP LOCKED +), + +locked_token AS ( + SELECT token.user_id + FROM email_tokens AS token + WHERE token.user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +locked_session AS ( + SELECT session.user_id + FROM sessions AS session + WHERE session.user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +deletable AS ( + SELECT candidate.id + FROM candidate + WHERE + ( + SELECT count(*) FROM email_tokens AS token + WHERE token.user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_token + WHERE locked_token.user_id = candidate.id + ) + AND ( + SELECT count(*) FROM sessions AS session + WHERE session.user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_session + WHERE locked_session.user_id = candidate.id + ) +) + +DELETE FROM users +USING deletable +WHERE users.id = deletable.id +` + +type DeleteUnverifiedUsersRegisteredBeforeParams struct { + Cutoff pgtype.Timestamptz + BatchLimit int32 +} + +// Deletes one batch of accounts that stayed unverified since before cutoff, +// oldest first, with their tokens and sessions. Every lock is taken with SKIP +// LOCKED, so the statement never waits: an account whose row is locked, for +// example by a re-registration or a token insert, is skipped, and so is an +// account with any token or session row locked, for example by a +// confirmation that consumed a token. Skipped accounts stay for the next run. +// Taking the account lock before the token locks is the reverse of the +// documented order, which is safe only because no lock here waits. +// An account qualifies only when every token and session row visible to the +// statement was locked above. +func (q *Queries) DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) { + result, err := q.db.Exec(ctx, deleteUnverifiedUsersRegisteredBefore, arg.Cutoff, arg.BatchLimit) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getActiveSessionByTokenHash = `-- name: GetActiveSessionByTokenHash :one +SELECT + id, + user_id, + token_hash, + created_at, + last_seen_at, + expires_at, + revoked_at +FROM sessions +WHERE + token_hash = $1 + AND revoked_at IS NULL + AND expires_at > $2 + AND last_seen_at > $3 +` + +type GetActiveSessionByTokenHashParams struct { + TokenHash []byte + At pgtype.Timestamptz + IdleCutoff pgtype.Timestamptz +} + +func (q *Queries) GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) { + row := q.db.QueryRow(ctx, getActiveSessionByTokenHash, arg.TokenHash, arg.At, arg.IdleCutoff) + var i Session + err := row.Scan( + &i.ID, + &i.UserID, + &i.TokenHash, + &i.CreatedAt, + &i.LastSeenAt, + &i.ExpiresAt, + &i.RevokedAt, + ) + return i, err +} + +const getEmailTokenState = `-- name: GetEmailTokenState :one +SELECT + token.consumed_at, + token.invalidated_at, + token.expires_at, + owner.registration_version = token.registration_version AS current_registration +FROM email_tokens AS token +INNER JOIN users AS owner ON token.user_id = owner.id +WHERE + token.token_hash = $1 + AND token.purpose = $2 +` + +type GetEmailTokenStateParams struct { + TokenHash []byte + Purpose string +} + +type GetEmailTokenStateRow struct { + ConsumedAt pgtype.Timestamptz + InvalidatedAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz + CurrentRegistration bool +} + +// Explains why ConsumeEmailToken matched no row. +func (q *Queries) GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) { + row := q.db.QueryRow(ctx, getEmailTokenState, arg.TokenHash, arg.Purpose) + var i GetEmailTokenStateRow + err := row.Scan( + &i.ConsumedAt, + &i.InvalidatedAt, + &i.ExpiresAt, + &i.CurrentRegistration, + ) + return i, err +} + +const getUserByEmailNormalized = `-- name: GetUserByEmailNormalized :one +SELECT + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +FROM users +WHERE email_normalized = $1 +` + +func (q *Queries) GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error) { + row := q.db.QueryRow(ctx, getUserByEmailNormalized, emailNormalized) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.EmailNormalized, + &i.PasswordHash, + &i.Scenario, + &i.OnboardingStep, + &i.EmailVerifiedAt, + &i.RegistrationVersion, + &i.LastRegisteredAt, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const getUserByID = `-- name: GetUserByID :one +SELECT + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +FROM users +WHERE id = $1 +` + +func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) { + row := q.db.QueryRow(ctx, getUserByID, id) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.EmailNormalized, + &i.PasswordHash, + &i.Scenario, + &i.OnboardingStep, + &i.EmailVerifiedAt, + &i.RegistrationVersion, + &i.LastRegisteredAt, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const insertEmailToken = `-- name: InsertEmailToken :exec +INSERT INTO email_tokens ( + id, + user_id, + purpose, + token_hash, + registration_version, + created_at, + expires_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7 +) +` + +type InsertEmailTokenParams struct { + ID pgtype.UUID + UserID pgtype.UUID + Purpose string + TokenHash []byte + RegistrationVersion int64 + CreatedAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz +} + +func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error { + _, err := q.db.Exec(ctx, insertEmailToken, + arg.ID, + arg.UserID, + arg.Purpose, + arg.TokenHash, + arg.RegistrationVersion, + arg.CreatedAt, + arg.ExpiresAt, + ) + return err +} + +const insertSession = `-- name: InsertSession :exec +INSERT INTO sessions ( + id, + user_id, + token_hash, + created_at, + last_seen_at, + expires_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6 +) +` + +type InsertSessionParams struct { + ID pgtype.UUID + UserID pgtype.UUID + TokenHash []byte + CreatedAt pgtype.Timestamptz + LastSeenAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz +} + +func (q *Queries) InsertSession(ctx context.Context, arg InsertSessionParams) error { + _, err := q.db.Exec(ctx, insertSession, + arg.ID, + arg.UserID, + arg.TokenHash, + arg.CreatedAt, + arg.LastSeenAt, + arg.ExpiresAt, + ) + return err +} + +const insertUser = `-- name: InsertUser :exec +INSERT INTO users ( + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8, + $9, + $10, + $11, + $12 +) +` + +type InsertUserParams struct { + ID pgtype.UUID + Email string + EmailNormalized string + PasswordHash string + Scenario string + OnboardingStep string + EmailVerifiedAt pgtype.Timestamptz + RegistrationVersion int64 + LastRegisteredAt pgtype.Timestamptz + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + +func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) error { + _, err := q.db.Exec(ctx, insertUser, + arg.ID, + arg.Email, + arg.EmailNormalized, + arg.PasswordHash, + arg.Scenario, + arg.OnboardingStep, + arg.EmailVerifiedAt, + arg.RegistrationVersion, + arg.LastRegisteredAt, + arg.Version, + arg.CreatedAt, + arg.UpdatedAt, + ) + return err +} + +const invalidateActiveEmailTokens = `-- name: InvalidateActiveEmailTokens :execrows +UPDATE email_tokens +SET invalidated_at = $1 +WHERE + user_id = $2 + AND purpose = $3 + AND consumed_at IS NULL + AND invalidated_at IS NULL +` + +type InvalidateActiveEmailTokensParams struct { + InvalidatedAt pgtype.Timestamptz + UserID pgtype.UUID + Purpose string +} + +func (q *Queries) InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) { + result, err := q.db.Exec(ctx, invalidateActiveEmailTokens, arg.InvalidatedAt, arg.UserID, arg.Purpose) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const markUserEmailVerified = `-- name: MarkUserEmailVerified :one +UPDATE users +SET + email_verified_at = $1, + updated_at = $1, + version = version + 1 +WHERE + id = $2 + AND registration_version = $3 + AND email_verified_at IS NULL +RETURNING + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +` + +type MarkUserEmailVerifiedParams struct { + VerifiedAt pgtype.Timestamptz + ID pgtype.UUID + RegistrationVersion int64 +} + +// Verifies the email only for the registration version the consumed token +// was issued for. +func (q *Queries) MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error) { + row := q.db.QueryRow(ctx, markUserEmailVerified, arg.VerifiedAt, arg.ID, arg.RegistrationVersion) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.EmailNormalized, + &i.PasswordHash, + &i.Scenario, + &i.OnboardingStep, + &i.EmailVerifiedAt, + &i.RegistrationVersion, + &i.LastRegisteredAt, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const revokeSession = `-- name: RevokeSession :execrows +UPDATE sessions +SET revoked_at = $1 +WHERE + id = $2 + AND revoked_at IS NULL +` + +type RevokeSessionParams struct { + RevokedAt pgtype.Timestamptz + ID pgtype.UUID +} + +func (q *Queries) RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error) { + result, err := q.db.Exec(ctx, revokeSession, arg.RevokedAt, arg.ID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const revokeUserSessions = `-- name: RevokeUserSessions :execrows +UPDATE sessions +SET revoked_at = $1 +WHERE + user_id = $2 + AND revoked_at IS NULL +` + +type RevokeUserSessionsParams struct { + RevokedAt pgtype.Timestamptz + UserID pgtype.UUID +} + +func (q *Queries) RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error) { + result, err := q.db.Exec(ctx, revokeUserSessions, arg.RevokedAt, arg.UserID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const touchSession = `-- name: TouchSession :one +WITH active_session AS ( + SELECT candidate.id + FROM sessions AS candidate + WHERE + candidate.id = $1 + AND candidate.revoked_at IS NULL + AND candidate.expires_at > $2 + AND candidate.last_seen_at > $3 +), + +touched AS ( + UPDATE sessions + SET last_seen_at = $2 + WHERE + sessions.id = $1 + AND sessions.revoked_at IS NULL + AND sessions.expires_at > $2 + AND sessions.last_seen_at > $3 + AND sessions.last_seen_at < $4 + RETURNING sessions.id +) + +SELECT + exists(SELECT 1 FROM active_session) AS active, + exists(SELECT 1 FROM touched) AS touched +` + +type TouchSessionParams struct { + ID pgtype.UUID + At pgtype.Timestamptz + IdleCutoff pgtype.Timestamptz + TouchCutoff pgtype.Timestamptz +} + +type TouchSessionRow struct { + Active bool + Touched bool +} + +// Records activity on an active session and reports whether it is active. +// The row is written only when last_seen_at is older than touch_cutoff, so +// frequent requests do not rewrite it. last_seen_at never moves back, and a +// revoked, expired, or idle session is not revived; the update re-checks +// those conditions against a concurrent change. +func (q *Queries) TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error) { + row := q.db.QueryRow(ctx, touchSession, + arg.ID, + arg.At, + arg.IdleCutoff, + arg.TouchCutoff, + ) + var i TouchSessionRow + err := row.Scan(&i.Active, &i.Touched) + return i, err +} + +const updateUserRegistration = `-- name: UpdateUserRegistration :one +UPDATE users +SET + email = $1, + password_hash = $2, + scenario = $3, + onboarding_step = $4, + registration_version = registration_version + 1, + last_registered_at = $5, + updated_at = $6, + version = version + 1 +WHERE + id = $7 + AND version = $8 + AND email_verified_at IS NULL +RETURNING + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +` + +type UpdateUserRegistrationParams struct { + Email string + PasswordHash string + Scenario string + OnboardingStep string + LastRegisteredAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + ID pgtype.UUID + ExpectedVersion int64 +} + +// Replaces the registration of an unverified account and advances the +// registration version in the same statement, so no caller can choose it. +// The version check rejects a writer that read an older row; a verified +// account never changes. +func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error) { + row := q.db.QueryRow(ctx, updateUserRegistration, + arg.Email, + arg.PasswordHash, + arg.Scenario, + arg.OnboardingStep, + arg.LastRegisteredAt, + arg.UpdatedAt, + arg.ID, + arg.ExpectedVersion, + ) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.EmailNormalized, + &i.PasswordHash, + &i.Scenario, + &i.OnboardingStep, + &i.EmailVerifiedAt, + &i.RegistrationVersion, + &i.LastRegisteredAt, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 8c2fcaf..8c5461c 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -8,6 +8,18 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +type EmailToken struct { + ID pgtype.UUID + UserID pgtype.UUID + Purpose string + TokenHash []byte + RegistrationVersion int64 + CreatedAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz + ConsumedAt pgtype.Timestamptz + InvalidatedAt pgtype.Timestamptz +} + type OutboxEvent struct { Position pgtype.Int8 EventID pgtype.UUID @@ -20,3 +32,28 @@ type OutboxEvent struct { OccurredAt pgtype.Timestamptz PublishedAt pgtype.Timestamptz } + +type Session struct { + ID pgtype.UUID + UserID pgtype.UUID + TokenHash []byte + CreatedAt pgtype.Timestamptz + LastSeenAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz +} + +type User struct { + ID pgtype.UUID + Email string + EmailNormalized string + PasswordHash string + Scenario string + OnboardingStep string + EmailVerifiedAt pgtype.Timestamptz + RegistrationVersion int64 + LastRegisteredAt pgtype.Timestamptz + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index c508693..eef61c1 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -6,11 +6,59 @@ package sqlc import ( "context" + + "github.com/jackc/pgx/v5/pgtype" ) type Querier interface { + // Consumes a token in one statement. Concurrent callers queue on the token + // row lock; under READ COMMITTED each waiter re-checks the WHERE clause + // against the committed row, so exactly one of them updates it. The join + // compares the registration version with the account row as the statement + // reads it, without locking that row, so it rejects a token from an earlier + // registration that already committed but not one that commits afterwards. + // The confirmation guarantee therefore needs MarkUserEmailVerified with the + // returned registration version in the same transaction, rolled back when it + // matches no row. + ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error) + // Deletes one batch of accounts that stayed unverified since before cutoff, + // oldest first, with their tokens and sessions. Every lock is taken with SKIP + // LOCKED, so the statement never waits: an account whose row is locked, for + // example by a re-registration or a token insert, is skipped, and so is an + // account with any token or session row locked, for example by a + // confirmation that consumed a token. Skipped accounts stay for the next run. + // Taking the account lock before the token locks is the reverse of the + // documented order, which is safe only because no lock here waits. + // An account qualifies only when every token and session row visible to the + // statement was locked above. + DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) + GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) + // Explains why ConsumeEmailToken matched no row. + GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) + GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error) + GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) + InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error + InsertSession(ctx context.Context, arg InsertSessionParams) error + InsertUser(ctx context.Context, arg InsertUserParams) error + InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) + // Verifies the email only for the registration version the consumed token + // was issued for. + MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error) Ping(ctx context.Context) (int32, error) + RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error) + RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error) + // Records activity on an active session and reports whether it is active. + // The row is written only when last_seen_at is older than touch_cutoff, so + // frequent requests do not rewrite it. last_seen_at never moves back, and a + // revoked, expired, or idle session is not revived; the update re-checks + // those conditions against a concurrent change. + TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error) + // Replaces the registration of an unverified account and advances the + // registration version in the same statement, so no caller can choose it. + // The version check rejects a writer that read an older row; a verified + // account never changes. + UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error) } var _ Querier = (*Queries)(nil) diff --git a/backend/internal/adapter/secondary/postgres/transactor.go b/backend/internal/adapter/secondary/postgres/transactor.go index 6d215ff..942fb29 100644 --- a/backend/internal/adapter/secondary/postgres/transactor.go +++ b/backend/internal/adapter/secondary/postgres/transactor.go @@ -66,6 +66,7 @@ func (transactor *Transactor) WithinTransaction( fnErr := fn(context.WithValue(ctx, transactionContextKey{}, true), &UnitOfWork{tx: tx, queries: sqlc.New(tx)}) finished = true if fnErr != nil { + fnErr = markTransactionConflict(fnErr) if rollbackErr := rollback(ctx, tx); rollbackErr != nil { return errors.Join(fnErr, fmt.Errorf("Transactor.WithinTransaction - roll back transaction: %w", rollbackErr)) } @@ -75,7 +76,7 @@ func (transactor *Transactor) WithinTransaction( // pgx reports pgx.ErrTxCommitRollback when fn ignored a statement error // and PostgreSQL rolled the aborted transaction back instead. After a // network error the commit outcome is unknown; see outbound.Transactor. - return fmt.Errorf("Transactor.WithinTransaction - commit transaction: %w", err) + return fmt.Errorf("Transactor.WithinTransaction - commit transaction: %w", markTransactionConflict(err)) } return nil } diff --git a/backend/internal/domain/email_address.go b/backend/internal/domain/email_address.go new file mode 100644 index 0000000..1bc5274 --- /dev/null +++ b/backend/internal/domain/email_address.go @@ -0,0 +1,157 @@ +package domain + +import ( + "errors" + "fmt" + "log/slog" + "strings" +) + +const ( + // Bounds follow the EmailAddress schema in the public contract (3 to 254 + // characters) and the RFC 5321 local-part limit of 64 octets. Addresses + // are ASCII, so characters and bytes coincide. + minEmailAddressLength = 3 + maxEmailAddressLength = 254 + maxEmailLocalPartSize = 64 + maxEmailDomainLabel = 63 + redactedEmailAddress = "[redacted email]" + asciiWhitespace = " \t\n\v\f\r" +) + +var ErrInvalidEmailAddress = errors.New("invalid email address") + +// EmailAddress is a syntactically valid ASCII account email in two forms. +// +// Address is the delivery form: the input with surrounding ASCII whitespace +// removed, in the letter case the user typed, because RFC 5321 allows a +// case-sensitive local part. The account view returns it. +// +// Normalized is the comparison key: the address with A-Z lowercased. Storage +// keeps it unique, so addresses that differ only in letter case conflict. Go +// owns this rule; the database never recomputes the key, because PostgreSQL +// lower() depends on the collation. +// +// Only ASCII addresses are accepted because the mailer does not support +// SMTPUTF8. Internationalized domains are accepted in their ASCII (punycode) +// form. Accepting Unicode addresses is future work: it needs IDNA ToASCII for +// the domain, a rule for Unicode local parts, and SMTPUTF8 delivery. +// +// String, GoString, Format, and LogValue redact the address so it does not +// reach logs by accident; Address returns the real value. +type EmailAddress struct { + address string + normalized string +} + +// NewEmailAddress validates raw and returns both forms. It rejects non-ASCII +// characters, display names, quoted local parts, comments, whitespace or +// control characters inside the address, IP-literal domains, and domains +// without a dot. The outcome depends only on raw, never on stored accounts. +func NewEmailAddress(raw string) (EmailAddress, error) { + // Only ASCII whitespace is trimmed; any other character is validated. + address := strings.Trim(raw, asciiWhitespace) + for index := range len(address) { + if address[index] <= ' ' || address[index] > '~' { + return EmailAddress{}, invalidEmailAddress("address must contain printable ASCII characters only") + } + } + if length := len(address); length < minEmailAddressLength || length > maxEmailAddressLength { + return EmailAddress{}, invalidEmailAddress("address must have 3 to 254 characters") + } + localPart, domainPart, found := strings.Cut(address, "@") + if !found || strings.Contains(domainPart, "@") { + return EmailAddress{}, invalidEmailAddress("address must contain exactly one @") + } + if err := validateEmailLocalPart(localPart); err != nil { + return EmailAddress{}, err + } + if err := validateEmailDomain(domainPart); err != nil { + return EmailAddress{}, err + } + return EmailAddress{address: address, normalized: normalizeEmailKey(address)}, nil +} + +// RestoreEmailAddress rebuilds an EmailAddress from storage. It checks only +// that the stored key matches the stored address, so a later, stricter +// NewEmailAddress rule does not make existing accounts unreadable. +func RestoreEmailAddress(address, normalized string) (EmailAddress, error) { + if address == "" || normalized != normalizeEmailKey(address) { + return EmailAddress{}, fmt.Errorf("domain.RestoreEmailAddress - stored key does not match the stored address: %w", ErrInvalidEmailAddress) + } + return EmailAddress{address: address, normalized: normalized}, nil +} + +// normalizeEmailKey lowercases A-Z only, independent of locale and Unicode +// case rules. +func normalizeEmailKey(address string) string { + return strings.Map(func(character rune) rune { + if 'A' <= character && character <= 'Z' { + return character + ('a' - 'A') + } + return character + }, address) +} + +func validateEmailLocalPart(localPart string) error { + if localPart == "" || len(localPart) > maxEmailLocalPartSize { + return invalidEmailAddress("local part must have 1 to 64 characters") + } + if strings.HasPrefix(localPart, ".") || strings.HasSuffix(localPart, ".") || strings.Contains(localPart, "..") { + return invalidEmailAddress("local part must not start or end with a dot or contain consecutive dots") + } + for _, character := range localPart { + if !isASCIILetterOrDigit(character) && !strings.ContainsRune(".!#$%&'*+-/=?^_`{|}~", character) { + return invalidEmailAddress("local part contains a character outside an unquoted dot-atom") + } + } + return nil +} + +func validateEmailDomain(domainPart string) error { + labels := strings.Split(domainPart, ".") + if len(labels) < 2 { + return invalidEmailAddress("domain must contain at least two labels") + } + for _, label := range labels { + if label == "" || len(label) > maxEmailDomainLabel { + return invalidEmailAddress("domain labels must have 1 to 63 characters") + } + if strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") { + return invalidEmailAddress("domain labels must not start or end with a hyphen") + } + for _, character := range label { + if !isASCIILetterOrDigit(character) && character != '-' { + return invalidEmailAddress("domain contains a character outside letters, digits, and hyphens") + } + } + } + return nil +} + +func isASCIILetterOrDigit(character rune) bool { + return ('a' <= character && character <= 'z') || ('A' <= character && character <= 'Z') || ('0' <= character && character <= '9') +} + +func invalidEmailAddress(reason string) error { + return fmt.Errorf("domain.NewEmailAddress - %s: %w", reason, ErrInvalidEmailAddress) +} + +// Address returns the delivery form. Use it only where the address is needed: +// storage, mail delivery, and the account view. +func (email EmailAddress) Address() string { return email.address } + +// Normalized returns the comparison key that storage keeps unique. +func (email EmailAddress) Normalized() string { return email.normalized } + +// IsZero reports an EmailAddress not built by NewEmailAddress. +func (email EmailAddress) IsZero() bool { return email.normalized == "" } + +func (email EmailAddress) String() string { return redactedEmailAddress } + +func (email EmailAddress) GoString() string { return redactedEmailAddress } + +// Format redacts every verb; without it %d would print the struct fields. +func (email EmailAddress) Format(state fmt.State, _ rune) { writeRedacted(state, redactedEmailAddress) } + +func (email EmailAddress) LogValue() slog.Value { return slog.StringValue(redactedEmailAddress) } diff --git a/backend/internal/domain/email_address_test.go b/backend/internal/domain/email_address_test.go new file mode 100644 index 0000000..82811bf --- /dev/null +++ b/backend/internal/domain/email_address_test.go @@ -0,0 +1,145 @@ +package domain + +import ( + "bytes" + "errors" + "fmt" + "log/slog" + "strings" + "testing" +) + +func TestNewEmailAddressNormalizes(t *testing.T) { + tests := []struct { + name string + raw string + wantAddress string + wantNormalized string + }{ + {name: "plain", raw: "candidate@example.com", wantAddress: "candidate@example.com", wantNormalized: "candidate@example.com"}, + {name: "trims and keeps case for delivery", raw: " \tAlice.Smith@Example.COM\n", wantAddress: "Alice.Smith@Example.COM", wantNormalized: "alice.smith@example.com"}, + {name: "atext characters", raw: "O'Neil+Tag_1!#$%&*/=?^`{|}~-x@example.com", wantAddress: "O'Neil+Tag_1!#$%&*/=?^`{|}~-x@example.com", wantNormalized: "o'neil+tag_1!#$%&*/=?^`{|}~-x@example.com"}, + {name: "punycode domain stays ASCII", raw: "Info@XN--E1AFMKFD.xn--p1ai", wantAddress: "Info@XN--E1AFMKFD.xn--p1ai", wantNormalized: "info@xn--e1afmkfd.xn--p1ai"}, + {name: "minimum length", raw: "a@b.c", wantAddress: "a@b.c", wantNormalized: "a@b.c"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + email, err := NewEmailAddress(test.raw) + if err != nil { + t.Fatalf("NewEmailAddress(%q) error = %v", test.raw, err) + } + if email.Address() != test.wantAddress || email.Normalized() != test.wantNormalized { + t.Fatalf("NewEmailAddress(%q) = (%q, %q), want (%q, %q)", + test.raw, email.Address(), email.Normalized(), test.wantAddress, test.wantNormalized) + } + }) + } +} + +func TestNewEmailAddressCaseVariantsShareTheKey(t *testing.T) { + variants := []string{"Candidate@Example.com", "CANDIDATE@EXAMPLE.COM", " candidate@example.com "} + first, err := NewEmailAddress(variants[0]) + if err != nil { + t.Fatalf("NewEmailAddress(%q) error = %v", variants[0], err) + } + for _, variant := range variants[1:] { + email, err := NewEmailAddress(variant) + if err != nil { + t.Fatalf("NewEmailAddress(%q) error = %v", variant, err) + } + if email.Normalized() != first.Normalized() { + t.Fatalf("Normalized(%q) = %q, want %q", variant, email.Normalized(), first.Normalized()) + } + } +} + +func TestNewEmailAddressRejectsInvalidInput(t *testing.T) { + longLocal := strings.Repeat("a", maxEmailLocalPartSize+1) + "@example.com" + longLabel := "a@" + strings.Repeat("b", maxEmailDomainLabel+1) + ".com" + tooLong := strings.Repeat("a", 60) + "@" + strings.Repeat(strings.Repeat("b", 60)+".", 3) + "example.com" + tests := map[string]string{ + "empty": "", + "blank": " ", + "too short": "a@", + "too long": tooLong, + "no at": "candidate.example.com", + "two ats": "a@b@example.com", + "empty local part": "@example.com", + "empty domain": "candidate@", + "single-label domain": "candidate@localhost", + "leading dot": ".candidate@example.com", + "trailing dot": "candidate.@example.com", + "consecutive dots": "can..didate@example.com", + "inner space": "can didate@example.com", + "quoted local part": `"can didate"@example.com`, + "display name": "Candidate ", + "comment": "candidate(comment)@example.com", + "control character": "cand\x00idate@example.com", + "empty domain label": "candidate@example..com", + "hyphen edge label": "candidate@-example.com", + "ip literal": "candidate@[127.0.0.1]", + "underscore in domain": "candidate@exa_mple.com", + "local part too long": longLocal, + "domain label too long": longLabel, + "invalid utf-8": "cand\xffidate@example.com", + // Non-ASCII input is rejected until IDNA and SMTPUTF8 are supported. + "dotted capital I": "İnfo@x.com", + "fullwidth domain": "info@example.com", + "mixed-script homoglyph": "pаypal@example.com", + "cyrillic domain": "info@пример.рф", + "decomposed accent": "José@example.com", + "non-breaking space trim": " candidate@example.com", + } + for name, raw := range tests { + t.Run(name, func(t *testing.T) { + if _, err := NewEmailAddress(raw); !errors.Is(err, ErrInvalidEmailAddress) { + t.Fatalf("NewEmailAddress(%q) error = %v, want ErrInvalidEmailAddress", raw, err) + } + }) + } +} + +func TestRestoreEmailAddressChecksOnlyConsistency(t *testing.T) { + // A stored address that today's rule would reject still restores, as long + // as its key matches. + restored, err := RestoreEmailAddress("Legacy@Host", "legacy@host") + if err != nil { + t.Fatalf("RestoreEmailAddress(consistent) error = %v", err) + } + if restored.Address() != "Legacy@Host" || restored.Normalized() != "legacy@host" { + t.Fatalf("RestoreEmailAddress() = (%q, %q)", restored.Address(), restored.Normalized()) + } + for _, pair := range [][2]string{{"Legacy@Host", "Legacy@Host"}, {"a@example.com", "b@example.com"}, {"", ""}} { + if _, err := RestoreEmailAddress(pair[0], pair[1]); !errors.Is(err, ErrInvalidEmailAddress) { + t.Fatalf("RestoreEmailAddress(%q, %q) error = %v, want ErrInvalidEmailAddress", pair[0], pair[1], err) + } + } +} + +func TestEmailAddressZeroValue(t *testing.T) { + if !(EmailAddress{}).IsZero() { + t.Fatal("zero EmailAddress is not reported as zero") + } + email, err := NewEmailAddress("candidate@example.com") + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + if email.IsZero() { + t.Fatal("valid EmailAddress is reported as zero") + } +} + +func TestEmailAddressIsRedacted(t *testing.T) { + email, err := NewEmailAddress("Secret.Person@Example.com") + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + var logs bytes.Buffer + slog.New(slog.NewJSONHandler(&logs, nil)).Info("redaction", "email", email) + formatted := fmt.Sprintf("%v %+v %#v %s %q %x %d", email, email, email, email, email, email, email) + logs.String() + for _, secret := range []string{email.Address(), email.Normalized(), "Secret", "secret"} { + if strings.Contains(formatted, secret) { + t.Fatalf("formatted output exposes the address: %s", formatted) + } + } +} diff --git a/backend/internal/domain/email_token.go b/backend/internal/domain/email_token.go new file mode 100644 index 0000000..c29924c --- /dev/null +++ b/backend/internal/domain/email_token.go @@ -0,0 +1,90 @@ +package domain + +import ( + "errors" + "fmt" + "time" + + "github.com/google/uuid" +) + +var ErrInvalidEmailToken = errors.New("invalid email token") + +// EmailTokenPurpose names what an email token authorizes. New purposes, such +// as a planned password reset, are added here and in the email_tokens CHECK +// constraint together. +type EmailTokenPurpose string + +// EmailTokenPurposeEmailVerification authorizes confirming the account email. +const EmailTokenPurposeEmailVerification EmailTokenPurpose = "email_verification" //nolint:gosec // A purpose name, not a credential. + +// ParseEmailTokenPurpose accepts a known purpose. +func ParseEmailTokenPurpose(value string) (EmailTokenPurpose, error) { + purpose := EmailTokenPurpose(value) + if purpose != EmailTokenPurposeEmailVerification { + return "", fmt.Errorf("domain.ParseEmailTokenPurpose - unknown purpose: %w", ErrInvalidEmailToken) + } + return purpose, nil +} + +// EmailToken is the stored record of a one-time token sent by email. It holds +// only the hash of the raw token. A token ends at most once: it is either +// consumed or invalidated, and it stops working at ExpiresAt. +type EmailToken struct { + ID uuid.UUID + UserID uuid.UUID + Purpose EmailTokenPurpose + TokenHash SecretTokenHash + RegistrationVersion int64 + CreatedAt time.Time + ExpiresAt time.Time + ConsumedAt *time.Time + InvalidatedAt *time.Time +} + +// NewEmailTokenInput describes a token to issue. RegistrationVersion is the +// user's current registration version. +type NewEmailTokenInput struct { + UserID uuid.UUID + Purpose EmailTokenPurpose + TokenHash SecretTokenHash + RegistrationVersion int64 + IssuedAt time.Time + Lifetime time.Duration +} + +// NewEmailToken validates input and assigns a UUIDv7 identifier. +func NewEmailToken(input NewEmailTokenInput) (EmailToken, error) { + switch { + case input.UserID == uuid.Nil: + return EmailToken{}, invalidEmailToken("user ID must not be nil") + case input.TokenHash.IsZero(): + return EmailToken{}, invalidEmailToken("token hash must be set") + case input.RegistrationVersion <= 0: + return EmailToken{}, invalidEmailToken("registration version must be positive") + case input.IssuedAt.IsZero(): + return EmailToken{}, invalidEmailToken("issue time must be set") + case input.Lifetime <= 0: + return EmailToken{}, invalidEmailToken("lifetime must be positive") + } + if _, err := ParseEmailTokenPurpose(string(input.Purpose)); err != nil { + return EmailToken{}, fmt.Errorf("domain.NewEmailToken - validate purpose: %w", err) + } + id, err := uuid.NewV7() + if err != nil { + return EmailToken{}, fmt.Errorf("domain.NewEmailToken - generate token ID: %w", err) + } + return EmailToken{ + ID: id, + UserID: input.UserID, + Purpose: input.Purpose, + TokenHash: input.TokenHash, + RegistrationVersion: input.RegistrationVersion, + CreatedAt: input.IssuedAt, + ExpiresAt: input.IssuedAt.Add(input.Lifetime), + }, nil +} + +func invalidEmailToken(reason string) error { + return fmt.Errorf("domain.NewEmailToken - %s: %w", reason, ErrInvalidEmailToken) +} diff --git a/backend/internal/domain/email_token_test.go b/backend/internal/domain/email_token_test.go new file mode 100644 index 0000000..5750668 --- /dev/null +++ b/backend/internal/domain/email_token_test.go @@ -0,0 +1,66 @@ +package domain + +import ( + "errors" + "testing" + "time" + + "github.com/google/uuid" +) + +func testTokenHash(t *testing.T) SecretTokenHash { + t.Helper() + token, err := NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + return token.Hash() +} + +func TestNewEmailTokenSetsExpiryFromLifetime(t *testing.T) { + input := NewEmailTokenInput{ + UserID: uuid.New(), + Purpose: EmailTokenPurposeEmailVerification, + TokenHash: testTokenHash(t), + RegistrationVersion: 3, + IssuedAt: testRegisteredAt, + Lifetime: 24 * time.Hour, + } + token, err := NewEmailToken(input) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + if token.ID.Version() != 7 || token.UserID != input.UserID || token.TokenHash != input.TokenHash || + token.RegistrationVersion != 3 || !token.CreatedAt.Equal(testRegisteredAt) || + !token.ExpiresAt.Equal(testRegisteredAt.Add(24*time.Hour)) || token.ConsumedAt != nil || token.InvalidatedAt != nil { + t.Fatalf("NewEmailToken() = %+v", token) + } +} + +func TestNewEmailTokenRejectsInvalidInput(t *testing.T) { + valid := NewEmailTokenInput{ + UserID: uuid.New(), + Purpose: EmailTokenPurposeEmailVerification, + TokenHash: testTokenHash(t), + RegistrationVersion: 1, + IssuedAt: testRegisteredAt, + Lifetime: time.Hour, + } + tests := map[string]func(*NewEmailTokenInput){ + "nil user": func(input *NewEmailTokenInput) { input.UserID = uuid.Nil }, + "unknown purpose": func(input *NewEmailTokenInput) { input.Purpose = "password_reset" }, + "zero hash": func(input *NewEmailTokenInput) { input.TokenHash = SecretTokenHash{} }, + "zero version": func(input *NewEmailTokenInput) { input.RegistrationVersion = 0 }, + "zero issue time": func(input *NewEmailTokenInput) { input.IssuedAt = time.Time{} }, + "non-positive lifetime": func(input *NewEmailTokenInput) { input.Lifetime = 0 }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + input := valid + mutate(&input) + if _, err := NewEmailToken(input); !errors.Is(err, ErrInvalidEmailToken) { + t.Fatalf("NewEmailToken() error = %v, want ErrInvalidEmailToken", err) + } + }) + } +} diff --git a/backend/internal/domain/secret_token.go b/backend/internal/domain/secret_token.go new file mode 100644 index 0000000..56d498a --- /dev/null +++ b/backend/internal/domain/secret_token.go @@ -0,0 +1,88 @@ +package domain + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "errors" + "fmt" + "log/slog" + "regexp" +) + +const ( + // secretTokenEntropyBytes gives 256 bits of entropy. The encoded value is + // 43 base64url characters, inside the 32 to 128 character bounds that the + // contract sets for VerificationToken and CsrfToken. + secretTokenEntropyBytes = 32 + // SecretTokenHashSize is the size of a SHA-256 digest. + SecretTokenHashSize = sha256.Size + redactedSecret = "[redacted]" +) + +var ( + ErrInvalidSecretToken = errors.New("invalid secret token") + + // The contract pattern for raw tokens that arrive in requests. + secretTokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{32,128}$`) +) + +// SecretToken is a random bearer secret: the token in an email link or the +// session cookie value. Only the holder sees the raw value; storage keeps +// SecretTokenHash. String and LogValue redact the value so it does not reach +// logs by accident; Reveal returns it for the one place that must send it. +type SecretToken struct { + value string +} + +// NewSecretToken returns a token with 256 bits from crypto/rand. +func NewSecretToken() (SecretToken, error) { + entropy := make([]byte, secretTokenEntropyBytes) + if _, err := rand.Read(entropy); err != nil { + return SecretToken{}, fmt.Errorf("domain.NewSecretToken - read random bytes: %w", err) + } + return SecretToken{value: base64.RawURLEncoding.EncodeToString(entropy)}, nil +} + +// ParseSecretToken accepts a raw token from a request. It checks only the +// contract shape; whether the token exists is decided by its hash in storage. +func ParseSecretToken(raw string) (SecretToken, error) { + if !secretTokenPattern.MatchString(raw) { + return SecretToken{}, fmt.Errorf("domain.ParseSecretToken - token must have 32 to 128 base64url characters: %w", ErrInvalidSecretToken) + } + return SecretToken{value: raw}, nil +} + +// Hash returns the SHA-256 digest that storage keeps. A token carries 256 bits +// of entropy, so a fast unsalted digest cannot be reversed by guessing, unlike +// a password, and lookups by digest stay a single index probe. +func (token SecretToken) Hash() SecretTokenHash { + return SecretTokenHash(sha256.Sum256([]byte(token.value))) +} + +// Reveal returns the raw value for delivery to its holder: the email link or +// the Set-Cookie header. Never store or log it. +func (token SecretToken) Reveal() string { return token.value } + +func (token SecretToken) String() string { return redactedSecret } + +func (token SecretToken) GoString() string { return redactedSecret } + +func (token SecretToken) LogValue() slog.Value { return slog.StringValue(redactedSecret) } + +// Format redacts every verb; without it %d would print the struct fields. +func (token SecretToken) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } + +func writeRedacted(state fmt.State, placeholder string) { + _, _ = state.Write([]byte(placeholder)) +} + +// IsZero reports a SecretToken not built by NewSecretToken or ParseSecretToken. +func (token SecretToken) IsZero() bool { return token.value == "" } + +// SecretTokenHash is the SHA-256 digest of a SecretToken. +type SecretTokenHash [SecretTokenHashSize]byte + +// IsZero reports the all-zero value, which no real token hashes to in practice +// and which marks a missing hash. +func (hash SecretTokenHash) IsZero() bool { return hash == SecretTokenHash{} } diff --git a/backend/internal/domain/secret_token_test.go b/backend/internal/domain/secret_token_test.go new file mode 100644 index 0000000..9121cc8 --- /dev/null +++ b/backend/internal/domain/secret_token_test.go @@ -0,0 +1,80 @@ +package domain + +import ( + "bytes" + "crypto/sha256" + "errors" + "fmt" + "log/slog" + "strings" + "testing" +) + +func TestNewSecretTokenMatchesTheContractShape(t *testing.T) { + token, err := NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + parsed, err := ParseSecretToken(token.Reveal()) + if err != nil { + t.Fatalf("ParseSecretToken(generated) error = %v", err) + } + if parsed.Hash() != token.Hash() { + t.Fatal("a parsed token hashes differently from the generated one") + } + other, err := NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + if other.Reveal() == token.Reveal() { + t.Fatal("NewSecretToken() repeated a value") + } +} + +func TestSecretTokenHashIsSHA256OfTheRawValue(t *testing.T) { + raw := strings.Repeat("A", 43) + token, err := ParseSecretToken(raw) + if err != nil { + t.Fatalf("ParseSecretToken() error = %v", err) + } + if want := sha256.Sum256([]byte(raw)); token.Hash() != SecretTokenHash(want) { + t.Fatal("Hash() is not the SHA-256 digest of the raw token") + } + if token.Hash().IsZero() || !(SecretTokenHash{}).IsZero() { + t.Fatal("IsZero() does not distinguish a real digest from the zero value") + } +} + +func TestParseSecretTokenRejectsValuesOutsideTheContract(t *testing.T) { + for _, raw := range []string{ + "", + strings.Repeat("a", 31), + strings.Repeat("a", 129), + strings.Repeat("a", 40) + "=", + strings.Repeat("a", 40) + "+/", + strings.Repeat("a", 40) + " ", + } { + if _, err := ParseSecretToken(raw); !errors.Is(err, ErrInvalidSecretToken) { + t.Fatalf("ParseSecretToken(%q) error = %v, want ErrInvalidSecretToken", raw, err) + } + } +} + +func TestSecretTokenAndPasswordHashAreRedacted(t *testing.T) { + token, err := NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + passwordHash, err := NewPasswordHash(testPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + var logs bytes.Buffer + slog.New(slog.NewTextHandler(&logs, nil)).Info("redaction", "token", token, "hash", passwordHash) + formatted := fmt.Sprintf("%v %+v %#v %s %v %#v", token, token, token, passwordHash, passwordHash, passwordHash) + logs.String() + for _, secret := range []string{token.Reveal(), testPasswordHash} { + if strings.Contains(formatted, secret) { + t.Fatalf("formatted output exposes a secret: %s", formatted) + } + } +} diff --git a/backend/internal/domain/session.go b/backend/internal/domain/session.go new file mode 100644 index 0000000..81a517a --- /dev/null +++ b/backend/internal/domain/session.go @@ -0,0 +1,67 @@ +package domain + +import ( + "errors" + "fmt" + "time" + + "github.com/google/uuid" +) + +var ErrInvalidSession = errors.New("invalid session") + +// Session is a server-side login session. The cookie carries the raw +// SecretToken; storage keeps only TokenHash. ID identifies the session inside +// the server, for example to revoke it, and never leaves the server. +// +// A session is active while it is not revoked, ExpiresAt (the absolute +// deadline) is in the future, and LastSeenAt is within the idle timeout. +// Activity moves only LastSeenAt. +type Session struct { + ID uuid.UUID + UserID uuid.UUID + TokenHash SecretTokenHash + CreatedAt time.Time + LastSeenAt time.Time + ExpiresAt time.Time + RevokedAt *time.Time +} + +// NewSessionInput describes a session to start. AbsoluteLifetime fixes +// ExpiresAt; the idle timeout is applied when the session is looked up. +type NewSessionInput struct { + UserID uuid.UUID + TokenHash SecretTokenHash + StartedAt time.Time + AbsoluteLifetime time.Duration +} + +// NewSession validates input and assigns a UUIDv7 identifier. +func NewSession(input NewSessionInput) (Session, error) { + switch { + case input.UserID == uuid.Nil: + return Session{}, invalidSession("user ID must not be nil") + case input.TokenHash.IsZero(): + return Session{}, invalidSession("token hash must be set") + case input.StartedAt.IsZero(): + return Session{}, invalidSession("start time must be set") + case input.AbsoluteLifetime <= 0: + return Session{}, invalidSession("absolute lifetime must be positive") + } + id, err := uuid.NewV7() + if err != nil { + return Session{}, fmt.Errorf("domain.NewSession - generate session ID: %w", err) + } + return Session{ + ID: id, + UserID: input.UserID, + TokenHash: input.TokenHash, + CreatedAt: input.StartedAt, + LastSeenAt: input.StartedAt, + ExpiresAt: input.StartedAt.Add(input.AbsoluteLifetime), + }, nil +} + +func invalidSession(reason string) error { + return fmt.Errorf("domain.NewSession - %s: %w", reason, ErrInvalidSession) +} diff --git a/backend/internal/domain/session_test.go b/backend/internal/domain/session_test.go new file mode 100644 index 0000000..bd32973 --- /dev/null +++ b/backend/internal/domain/session_test.go @@ -0,0 +1,46 @@ +package domain + +import ( + "errors" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestNewSessionSetsDeadlines(t *testing.T) { + input := NewSessionInput{ + UserID: uuid.New(), + TokenHash: testTokenHash(t), + StartedAt: testRegisteredAt, + AbsoluteLifetime: 7 * 24 * time.Hour, + } + session, err := NewSession(input) + if err != nil { + t.Fatalf("NewSession() error = %v", err) + } + if session.ID.Version() != 7 || session.UserID != input.UserID || session.TokenHash != input.TokenHash || + !session.CreatedAt.Equal(testRegisteredAt) || !session.LastSeenAt.Equal(testRegisteredAt) || + !session.ExpiresAt.Equal(testRegisteredAt.Add(7*24*time.Hour)) || session.RevokedAt != nil { + t.Fatalf("NewSession() = %+v", session) + } +} + +func TestNewSessionRejectsInvalidInput(t *testing.T) { + valid := NewSessionInput{UserID: uuid.New(), TokenHash: testTokenHash(t), StartedAt: testRegisteredAt, AbsoluteLifetime: time.Hour} + tests := map[string]func(*NewSessionInput){ + "nil user": func(input *NewSessionInput) { input.UserID = uuid.Nil }, + "zero hash": func(input *NewSessionInput) { input.TokenHash = SecretTokenHash{} }, + "zero start": func(input *NewSessionInput) { input.StartedAt = time.Time{} }, + "non-positive lifetime": func(input *NewSessionInput) { input.AbsoluteLifetime = -time.Second }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + input := valid + mutate(&input) + if _, err := NewSession(input); !errors.Is(err, ErrInvalidSession) { + t.Fatalf("NewSession() error = %v, want ErrInvalidSession", err) + } + }) + } +} diff --git a/backend/internal/domain/user.go b/backend/internal/domain/user.go new file mode 100644 index 0000000..574c113 --- /dev/null +++ b/backend/internal/domain/user.go @@ -0,0 +1,255 @@ +package domain + +import ( + "encoding/base64" + "errors" + "fmt" + "log/slog" + "regexp" + "time" + + "github.com/google/uuid" +) + +const ( + // maxPasswordHashLength bounds a PHC string. Encoded Argon2id hashes with + // common parameters stay near 100 bytes. + maxPasswordHashLength = 512 + // minPasswordSaltBytes and minPasswordDigestBytes follow the RFC 9106 + // recommendations of a 16-byte salt and a 32-byte tag, relaxed to bounds + // that still reject truncated or placeholder values. + minPasswordSaltBytes = 8 + minPasswordDigestBytes = 16 +) + +// passwordHashPattern is the Argon2id PHC string format: version 19, memory, +// iterations, and parallelism, then the salt and the digest in unpadded +// standard base64. Argon2id is the only password hash the identity contract +// accepts. +var passwordHashPattern = regexp.MustCompile( + `^\$argon2id\$v=19\$m=[1-9][0-9]{0,9},t=[1-9][0-9]{0,9},p=[1-9][0-9]{0,2}\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)$`, +) + +var ( + ErrInvalidUser = errors.New("invalid user") + ErrInvalidPasswordHash = errors.New("invalid password hash") + ErrEmailAlreadyVerified = errors.New("email already verified") +) + +// Scenario is the account scenario chosen at registration. Values match the +// AccountScenario schema of the public contract. +type Scenario string + +const ( + ScenarioCandidate Scenario = "candidate" + ScenarioEmployer Scenario = "employer" +) + +// ParseScenario accepts a value of the AccountScenario contract enum. +func ParseScenario(value string) (Scenario, error) { + scenario := Scenario(value) + switch scenario { + case ScenarioCandidate, ScenarioEmployer: + return scenario, nil + default: + return "", fmt.Errorf("domain.ParseScenario - unknown scenario: %w", ErrInvalidUser) + } +} + +// InitialOnboardingStep is the step a new or re-registered account starts at. +func (scenario Scenario) InitialOnboardingStep() OnboardingStep { + if scenario == ScenarioEmployer { + return OnboardingStepEmployerCompany + } + return OnboardingStepCandidateConsents +} + +// AllowsStep reports whether step belongs to the scenario's onboarding. +func (scenario Scenario) AllowsStep(step OnboardingStep) bool { + switch step { + case OnboardingStepCompleted: + return scenario == ScenarioCandidate || scenario == ScenarioEmployer + case OnboardingStepCandidateConsents, OnboardingStepCandidateProfile, + OnboardingStepCandidateQuestionnaire, OnboardingStepCandidateAssessment: + return scenario == ScenarioCandidate + case OnboardingStepEmployerCompany: + return scenario == ScenarioEmployer + default: + return false + } +} + +// OnboardingStep is the saved step the account returns to after login. Values +// match the OnboardingStep schema of the public contract. +type OnboardingStep string + +const ( + OnboardingStepCandidateConsents OnboardingStep = "candidate_consents" + OnboardingStepCandidateProfile OnboardingStep = "candidate_profile" + OnboardingStepCandidateQuestionnaire OnboardingStep = "candidate_questionnaire" + OnboardingStepCandidateAssessment OnboardingStep = "candidate_assessment" + OnboardingStepEmployerCompany OnboardingStep = "employer_company" + OnboardingStepCompleted OnboardingStep = "completed" +) + +// ParseOnboardingStep accepts a value of the OnboardingStep contract enum. +func ParseOnboardingStep(value string) (OnboardingStep, error) { + step := OnboardingStep(value) + switch step { + case OnboardingStepCandidateConsents, OnboardingStepCandidateProfile, OnboardingStepCandidateQuestionnaire, + OnboardingStepCandidateAssessment, OnboardingStepEmployerCompany, OnboardingStepCompleted: + return step, nil + default: + return "", fmt.Errorf("domain.ParseOnboardingStep - unknown onboarding step: %w", ErrInvalidUser) + } +} + +// PasswordHash is an Argon2id hash in the PHC string format. It is never the +// password itself. String and LogValue redact it. +type PasswordHash struct { + phc string +} + +// NewPasswordHash validates the structure of a PHC string produced by the +// password hasher, which also keeps a raw password from being stored by +// mistake. +func NewPasswordHash(phc string) (PasswordHash, error) { + if len(phc) > maxPasswordHashLength { + return PasswordHash{}, invalidPasswordHash("hash must have at most 512 bytes") + } + parts := passwordHashPattern.FindStringSubmatch(phc) + if parts == nil { + return PasswordHash{}, invalidPasswordHash("hash must be an Argon2id v19 PHC string") + } + salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[1]) + if err != nil || len(salt) < minPasswordSaltBytes { + return PasswordHash{}, invalidPasswordHash("salt must be unpadded base64 of at least 8 bytes") + } + digest, err := base64.RawStdEncoding.Strict().DecodeString(parts[2]) + if err != nil || len(digest) < minPasswordDigestBytes { + return PasswordHash{}, invalidPasswordHash("digest must be unpadded base64 of at least 16 bytes") + } + return PasswordHash{phc: phc}, nil +} + +func invalidPasswordHash(reason string) error { + return fmt.Errorf("domain.NewPasswordHash - %s: %w", reason, ErrInvalidPasswordHash) +} + +// PHC returns the encoded hash for storage and verification. +func (hash PasswordHash) PHC() string { return hash.phc } + +func (hash PasswordHash) String() string { return redactedSecret } + +func (hash PasswordHash) GoString() string { return redactedSecret } + +func (hash PasswordHash) LogValue() slog.Value { return slog.StringValue(redactedSecret) } + +// Format redacts every verb; without it %d would print the struct fields. +func (hash PasswordHash) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } + +// IsZero reports a PasswordHash not built by NewPasswordHash. +func (hash PasswordHash) IsZero() bool { return hash.phc == "" } + +// Registration is the validated content of one registration request. +type Registration struct { + Email EmailAddress + PasswordHash PasswordHash + Scenario Scenario + // RegisteredAt is the application clock at registration. The planned + // cleanup deletes an account that stays unverified past a deadline counted + // from the latest registration. + RegisteredAt time.Time +} + +func (registration Registration) validate(location string) error { + if registration.Email.IsZero() { + return fmt.Errorf("%s - email must be built by NewEmailAddress: %w", location, ErrInvalidUser) + } + if registration.PasswordHash.IsZero() { + return fmt.Errorf("%s - password hash must be built by NewPasswordHash: %w", location, ErrInvalidUser) + } + if _, err := ParseScenario(string(registration.Scenario)); err != nil { + return fmt.Errorf("%s - validate scenario: %w", location, err) + } + if registration.RegisteredAt.IsZero() { + return fmt.Errorf("%s - registration time must be set: %w", location, ErrInvalidUser) + } + return nil +} + +// User is an account. Storage reconstructs it from trusted rows; new accounts +// come from NewUser and changes from its methods. +type User struct { + ID uuid.UUID + Email EmailAddress + PasswordHash PasswordHash + Scenario Scenario + // OnboardingStep always belongs to Scenario (see Scenario.AllowsStep). + OnboardingStep OnboardingStep + EmailVerifiedAt *time.Time + // RegistrationVersion starts at 1 and advances on every registration of + // the still unverified email. Email tokens are bound to the version they + // were issued for, so a token from an earlier registration never confirms + // newer credentials. + RegistrationVersion int64 + LastRegisteredAt time.Time + // Version is the optimistic concurrency version. Storage advances it on + // every update and accepts an update only from the version it was read at. + Version int64 + CreatedAt time.Time + UpdatedAt time.Time +} + +// NewUser creates an unverified account at the scenario's first onboarding +// step with a time-ordered UUIDv7 identifier. +func NewUser(registration Registration) (User, error) { + if err := registration.validate("domain.NewUser"); err != nil { + return User{}, err + } + id, err := uuid.NewV7() + if err != nil { + return User{}, fmt.Errorf("domain.NewUser - generate user ID: %w", err) + } + return User{ + ID: id, + Email: registration.Email, + PasswordHash: registration.PasswordHash, + Scenario: registration.Scenario, + OnboardingStep: registration.Scenario.InitialOnboardingStep(), + RegistrationVersion: 1, + LastRegisteredAt: registration.RegisteredAt, + Version: 1, + CreatedAt: registration.RegisteredAt, + UpdatedAt: registration.RegisteredAt, + }, nil +} + +// EmailVerified reports whether the email has been confirmed. +func (user User) EmailVerified() bool { return user.EmailVerifiedAt != nil } + +// ReRegister applies a new registration of the same unverified email. It +// replaces the delivery form of the email, the password hash, the scenario, +// and the onboarding step. Version and RegistrationVersion are left unchanged: +// storage checks Version as the expected version, advances both in the same +// statement, and returns the stored account. A verified account returns +// ErrEmailAlreadyVerified and does not change. +func (user User) ReRegister(registration Registration) (User, error) { + if err := registration.validate("User.ReRegister"); err != nil { + return User{}, err + } + if user.EmailVerified() { + return User{}, fmt.Errorf("User.ReRegister - re-register account: %w", ErrEmailAlreadyVerified) + } + if registration.Email.Normalized() != user.Email.Normalized() { + return User{}, fmt.Errorf("User.ReRegister - email must match the account email: %w", ErrInvalidUser) + } + updated := user + updated.Email = registration.Email + updated.PasswordHash = registration.PasswordHash + updated.Scenario = registration.Scenario + updated.OnboardingStep = registration.Scenario.InitialOnboardingStep() + updated.LastRegisteredAt = registration.RegisteredAt + updated.UpdatedAt = registration.RegisteredAt + return updated, nil +} diff --git a/backend/internal/domain/user_test.go b/backend/internal/domain/user_test.go new file mode 100644 index 0000000..f53fabc --- /dev/null +++ b/backend/internal/domain/user_test.go @@ -0,0 +1,211 @@ +package domain + +import ( + "errors" + "fmt" + "strings" + "testing" + "time" +) + +const testPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA" + +var testRegisteredAt = time.Date(2026, time.October, 5, 12, 0, 0, 0, time.UTC) + +func testRegistration(t *testing.T, rawEmail string, scenario Scenario) Registration { + t.Helper() + email, err := NewEmailAddress(rawEmail) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + passwordHash, err := NewPasswordHash(testPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + return Registration{Email: email, PasswordHash: passwordHash, Scenario: scenario, RegisteredAt: testRegisteredAt} +} + +func TestParseScenarioAndOnboardingStepAcceptContractValues(t *testing.T) { + for _, value := range []string{"candidate", "employer"} { + if scenario, err := ParseScenario(value); err != nil || string(scenario) != value { + t.Fatalf("ParseScenario(%q) = %q, %v", value, scenario, err) + } + } + for _, value := range []string{ + "candidate_consents", "candidate_profile", "candidate_questionnaire", + "candidate_assessment", "employer_company", "completed", + } { + if step, err := ParseOnboardingStep(value); err != nil || string(step) != value { + t.Fatalf("ParseOnboardingStep(%q) = %q, %v", value, step, err) + } + } + for _, value := range []string{"", "Candidate", "admin"} { + if _, err := ParseScenario(value); !errors.Is(err, ErrInvalidUser) { + t.Fatalf("ParseScenario(%q) error = %v, want ErrInvalidUser", value, err) + } + if _, err := ParseOnboardingStep(value); !errors.Is(err, ErrInvalidUser) { + t.Fatalf("ParseOnboardingStep(%q) error = %v, want ErrInvalidUser", value, err) + } + } +} + +func TestScenarioOnboardingSteps(t *testing.T) { + tests := []struct { + scenario Scenario + initial OnboardingStep + allowed []OnboardingStep + denied []OnboardingStep + }{ + { + scenario: ScenarioCandidate, + initial: OnboardingStepCandidateConsents, + allowed: []OnboardingStep{ + OnboardingStepCandidateConsents, OnboardingStepCandidateProfile, OnboardingStepCandidateQuestionnaire, + OnboardingStepCandidateAssessment, OnboardingStepCompleted, + }, + denied: []OnboardingStep{OnboardingStepEmployerCompany, "unknown"}, + }, + { + scenario: ScenarioEmployer, + initial: OnboardingStepEmployerCompany, + allowed: []OnboardingStep{OnboardingStepEmployerCompany, OnboardingStepCompleted}, + denied: []OnboardingStep{OnboardingStepCandidateConsents, OnboardingStepCandidateAssessment, "unknown"}, + }, + } + for _, test := range tests { + if got := test.scenario.InitialOnboardingStep(); got != test.initial { + t.Fatalf("%s.InitialOnboardingStep() = %q, want %q", test.scenario, got, test.initial) + } + for _, step := range test.allowed { + if !test.scenario.AllowsStep(step) { + t.Fatalf("%s.AllowsStep(%q) = false, want true", test.scenario, step) + } + } + for _, step := range test.denied { + if test.scenario.AllowsStep(step) { + t.Fatalf("%s.AllowsStep(%q) = true, want false", test.scenario, step) + } + } + } +} + +func TestNewPasswordHashAcceptsOnlyArgon2idPHC(t *testing.T) { + for _, value := range []string{ + testPasswordHash, + "$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHRzb21lc2FsdA$RdescudvJCsgt3ub+b+dWRWJTmaaJObG", + } { + if _, err := NewPasswordHash(value); err != nil { + t.Fatalf("NewPasswordHash(%.30q) error = %v", value, err) + } + } + for name, value := range map[string]string{ + "empty": "", + "raw password": "correct horse battery staple", + "bcrypt": "$2b$12$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ01234", + "argon2i": "$argon2i$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "prefix only": "$argon2id$", + "old version": "$argon2id$v=16$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "missing parameter": "$argon2id$v=19$m=19456,t=2$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "zero memory": "$argon2id$v=19$m=0,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "padded salt": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHQ=$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "short salt": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "short digest": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaA", + "impossible base64": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0a$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "url-safe alphabet": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGF_aGhhc2hoYXNoaGFzaA", + "trailing space": testPasswordHash + " ", + "trailing newline": testPasswordHash + "\n", + "extra segment": testPasswordHash + "$extra", + "too long": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$" + strings.Repeat("a", maxPasswordHashLength), + } { + if _, err := NewPasswordHash(value); !errors.Is(err, ErrInvalidPasswordHash) { + t.Fatalf("NewPasswordHash(%s) error = %v, want ErrInvalidPasswordHash", name, err) + } + } +} + +func TestNewUserStartsUnverifiedAtTheFirstStep(t *testing.T) { + registration := testRegistration(t, "Employer@Example.com", ScenarioEmployer) + user, err := NewUser(registration) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if user.ID.Version() != 7 { + t.Fatalf("ID version = %d, want UUIDv7", user.ID.Version()) + } + if user.EmailVerified() || user.OnboardingStep != OnboardingStepEmployerCompany || + user.RegistrationVersion != 1 || user.Version != 1 { + t.Fatalf("NewUser() = %+v, want an unverified employer at employer_company with versions 1", user) + } + if !user.LastRegisteredAt.Equal(testRegisteredAt) || !user.CreatedAt.Equal(testRegisteredAt) || !user.UpdatedAt.Equal(testRegisteredAt) { + t.Fatalf("NewUser() timestamps = %v, %v, %v, want the registration time", user.LastRegisteredAt, user.CreatedAt, user.UpdatedAt) + } +} + +func TestNewUserRejectsIncompleteRegistration(t *testing.T) { + valid := testRegistration(t, "candidate@example.com", ScenarioCandidate) + tests := map[string]func(*Registration){ + "zero email": func(registration *Registration) { registration.Email = EmailAddress{} }, + "zero password hash": func(registration *Registration) { registration.PasswordHash = PasswordHash{} }, + "unknown scenario": func(registration *Registration) { registration.Scenario = "admin" }, + "zero time": func(registration *Registration) { registration.RegisteredAt = time.Time{} }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + registration := valid + mutate(®istration) + if _, err := NewUser(registration); !errors.Is(err, ErrInvalidUser) { + t.Fatalf("NewUser() error = %v, want ErrInvalidUser", err) + } + }) + } +} + +func TestReRegisterReplacesTheRegistrationOfAnUnverifiedAccount(t *testing.T) { + user, err := NewUser(testRegistration(t, "candidate@example.com", ScenarioCandidate)) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + user.OnboardingStep = OnboardingStepCandidateProfile + again := testRegistration(t, "Candidate@Example.com", ScenarioEmployer) + again.RegisteredAt = testRegisteredAt.Add(time.Hour) + + updated, err := user.ReRegister(again) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + if updated.ID != user.ID || updated.Email.Address() != "Candidate@Example.com" || + updated.Scenario != ScenarioEmployer || updated.OnboardingStep != OnboardingStepEmployerCompany || + updated.RegistrationVersion != user.RegistrationVersion || updated.Version != user.Version || + !updated.LastRegisteredAt.Equal(again.RegisteredAt) || !updated.UpdatedAt.Equal(again.RegisteredAt) || + !updated.CreatedAt.Equal(user.CreatedAt) { + t.Fatalf("ReRegister() = %+v", updated) + } +} + +func TestReRegisterRejectsVerifiedOrDifferentEmail(t *testing.T) { + user, err := NewUser(testRegistration(t, "candidate@example.com", ScenarioCandidate)) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if _, err := user.ReRegister(testRegistration(t, "other@example.com", ScenarioCandidate)); !errors.Is(err, ErrInvalidUser) { + t.Fatalf("ReRegister(other email) error = %v, want ErrInvalidUser", err) + } + verifiedAt := testRegisteredAt.Add(time.Minute) + user.EmailVerifiedAt = &verifiedAt + if _, err := user.ReRegister(testRegistration(t, "candidate@example.com", ScenarioCandidate)); !errors.Is(err, ErrEmailAlreadyVerified) { + t.Fatalf("ReRegister(verified) error = %v, want ErrEmailAlreadyVerified", err) + } +} + +func TestFormattedUserHidesEmailAndPasswordHash(t *testing.T) { + user, err := NewUser(testRegistration(t, "Private.Person@Example.com", ScenarioCandidate)) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + formatted := fmt.Sprintf("%v %+v %#v", user, user, user) + for _, secret := range []string{"Private", "private", "example.com", testPasswordHash, "argon2id"} { + if strings.Contains(formatted, secret) { + t.Fatalf("formatted user exposes %q: %s", secret, formatted) + } + } +} diff --git a/backend/internal/port/outbound/identity.go b/backend/internal/port/outbound/identity.go new file mode 100644 index 0000000..9bf69ca --- /dev/null +++ b/backend/internal/port/outbound/identity.go @@ -0,0 +1,165 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrUserNotFound reports that no account matches, including an insert + // that references an account deleted in the meantime. + ErrUserNotFound = errors.New("user not found") + + // ErrEmailTaken reports that another account already has the same + // normalized email. + ErrEmailTaken = errors.New("email already registered") + + // ErrUserVersionConflict reports that a conditional account update matched + // no row: the expected version is stale, the email is already verified, + // or the registration version has moved on. Read the account again. + ErrUserVersionConflict = errors.New("user changed concurrently") + + // ErrTokenHashConflict reports a second token or session with the same + // hash. With 256-bit random tokens it signals a broken generator, not a + // retryable condition. + ErrTokenHashConflict = errors.New("token hash already stored") + + // ErrEmailTokenNotFound reports that no token of the purpose has the hash. + ErrEmailTokenNotFound = errors.New("email token not found") + + // ErrEmailTokenConsumed reports a token that was already consumed. + ErrEmailTokenConsumed = errors.New("email token already consumed") + + // ErrEmailTokenInvalidated reports a token replaced by a later resend or + // re-registration, or issued for an earlier registration version. + ErrEmailTokenInvalidated = errors.New("email token invalidated") + + // ErrEmailTokenExpired reports a token past its lifetime that was neither + // consumed nor invalidated. + ErrEmailTokenExpired = errors.New("email token expired") + + // ErrSessionNotFound reports a session that does not exist, is revoked, + // is past its absolute deadline, or is idle longer than the timeout. + ErrSessionNotFound = errors.New("session not found") +) + +// IdentityRepositories exposes the identity repositories. UnitOfWork binds +// them to one transaction; an adapter may also provide them outside a +// transaction, where every call is its own statement. Every method that takes +// a time rejects the zero time. +// +// Lock order: an operation that changes both an account and its email tokens +// locks the tokens first and the account second, as Consume and +// MarkEmailVerified do in a confirmation. A re-registration or a resend +// therefore calls InvalidateActive before UpdateRegistration or Insert; the +// opposite order can deadlock against a concurrent confirmation. The only +// exception is DeleteUnverifiedRegisteredBefore, which locks the account +// before its tokens and sessions; it is safe because every lock it takes uses +// SKIP LOCKED and never waits. A deadlock that still happens, for example +// between callers that ignore this order, aborts one transaction with +// ErrTransactionConflict, and the caller may retry it. +type IdentityRepositories interface { + Users() UserRepository + EmailTokens() EmailTokenRepository + Sessions() SessionRepository +} + +// UserRepository stores accounts. Lookups by email use the normalized form. +type UserRepository interface { + // Create returns an error wrapping ErrEmailTaken when the normalized email + // already belongs to an account. + Create(ctx context.Context, user domain.User) error + + // GetByID returns ErrUserNotFound when no account has the ID. + GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) + + // GetByEmail returns ErrUserNotFound when no account has the normalized + // email. + GetByEmail(ctx context.Context, email domain.EmailAddress) (domain.User, error) + + // UpdateRegistration stores user as returned by domain.User.ReRegister. + // It applies only when the stored version still equals user.Version and + // the email is unverified. The same statement advances Version and + // RegistrationVersion by one, so callers never choose the registration + // version; the returned account carries the new values. Otherwise it + // returns ErrUserVersionConflict. + UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error) + + // MarkEmailVerified sets the verification time when the account is still + // unverified and still has registrationVersion, and returns the stored + // account. Otherwise it returns ErrUserVersionConflict. A confirmation + // calls it after EmailTokenRepository.Consume in the same transaction; see + // Consume. + MarkEmailVerified(ctx context.Context, id uuid.UUID, registrationVersion int64, at time.Time) (domain.User, error) + + // DeleteUnverifiedRegisteredBefore deletes at most limit accounts that are + // unverified and were last registered before cutoff, oldest first, with + // their tokens and sessions, and returns how many it deleted. It never + // waits for a lock: an account whose row, token, or session is locked by + // another transaction is skipped and stays for the next run. A cleanup job + // repeats it until the result is below limit and runs again later. + DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error) +} + +// EmailTokenRepository stores email token hashes. It never receives a raw +// token. +type EmailTokenRepository interface { + // Insert returns ErrUserNotFound when the account does not exist and + // ErrTokenHashConflict for a duplicate hash. + Insert(ctx context.Context, token domain.EmailToken) error + + // InvalidateActive marks every unconsumed, not yet invalidated token of + // the user and purpose as invalidated at the given time, and returns how + // many it marked. + InvalidateActive(ctx context.Context, userID uuid.UUID, purpose domain.EmailTokenPurpose, at time.Time) (int64, error) + + // Consume atomically marks the token consumed at the given time and + // returns it. Of concurrent calls with the same hash exactly one succeeds; + // the others wait for its transaction and then fail. It fails with + // ErrEmailTokenNotFound, ErrEmailTokenConsumed, ErrEmailTokenInvalidated, + // or ErrEmailTokenExpired, in that order of precedence. + // + // Consume compares the token's registration version with the account only + // as its statement reads the account, without locking it, so a + // re-registration that commits right after it is not detected. Binding the + // token to the current registration therefore requires a confirmation to + // call Users().MarkEmailVerified(token.UserID, token.RegistrationVersion) + // in the same transaction and to roll back when it returns + // ErrUserVersionConflict; the rollback also restores the token. The + // confirmation usecase maps that outcome to verification_token_invalid. + Consume(ctx context.Context, hash domain.SecretTokenHash, purpose domain.EmailTokenPurpose, at time.Time) (domain.EmailToken, error) +} + +// SessionRepository stores server-side sessions by the hash of their token. +type SessionRepository interface { + // Create returns ErrUserNotFound when the account does not exist and + // ErrTokenHashConflict for a duplicate hash. + Create(ctx context.Context, session domain.Session) error + + // FindActive returns the session with the hash when it is not revoked, + // its absolute deadline is after at, and it was last seen less than + // idleTimeout before at. Otherwise it returns ErrSessionNotFound. + FindActive(ctx context.Context, hash domain.SecretTokenHash, at time.Time, idleTimeout time.Duration) (domain.Session, error) + + // Touch records activity at the given time on a session that is still + // active by the same rules as FindActive and returns ErrSessionNotFound + // when it is not. To avoid a write on every request, the adapter stores + // the new time only when the stored last_seen_at is at least a short + // interval older (one minute in PostgreSQL), so the idle timeout can end + // a session up to that interval early. last_seen_at never moves back. + Touch(ctx context.Context, id uuid.UUID, at time.Time, idleTimeout time.Duration) error + + // Revoke revokes the session at the given time. It returns + // ErrSessionNotFound when the session does not exist or is already + // revoked. + Revoke(ctx context.Context, id uuid.UUID, at time.Time) error + + // RevokeAllForUser revokes every unrevoked session of the user and returns + // how many it revoked. + RevokeAllForUser(ctx context.Context, userID uuid.UUID, at time.Time) (int64, error) +} diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index 34f69b6..3b4d3f0 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -17,13 +17,22 @@ var ( // transaction callback. Nested calls would silently use a second connection // and commit independently of the outer transaction. ErrNestedTransaction = errors.New("transaction already in progress") + + // ErrTransactionConflict reports that PostgreSQL aborted the work with a + // deadlock (SQLSTATE 40P01) or a serialization failure (40001). Nothing + // was committed. The caller may retry the whole operation, ideally with a + // short backoff and a bounded number of attempts; a usecase or job that + // retries must stay idempotent. + ErrTransactionConflict = errors.New("transaction conflict") ) // Transactor runs a business operation in one database transaction. type Transactor interface { // WithinTransaction commits when fn returns nil and rolls back when fn - // returns an error or panics. The error is returned unchanged in identity - // and a panic is re-raised after the rollback. fn must use only the + // returns an error or panics. The error keeps its identity for errors.Is + // and errors.As; a deadlock or serialization failure, from fn or from the + // commit, additionally matches ErrTransactionConflict. A panic is + // re-raised after the rollback. fn must use only the // UnitOfWork and context it receives and must not retain them after // returning. Calling WithinTransaction with that context returns // ErrNestedTransaction. After a database error inside fn the transaction is @@ -39,6 +48,7 @@ type Transactor interface { // UnitOfWork exposes repositories bound to one transaction. Product // repositories are added here as their usecases appear. type UnitOfWork interface { + IdentityRepositories Outbox() OutboxWriter } diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index e94302e..4800c18 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -107,10 +107,10 @@ backend/ cmd/app/main.go calls bootstrap.Run and reports errors config/ shared runtime configuration internal/ - domain/ flat package; DomainEvent for the outbox + domain/ flat package; DomainEvent, identity types usecase/health/ operational readiness usecase port/inbound/ readiness input boundary - port/outbound/ readiness, cache, object storage, transaction, and outbox boundaries + port/outbound/ readiness, cache, object storage, transaction, outbox, and identity boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -119,22 +119,22 @@ backend/ router.go chi composition adapter/secondary/ ml/api/ generated client from backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, outbox writer, health check + postgres/ pool, migrator, transactor, outbox writer, identity repositories, health check postgres/sqlc/ generated SQL adapter redis/ cache adapter and Redis check seaweedfs/ S3 adapter and bucket check prometheus/ bounded Go/process and request metrics bootstrap/ configuration, wiring, lifecycle, shutdown - db/ embedded migrations and SQL queries; outbox table, no product schema yet + db/ embedded migrations and SQL queries; outbox and identity tables codegen/ ogen and sqlc configs pkg/ reserved for justified shared technical helpers ``` -Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. +Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`. Product domain types and usecase modules, mail/FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. -This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, a Redis cache adapter, and a SeaweedFS S3 adapter. Accounts, resumes, assessments, invitations, worker jobs, file workflows, mail, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. +This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, a Redis cache adapter, and a SeaweedFS S3 adapter. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. `backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `emailtemplate`, `mailer`, and test helpers. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. @@ -227,6 +227,34 @@ Future FSP identity linking requires provider verification. A manually entered i The brief references Russian Federal Law 152-FZ. The system design calls for separate processing/publication consents, revocation, transfer controls for ML, and retention/deletion periods. Architecture documentation does not prove legal compliance. Agree on data handling before using real personal data; use synthetic profiles for the demo. +### Identity storage + +Implemented as storage only (TASK-051): migration `backend/db/migrations/00002_create_identity_tables.sql`, queries in `backend/db/queries/identity.sql`, domain types in `backend/internal/domain/`, ports in `backend/internal/port/outbound/identity.go`, and the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/identity.go`. The registration, verification, login, and session behavior described in [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf) is planned (TASK-053 to TASK-056); no usecase or handler uses this storage yet. + +- `users`: UUIDv7 `id`; `email`, the delivery form (trimmed ASCII, letter case as typed, returned as `Account.email`), and `email_normalized`, the unique comparison key (the same address with A-Z lowercased); `password_hash`, an Argon2id v19 PHC string; `scenario` and `onboarding_step` with a CHECK that the step belongs to the scenario; nullable `email_verified_at`; `registration_version`; `last_registered_at` with a partial index over unverified accounts for the planned 7-day cleanup; the optimistic `version`; `created_at` and `updated_at`. The delivery form is kept because RFC 5321 allows a case-sensitive local part: mail goes to the address as typed, while uniqueness ignores letter case. +- `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists the allowed purposes, so a password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. A CHECK allows at most one of consumed and invalidated. +- `sessions`: a UUIDv7 `id` that never leaves the server, `token_hash` (SHA-256 of the cookie value, unique), `user_id`, `created_at`, `last_seen_at`, the absolute `expires_at`, and `revoked_at`. No IP address or user agent is stored. +- Tokens and sessions reference `users` with `ON DELETE CASCADE`. The consent tables planned in TASK-062 can reference `users.id` the same way. CHECK constraints repeat the domain rules as a backstop: the ASCII address and its key, the PHC format, and timestamps (verification, consumption, invalidation, and revocation) not earlier than `created_at`. + +Decisions: + +- Email addresses are ASCII only, because the mailer has no SMTPUTF8 support. `domain.NewEmailAddress` rejects any non-ASCII character, including homoglyphs and fullwidth forms, with `ErrInvalidEmailAddress`, which the registration handler is expected to answer with 400 `validation_failed` whether or not an account exists. Internationalized domains are accepted only in their punycode form (`xn--...`). The key lowercases A-Z only; the database checks it with `translate()`, which does not depend on the collation, unlike `lower()`. Unicode addresses are future work: they need IDNA ToASCII for the domain, a rule for Unicode local parts, and SMTPUTF8 delivery. Rows are read back with `domain.RestoreEmailAddress`, which checks only that the address and key match, so a stricter rule later does not make existing accounts unreadable. +- The database stores hashes, never passwords or raw tokens. A token carries 256 bits from crypto/rand, so an unsalted SHA-256 cannot be reversed by guessing and a lookup stays one index probe; passwords need the slow Argon2id KDF instead. `bytea` keeps the digest at half the size of hex text, with an exact length CHECK and no letter-case variants. `domain.SecretToken`, `domain.PasswordHash`, and `domain.EmailAddress` redact themselves in `fmt` (every verb) and `slog` output, so printing a `domain.User` shows neither the address nor the hash; explicit accessors return the real values. Unmapped PostgreSQL errors from the identity repositories keep only the SQLSTATE and the constraint name, because the message and detail can quote row values. +- Enum-like columns are text with CHECK constraints rather than PostgreSQL enum types. A new scenario, step, or purpose replaces one constraint in a reversible migration; an enum value cannot be removed and cannot be used in the transaction that adds it. +- Every stored time comes from the application clock that the caller passes, so deadlines and the checks against them use one clock. Repositories reject the zero time. +- There is no CSRF column. `GetCurrentSession` must return the session's CSRF token after a reload, which a stored hash cannot reproduce. TASK-056 can derive the token from the session token with a server key, which needs no storage, or add a column in an additive migration. + +What the ports guarantee: + +- `UserRepository.Create` returns `ErrEmailTaken` for a duplicate key. `UpdateRegistration` stores the result of `domain.User.ReRegister` only when the stored `version` matches and the email is unverified; the same statement advances `version` and `registration_version` by one, so no caller chooses the registration version. `MarkEmailVerified` applies only to an unverified account with the given registration version. Both return `ErrUserVersionConflict` otherwise. +- `EmailTokenRepository.Consume` is one `UPDATE ... RETURNING` that requires an unconsumed, uninvalidated, unexpired token. Concurrent callers queue on the token row lock; under READ COMMITTED each waiter re-checks the row after the holder finishes, so exactly one succeeds and, if the holder rolls back, a waiter can still succeed. A miss is reported as `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (replaced, or issued for an earlier registration version), or `ErrEmailTokenExpired`. `InvalidateActive` marks every earlier token of a user and purpose. +- Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase (TASK-054) maps that outcome to `verification_token_invalid`. +- `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` writes `last_seen_at` only when the stored value is more than one minute older, so frequent requests do not rewrite the row and the idle timeout can end a session up to a minute early; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`. +- `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, and their sessions with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token or session row, is locked by another transaction, such as a re-registration, a resend, or a confirmation; skipped accounts stay for the next run. +- `postgres.IdentityStore` runs the same repositories outside a transaction. Called with a context from a `Transactor` callback, it returns `ErrNestedTransaction` instead of committing on a separate connection. +- Unique and foreign key violations map to `ErrEmailTaken`, `ErrTokenHashConflict`, and `ErrUserNotFound` by SQLSTATE and constraint name, never by error text. +- Lock order: an operation that changes both an account and its tokens locks the tokens first. A confirmation consumes the token and then verifies the account, so a re-registration or resend calls `InvalidateActive` before it updates the account or inserts a token; the opposite order can deadlock. The cleanup is the only exception: it locks the account before the tokens and sessions, which is safe because each of those locks uses SKIP LOCKED and never waits. A deadlock (SQLSTATE 40P01) or serialization failure (40001) that still happens is reported by `Transactor.WithinTransaction` and the identity repositories as `outbound.ErrTransactionConflict`; nothing was committed, and the usecase or job may retry the whole operation with backoff while staying idempotent. + ## Frontend The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index e2224c4..f90825c 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -48,14 +48,14 @@ The repository contains a verifiable technical scaffold, not a product. Values b What exists now: - Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, and a 404 for an unknown API route; it does not start ML. -- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, and a transactor with the transactional outbox writer; Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap. +- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, and sqlc-backed identity repositories for accounts, email tokens, and sessions; Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap. - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has a home page, a generated API client, and MSW handlers. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the backend has no Go Kafka client, topics, or readiness check for Kafka. - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. -Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains only the outbox table and no business schema, product usecase and adapter directories contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). +Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table and the identity storage tables (`users`, `email_tokens`, `sessions`) and no other business schema; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). ## Install and work loop @@ -159,6 +159,12 @@ For a local database, export `DATABASE_URL` in your shell and use these targets: The targets run `backend/cmd/migrate` with the same runner, lock, and timeouts as startup. The Makefile contains no connection strings; keep credentials out of committed files. Integration tests apply all migrations to the PostgreSQL container from the shared bootstrap; see [TESTING.md](TESTING.md). +### Identity storage + +Migration `00002_create_identity_tables.sql` creates `users`, `email_tokens`, and `sessions`; the queries are in `backend/db/queries/identity.sql`. The `outbound.UserRepository`, `EmailTokenRepository`, and `SessionRepository` ports are available through `UnitOfWork` inside `Transactor.WithinTransaction` and through `postgres.IdentityStore` outside a transaction. Nothing in bootstrap or the HTTP handlers uses them yet; registration, verification, login, and the session principal come in later tasks. + +The database never receives a password, a raw email token, or a raw session token. Repositories take a `domain.PasswordHash` (an Argon2id v19 PHC string) and a `domain.SecretTokenHash` (the SHA-256 of a `domain.SecretToken`). Email addresses are ASCII only for now; IDN and SMTPUTF8 support is future work that needs IDNA ToASCII for the domain. `SecretToken`, `PasswordHash`, and `EmailAddress` redact themselves in `fmt` and `slog` output; `SecretToken.Reveal` and `EmailAddress.Address` return the real values where they are needed. Every stored time comes from the application clock that the caller passes, and PostgreSQL keeps microseconds. A deadlock or serialization failure is reported as `outbound.ErrTransactionConflict`, and the caller may retry the whole operation. The schema and its decisions are described in [ARCHITECTURE.md](ARCHITECTURE.md#identity-storage). + ## Go readability - Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 43f1173..03882c7 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -36,7 +36,7 @@ Security checks run separately: `make -C security check` scans source/dependenci ## Current scaffold coverage -Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or real model inference to validate as product behavior. +Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows and no real model inference to validate as product behavior. API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 6f2de92..5dce2b7 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -107,10 +107,10 @@ backend/ cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку config/ общая конфигурация runtime internal/ - domain/ плоский пакет; DomainEvent для outbox + domain/ плоский пакет; DomainEvent, типы identity usecase/health/ operational readiness usecase port/inbound/ inbound граница readiness - port/outbound/ границы readiness, кеша, объектного хранилища, транзакции и outbox + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox и identity adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -119,22 +119,22 @@ backend/ router.go сборка chi router adapter/secondary/ ml/api/ generated client из backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, запись outbox, health check + postgres/ pool, migrator, transactor, запись outbox, репозитории identity, health check postgres/sqlc/ generated SQL adapter redis/ адаптер кеша и проверка Redis seaweedfs/ S3-адаптер и проверка bucket prometheus/ ограниченные Go/process и request metrics bootstrap/ конфигурация, wiring, lifecycle, shutdown - db/ встроенные миграции и SQL-запросы; таблица outbox, продуктовой схемы пока нет + db/ встроенные миграции и SQL-запросы; таблицы outbox и identity codegen/ конфигурация ogen и sqlc pkg/ резерв для обоснованных общих технических helpers ``` -Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. +Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`. `domain/`, продуктовые `usecase/`, адаптеры почты и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. -Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, Redis cache adapter и S3-адаптер SeaweedFS. Аккаунты, резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, Redis cache adapter и S3-адаптер SeaweedFS. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. @@ -227,6 +227,34 @@ contact_grant относится к паре кандидат-компания ТЗ ссылается на 152-ФЗ. Система должна иметь раздельные согласия на обработку и публикацию, отзыв, контроль передачи документов ML и сроки хранения/удаления. Описание архитектуры не является подтверждением юридического соответствия. До работы с настоящими данными нужны согласованные условия хранения и обработки; демонстрация использует синтетические профили. +### Хранение identity + +Реализовано только хранение (TASK-051): миграция `backend/db/migrations/00002_create_identity_tables.sql`, запросы в `backend/db/queries/identity.sql`, доменные типы в `backend/internal/domain/`, порты в `backend/internal/port/outbound/identity.go` и адаптер на sqlc в `backend/internal/adapter/secondary/postgres/identity.go`. Регистрация, подтверждение, вход и сессии из [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf) запланированы (TASK-053 - TASK-056); ни один usecase или обработчик это хранение пока не использует. + +- `users`: UUIDv7 `id`; `email` - форма для доставки (ASCII без пробелов по краям, регистр как при вводе, возвращается в `Account.email`), и `email_normalized` - уникальный ключ сравнения (тот же адрес, в котором A-Z переведены в нижний регистр); `password_hash` - строка PHC Argon2id v19; `scenario` и `onboarding_step` с CHECK, что шаг относится к сценарию; nullable `email_verified_at`; `registration_version`; `last_registered_at` с частичным индексом по неподтвержденным аккаунтам для запланированной очистки через 7 дней; оптимистичная `version`; `created_at` и `updated_at`. Форма для доставки хранится, потому что RFC 5321 допускает local part с учетом регистра: письмо уходит на адрес в введенном виде, а уникальность не учитывает регистр. +- `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. CHECK допускает не больше одного из consumed и invalidated. +- `sessions`: UUIDv7 `id`, который не покидает сервер, `token_hash` (SHA-256 значения cookie, уникальный), `user_id`, `created_at`, `last_seen_at`, абсолютный `expires_at` и `revoked_at`. IP-адрес и user agent не хранятся. +- Токены и сессии ссылаются на `users` с `ON DELETE CASCADE`. Таблицы согласий, запланированные в TASK-062, могут ссылаться на `users.id` так же. CHECK-ограничения дублируют доменные правила как последнюю защиту: ASCII-адрес и его ключ, формат PHC и времена (подтверждения, погашения, аннулирования и отзыва) не раньше `created_at`. + +Решения: + +- Email-адреса принимаются только в ASCII, потому что отправка почты не поддерживает SMTPUTF8. `domain.NewEmailAddress` отклоняет любой символ вне ASCII, включая гомоглифы и полноширинные формы, с `ErrInvalidEmailAddress`; обработчик регистрации должен отвечать на это 400 `validation_failed` независимо от того, существует ли аккаунт. Интернационализированные домены принимаются только в punycode (`xn--...`). Ключ переводит в нижний регистр только A-Z; база проверяет его через `translate()`, который, в отличие от `lower()`, не зависит от collation. Поддержка Unicode-адресов - будущая работа: нужны IDNA ToASCII для домена, правило для Unicode в local part и доставка через SMTPUTF8. Строки читаются через `domain.RestoreEmailAddress`, который проверяет только соответствие адреса и ключа, поэтому более строгое правило в будущем не сделает существующие аккаунты нечитаемыми. +- База хранит хеши, а не пароли и исходные токены. Токен несет 256 бит из crypto/rand, поэтому SHA-256 без соли нельзя обратить перебором, а поиск остается одним обращением к индексу; для паролей нужен медленный KDF Argon2id. `bytea` вдвое компактнее hex-текста, допускает точную проверку длины и не имеет вариантов регистра. `domain.SecretToken`, `domain.PasswordHash` и `domain.EmailAddress` скрывают значение в выводе `fmt` (для любого verb) и `slog`, поэтому при печати `domain.User` не видны ни адрес, ни хеш; настоящие значения возвращают явные методы доступа. Неотображенные ошибки PostgreSQL из репозиториев identity сохраняют только SQLSTATE и имя ограничения, потому что текст и detail ошибки могут содержать значения строки. +- Колонки с перечислимыми значениями - text с CHECK, а не enum-типы PostgreSQL. Новый сценарий, шаг или назначение заменяет одно ограничение в обратимой миграции; значение enum нельзя удалить и нельзя использовать в транзакции, которая его добавила. +- Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, поэтому сроки и проверки по ним используют одни часы. Репозитории отклоняют нулевое время. +- Колонки для CSRF нет. `GetCurrentSession` должен вернуть CSRF-токен сессии после перезагрузки страницы, а сохраненный хеш не позволяет его восстановить. TASK-056 может выводить токен из токена сессии с серверным ключом, что не требует хранения, или добавить колонку аддитивной миграцией. + +Что гарантируют порты: + +- `UserRepository.Create` возвращает `ErrEmailTaken` для повторного ключа. `UpdateRegistration` сохраняет результат `domain.User.ReRegister`, только если сохраненная `version` совпадает и email не подтвержден; тот же запрос увеличивает `version` и `registration_version` на единицу, поэтому версию регистрации не выбирает вызывающий код. `MarkEmailVerified` применяется только к неподтвержденному аккаунту с указанной версией регистрации. В остальных случаях оба возвращают `ErrUserVersionConflict`. +- `EmailTokenRepository.Consume` - один `UPDATE ... RETURNING`, который требует непогашенный, неаннулированный и неистекший токен. Параллельные вызовы ждут в очереди на блокировку строки токена; при READ COMMITTED каждый ожидающий заново проверяет строку после завершения владельца блокировки, поэтому успешен ровно один, а если владелец откатился, ожидающий еще может погасить токен. Неудача сообщается как `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (заменен или выдан для более ранней версии регистрации) или `ErrEmailTokenExpired`. `InvalidateActive` помечает все прежние токены пользователя с этим назначением. +- Consume сравнивает версию регистрации токена с аккаунтом только в том виде, в каком его прочитал запрос, без блокировки, поэтому не видит повторную регистрацию, зафиксированную сразу после него. Привязка токена к текущей регистрации поэтому соблюдается, только если подтверждение вызывает `MarkEmailVerified(token.UserID, token.RegistrationVersion)` в той же транзакции и откатывает ее при `ErrUserVersionConflict`; откат возвращает и токен, который затем считается замененным. Usecase подтверждения (TASK-054) переводит этот исход в `verification_token_invalid`. +- `SessionRepository.FindActive` и `Touch` получают таймаут простоя от вызывающего кода и принимают только неотозванную сессию до ее абсолютного срока и в пределах таймаута простоя. `Touch` записывает `last_seen_at`, только если сохраненное значение старше более чем на минуту, поэтому частые запросы не переписывают строку, а таймаут простоя может завершить сессию на минуту раньше; `Touch` не сдвигает `last_seen_at` назад и не возобновляет завершенную сессию. `Revoke` и `RevokeAllForUser` устанавливают `revoked_at`. +- `DeleteUnverifiedRegisteredBefore` удаляет одну пачку неподтвержденных аккаунтов, начиная со старых, и никогда не ждет блокировку. Он блокирует аккаунты-кандидаты, их токены и сессии через `FOR UPDATE SKIP LOCKED` и пропускает каждый аккаунт, у которого строка аккаунта или любая строка токена или сессии заблокирована другой транзакцией, например повторной регистрацией, повторной отправкой или подтверждением; пропущенные аккаунты остаются до следующего запуска. +- `postgres.IdentityStore` выполняет те же репозитории вне транзакции. При вызове с контекстом из callback `Transactor` он возвращает `ErrNestedTransaction`, а не фиксирует изменения через отдельное соединение. +- Нарушения уникальности и внешних ключей переводятся в `ErrEmailTaken`, `ErrTokenHashConflict` и `ErrUserNotFound` по SQLSTATE и имени ограничения, а не по тексту ошибки. +- Порядок блокировок: операция, которая меняет и аккаунт, и его токены, сначала блокирует токены. Подтверждение гасит токен, а затем подтверждает аккаунт, поэтому повторная регистрация или повторная отправка вызывает `InvalidateActive` до обновления аккаунта или вставки токена; обратный порядок может привести к взаимной блокировке. Единственное исключение - очистка: она блокирует аккаунт раньше токенов и сессий, и это безопасно, потому что каждая из этих блокировок берется с SKIP LOCKED и никогда не ждет. Если взаимная блокировка (SQLSTATE 40P01) или ошибка сериализации (40001) все же случится, `Transactor.WithinTransaction` и репозитории identity сообщают ее как `outbound.ErrTransactionConflict`; ничего не зафиксировано, и usecase или job может повторить всю операцию с паузой, оставаясь идемпотентным. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index f5dcccf..88a3f35 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -48,14 +48,14 @@ Frontend зависимости выбираются из актуальных s Что есть сейчас: - Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose и 404 для неизвестного API маршрута; ML он не запускает. -- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, и transactor с записью transactional outbox; Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. +- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox и репозитории identity на sqlc для аккаунтов, email-токенов и сессий; Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. - OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть домашняя страница, generated API client и MSW handlers. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness. - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть только таблица outbox и нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox и таблицы хранения identity (`users`, `email_tokens`, `sessions`), другой бизнес-схемы нет; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -159,6 +159,12 @@ goose выполняет каждую миграцию в отдельной т Цели запускают `backend/cmd/migrate` с тем же runner, блокировкой и таймаутами, что и старт сервиса. Makefile не содержит строк подключения; не храните учетные данные в коммитах. Интеграционные тесты применяют все миграции к контейнеру PostgreSQL из общего bootstrap; см. [TESTING.md](TESTING.md). +### Хранение identity + +Миграция `00002_create_identity_tables.sql` создает `users`, `email_tokens` и `sessions`; запросы лежат в `backend/db/queries/identity.sql`. Порты `outbound.UserRepository`, `EmailTokenRepository` и `SessionRepository` доступны через `UnitOfWork` внутри `Transactor.WithinTransaction` и через `postgres.IdentityStore` вне транзакции. Bootstrap и HTTP-обработчики их пока не используют; регистрация, подтверждение, вход и principal сессии появятся в следующих задачах. + +База данных никогда не получает пароль, исходный email-токен или исходный токен сессии. Репозитории принимают `domain.PasswordHash` (строку PHC Argon2id v19) и `domain.SecretTokenHash` (SHA-256 от `domain.SecretToken`). Email-адреса пока принимаются только в ASCII; поддержка IDN и SMTPUTF8 - будущая работа, для которой нужен IDNA ToASCII для домена. `SecretToken`, `PasswordHash` и `EmailAddress` скрывают значение в выводе `fmt` и `slog`; `SecretToken.Reveal` и `EmailAddress.Address` возвращают настоящие значения там, где они нужны. Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, а PostgreSQL хранит микросекунды. Взаимная блокировка или ошибка сериализации сообщается как `outbound.ErrTransactionConflict`, и вызывающий код может повторить всю операцию. Схема и принятые решения описаны в [ARCHITECTURE.md](ARCHITECTURE.md#хранение-identity). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 23c0213..e1e86ea 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -36,7 +36,7 @@ make -C ml check-generated использует datamodel-code-generator --check ## Что покрывает текущий каркас -Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат. +Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами и нет реального model inference, которые можно было бы проверить как бизнес-результат. API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub.