225 lines
8.9 KiB
Go
225 lines
8.9 KiB
Go
package identity
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
const (
|
|
// DefaultTokenHourlyLimit bounds confirmation attempts for one token.
|
|
DefaultTokenHourlyLimit = 5
|
|
|
|
verificationEventType = "identity.email_verified"
|
|
verificationAggregateType = "user"
|
|
verificationSchemaVersion = 1
|
|
)
|
|
|
|
// ConfirmationDependencies are the collaborators of EmailConfirmation.
|
|
// Every field is required except Metrics.
|
|
type ConfirmationDependencies struct {
|
|
Transactor outbound.Transactor
|
|
Tokens outbound.EmailTokenRepository
|
|
Credentials *Credentials
|
|
Limiter outbound.RateLimiter
|
|
Keyring *Keyring
|
|
Clock func() time.Time
|
|
Metrics RateLimitMetrics
|
|
}
|
|
|
|
// ConfirmationSettings contains the attempt limits for one token and one
|
|
// client. The client limit matches registration and resend.
|
|
type ConfirmationSettings struct {
|
|
TokenHourlyLimit int64
|
|
ClientHourlyLimit int64
|
|
}
|
|
|
|
// EmailConfirmation confirms the address and applies the credentials of the
|
|
// registration carried by its token. It holds no mutable state.
|
|
type EmailConfirmation struct {
|
|
deps ConfirmationDependencies
|
|
settings ConfirmationSettings
|
|
}
|
|
|
|
// NewEmailConfirmation checks the collaborators and limits once, so a wiring
|
|
// mistake fails at startup rather than on the first confirmation.
|
|
func NewEmailConfirmation(deps ConfirmationDependencies, settings ConfirmationSettings) (*EmailConfirmation, error) {
|
|
switch {
|
|
case deps.Transactor == nil, deps.Tokens == nil, deps.Credentials == nil,
|
|
deps.Limiter == nil, deps.Keyring == nil, deps.Clock == nil:
|
|
return nil, errors.New("identity.NewEmailConfirmation - every dependency must be set")
|
|
case settings.TokenHourlyLimit < 1, settings.ClientHourlyLimit < 1:
|
|
return nil, errors.New("identity.NewEmailConfirmation - confirmation limits must be positive")
|
|
}
|
|
return &EmailConfirmation{deps: deps, settings: settings}, nil
|
|
}
|
|
|
|
// ConfirmCommand is the content of an email confirmation request.
|
|
type ConfirmCommand struct {
|
|
Token string
|
|
Password string
|
|
// ClientKey is the opaque limiter key of the client network address.
|
|
ClientKey string
|
|
}
|
|
|
|
// ConfirmationResult is the saved destination after the user signs in.
|
|
type ConfirmationResult struct {
|
|
Scenario domain.Scenario
|
|
OnboardingStep domain.OnboardingStep
|
|
}
|
|
|
|
// Confirm verifies the registration password outside the database
|
|
// transaction, then rechecks and consumes the token with the account and its
|
|
// registration C1 in one transaction.
|
|
func (confirmation *EmailConfirmation) Confirm(ctx context.Context, command ConfirmCommand) (ConfirmationResult, error) {
|
|
const location = "EmailConfirmation.Confirm"
|
|
if err := confirmation.takeAttempt(ctx, command); err != nil {
|
|
return ConfirmationResult{}, fmt.Errorf("%s - limit confirmation: %w", location, err)
|
|
}
|
|
token, err := domain.ParseSecretToken(command.Token)
|
|
if err != nil {
|
|
return ConfirmationResult{}, fmt.Errorf("%s - parse token: %w", location, ErrVerificationTokenInvalid)
|
|
}
|
|
prepared, err := confirmation.deps.Tokens.FindByHash(ctx, token.Hash(), domain.EmailTokenPurposeEmailVerification)
|
|
if errors.Is(err, outbound.ErrEmailTokenNotFound) || errors.Is(err, outbound.ErrEmailTokenInvalidated) {
|
|
return ConfirmationResult{}, fmt.Errorf("%s - read token: %w", location, ErrVerificationTokenInvalid)
|
|
}
|
|
if err != nil {
|
|
return ConfirmationResult{}, fmt.Errorf("%s - read token: %w", location, err)
|
|
}
|
|
if prepared.ConsumedAt != nil || prepared.InvalidatedAt != nil || prepared.Pending == nil {
|
|
return ConfirmationResult{}, fmt.Errorf("%s - token cannot confirm a registration: %w", location, ErrVerificationTokenInvalid)
|
|
}
|
|
if !prepared.ExpiresAt.After(confirmation.deps.Clock()) {
|
|
return ConfirmationResult{}, fmt.Errorf("%s - check token expiry: %w", location, ErrVerificationTokenExpired)
|
|
}
|
|
if err := confirmation.deps.Credentials.VerifyLoginPassword(ctx, command.Password, prepared.Pending.PasswordHash); err != nil {
|
|
if errors.Is(err, outbound.ErrPasswordMismatch) || errors.Is(err, domain.ErrInvalidPassword) {
|
|
return ConfirmationResult{}, fmt.Errorf("%s - verify registration password: %w", location, ErrVerificationTokenInvalid)
|
|
}
|
|
return ConfirmationResult{}, fmt.Errorf("%s - verify registration password: %w", location, err)
|
|
}
|
|
|
|
var result ConfirmationResult
|
|
err = confirmation.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
return confirmation.confirmInTransaction(ctx, unit, token.Hash(), prepared, &result)
|
|
})
|
|
if err != nil {
|
|
return ConfirmationResult{}, fmt.Errorf("%s - confirm registration: %w", location, confirmationOutcomeError(err))
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func confirmationOutcomeError(err error) error {
|
|
switch {
|
|
case errors.Is(err, outbound.ErrEmailTokenExpired):
|
|
return ErrVerificationTokenExpired
|
|
case errors.Is(err, outbound.ErrEmailTokenNotFound),
|
|
errors.Is(err, outbound.ErrEmailTokenConsumed),
|
|
errors.Is(err, outbound.ErrEmailTokenInvalidated),
|
|
errors.Is(err, outbound.ErrConsentNotFound),
|
|
errors.Is(err, outbound.ErrUserVersionConflict),
|
|
errors.Is(err, ErrVerificationTokenInvalid):
|
|
return ErrVerificationTokenInvalid
|
|
default:
|
|
return err
|
|
}
|
|
}
|
|
|
|
func (confirmation *EmailConfirmation) takeAttempt(ctx context.Context, command ConfirmCommand) error {
|
|
const location = "EmailConfirmation.takeAttempt"
|
|
type attemptCheck struct {
|
|
key string
|
|
scope string
|
|
rule outbound.RateLimitRule
|
|
}
|
|
checks := make([]attemptCheck, 0, 2)
|
|
if command.ClientKey != "" {
|
|
checks = append(checks, attemptCheck{
|
|
key: confirmation.deps.Keyring.ClientBucket(command.ClientKey),
|
|
scope: ScopeClient,
|
|
rule: outbound.RateLimitRule{Window: clientWindow, Limit: confirmation.settings.ClientHourlyLimit},
|
|
})
|
|
}
|
|
checks = append(checks, attemptCheck{
|
|
key: confirmation.deps.Keyring.VerificationTokenBucket(command.Token),
|
|
scope: ScopeToken,
|
|
rule: outbound.RateLimitRule{Window: time.Hour, Limit: confirmation.settings.TokenHourlyLimit},
|
|
})
|
|
for _, check := range checks {
|
|
decision, err := confirmation.deps.Limiter.Take(ctx, check.key, check.rule)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - take %s limit: %w", location, check.scope, err)
|
|
}
|
|
if !decision.Allowed {
|
|
if confirmation.deps.Metrics != nil {
|
|
confirmation.deps.Metrics.ObserveIdentityRateLimited(check.scope)
|
|
}
|
|
return &RateLimitedError{RetryAfter: decision.RetryAfter}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (confirmation *EmailConfirmation) confirmInTransaction(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
hash domain.SecretTokenHash,
|
|
prepared domain.EmailToken,
|
|
result *ConfirmationResult,
|
|
) error {
|
|
const location = "EmailConfirmation.confirmInTransaction"
|
|
consumedAt := confirmation.deps.Clock()
|
|
token, err := unit.EmailTokens().Consume(ctx, hash, domain.EmailTokenPurposeEmailVerification, consumedAt)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - consume token: %w", location, err)
|
|
}
|
|
if !token.ExpiresAt.After(confirmation.deps.Clock()) {
|
|
return fmt.Errorf("%s - token expired while waiting: %w", location, outbound.ErrEmailTokenExpired)
|
|
}
|
|
if token.Pending == nil || prepared.Pending == nil || !samePendingRegistration(*prepared.Pending, *token.Pending) {
|
|
return fmt.Errorf("%s - pending registration does not match: %w", location, ErrVerificationTokenInvalid)
|
|
}
|
|
if token.ConsumedAt == nil {
|
|
return fmt.Errorf("%s - consumed token has no consumption time: %w", location, domain.ErrInvalidEmailToken)
|
|
}
|
|
user, err := unit.Users().ConfirmEmail(ctx, token.UserID, token.RegistrationVersion, *token.Pending, *token.ConsumedAt)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - apply pending registration: %w", location, err)
|
|
}
|
|
if !token.ExpiresAt.After(confirmation.deps.Clock()) {
|
|
return fmt.Errorf("%s - token expired while waiting for account lock: %w", location, outbound.ErrEmailTokenExpired)
|
|
}
|
|
if _, err := unit.ConsentLedger().LockRegistration(ctx, token.UserID, token.RegistrationVersion); err != nil {
|
|
return fmt.Errorf("%s - lock registration C1: %w", location, err)
|
|
}
|
|
if !token.ExpiresAt.After(confirmation.deps.Clock()) {
|
|
return fmt.Errorf("%s - token expired while waiting for consent lock: %w", location, outbound.ErrEmailTokenExpired)
|
|
}
|
|
event, err := domain.NewDomainEvent(domain.DomainEventInput{
|
|
EventType: verificationEventType,
|
|
SchemaVersion: verificationSchemaVersion,
|
|
AggregateType: verificationAggregateType,
|
|
AggregateID: user.ID,
|
|
AggregateVersion: user.Version,
|
|
Payload: []byte("{}"),
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build verification event: %w", location, err)
|
|
}
|
|
if err := unit.Outbox().Append(ctx, event); err != nil {
|
|
return fmt.Errorf("%s - append verification event: %w", location, err)
|
|
}
|
|
*result = ConfirmationResult{Scenario: user.Scenario, OnboardingStep: user.OnboardingStep}
|
|
return nil
|
|
}
|
|
|
|
func samePendingRegistration(left, right domain.PendingRegistration) bool {
|
|
return left.PasswordHash.PHC() == right.PasswordHash.PHC() &&
|
|
left.Scenario == right.Scenario && left.OnboardingStep == right.OnboardingStep
|
|
}
|