Files
lincodex/backend/internal/port/outbound/identity.go
T

257 lines
13 KiB
Go

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 ConfirmEmail
// 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, sessions, and deliveries; 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
IdempotencyRecords() IdempotencyRepository
}
// 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.
//
// The same statement deletes the C1 records with the source
// registration that the earlier registration of this account stored,
// because the earlier registrant's consent must never stand for the new
// one. The registration usecase must record the new C1 with
// ConsentLedger().Grant in the same transaction; a version conflict
// deletes nothing.
UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error)
// AdvanceRegistration starts a new registration of an unverified account
// without changing its password hash, scenario, or onboarding step: the
// new registration carries them on its token (see
// domain.PendingRegistration). It applies only when the stored version
// still equals expectedVersion and the email is unverified, advances
// Version and RegistrationVersion by one in the same statement, sets the
// registration time, and deletes the C1 records with the source
// registration of the earlier registration like UpdateRegistration does;
// the caller grants the new C1 strictly after it. Otherwise it returns
// ErrUserVersionConflict.
AdvanceRegistration(ctx context.Context, id uuid.UUID, expectedVersion int64, at time.Time) (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. It keeps the
// storage operation available to existing callers; registration-token
// confirmation uses ConfirmEmail to apply pending credentials as well.
MarkEmailVerified(ctx context.Context, id uuid.UUID, registrationVersion int64, at time.Time) (domain.User, error)
// ConfirmEmail applies the pending credentials of one registration and
// verifies the account only while that registration version is current.
// It returns ErrUserVersionConflict when the account is already verified
// or its registration has changed.
ConfirmEmail(ctx context.Context, id uuid.UUID, registrationVersion int64, pending domain.PendingRegistration, 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, sessions, mail deliveries, and consent records, and
// returns how many it deleted. It never waits for a lock: an account
// whose row, token, session, delivery, or consent record is locked by
// another transaction is skipped and stays for the next run. A consent
// recorded for a candidate account after the statement started fails the
// restricting foreign key; the run then returns an error matching
// ErrTransactionConflict, deletes nothing, and may be repeated. 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 {
// FindByHash returns the token row, including pending registration data,
// whether or not it has already ended. It returns ErrEmailTokenNotFound
// when the hash or purpose does not match, and ErrEmailTokenInvalidated
// when its registration version is no longer current. Callers that use this
// read to prepare work must recheck the token with Consume in their transaction.
FindByHash(ctx context.Context, hash domain.SecretTokenHash, purpose domain.EmailTokenPurpose) (domain.EmailToken, error)
// Insert returns ErrUserNotFound when the account does not exist and
// ErrTokenHashConflict for a duplicate hash.
Insert(ctx context.Context, token domain.EmailToken) error
// LatestPending returns the pending credentials of the newest token that
// the registration version of the user has, or false when none carries
// any. A resend copies them to its new token.
LatestPending(ctx context.Context, userID uuid.UUID, registrationVersion int64) (domain.PendingRegistration, bool, 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, clears its
// pending registration data, and returns the token with that data from
// before the update. 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().ConfirmEmail(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)
}
// IdempotencyRetention is how long the replay record of a command with an
// Idempotency-Key lives, as the public contract states. After it the key may
// be accepted as new.
const IdempotencyRetention = 24 * time.Hour
// IdempotencyDigestSize is the size of the HMAC-SHA-256 values that identify
// and fingerprint a command.
const IdempotencyDigestSize = 32
// IdempotencyRecord is the replay record of a committed command. Both digests
// are HMAC-SHA-256 values computed with a server secret; the record holds
// neither the key, the email, nor the request body.
type IdempotencyRecord struct {
// Scope identifies the operation, the key, and the principal; for an
// anonymous operation the principal is the normalized email.
Scope [IdempotencyDigestSize]byte
// Fingerprint identifies the request that the key was first used with.
Fingerprint [IdempotencyDigestSize]byte
CreatedAt time.Time
ExpiresAt time.Time
}
// IdempotencyRepository stores the replay records of commands. Reserve runs
// in the transaction of the command it guards, so a stored record always
// belongs to a committed command.
type IdempotencyRepository interface {
// Reserve stores record unless a live record with the same scope exists.
// For a stored record it returns it with created true. For a live record
// it returns that record with created false and stores nothing; the
// caller compares the fingerprints to decide between a replay and a
// reused key. A concurrent Reserve with the same scope waits until the
// transaction of the first ends. A record past ExpiresAt is replaced.
// Every method that takes a time rejects the zero time.
Reserve(ctx context.Context, record IdempotencyRecord) (stored IdempotencyRecord, created bool, err error)
// Find returns the live record with the scope at the given time, or
// ErrIdempotencyRecordNotFound.
Find(ctx context.Context, scope [IdempotencyDigestSize]byte, at time.Time) (IdempotencyRecord, error)
// PurgeExpired deletes at most limit records that expired at or before
// the given time and returns how many it deleted. It never waits for a
// locked record.
PurgeExpired(ctx context.Context, at time.Time, limit int32) (int64, error)
}
// ErrIdempotencyRecordNotFound reports that no live record has the scope.
var ErrIdempotencyRecordNotFound = errors.New("idempotency record not found")