feat(identity): store users, email tokens, and sessions
This commit is contained in:
1 parent
15e2e50561
commit
e7d0d92ef9
30 files changed
+4792
-32
No files matched your search
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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) }
|
||||
@@ -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 <candidate@example.com>",
|
||||
"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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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{} }
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user