package identity import ( "context" "errors" "fmt" "time" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) const ( // codePointer is the JSON Pointer of the code field in a request body. codePointer = "/code" // addressCodeWindow is the window of the per-address limit. It is the // window of the login limit, so both draw on one counter. addressCodeWindow = time.Hour ) // ConfirmCodeCommand is the content of a confirmation by the six-digit code of // a verification message, unvalidated. type ConfirmCodeCommand struct { Email string Code string Password string // ClientKey is the opaque limiter key of the client network address. ClientKey string } // ConfirmByCode verifies the address with the code of its verification // message. It checks the same things as the link confirmation: the open token // of the current registration, the password chosen for that registration, and // the consumption of the token in one transaction. The code also has its own // expiry and attempt limit. // // Every refusal is ErrVerificationTokenInvalid, whatever its cause: an unknown // address, no open code, a wrong code or password, an expired code, or a burned // token. The answer then does not reveal which addresses have a pending // registration. Each failed attempt against an open code is counted in the // token row; the attempt that reaches the limit burns the token, so both the // code and the link stop working. // // The password is checked on every branch, with the same hashing work, so the // time of a refusal does not depend on whether the address has an account. func (confirmation *EmailConfirmation) ConfirmByCode(ctx context.Context, command ConfirmCodeCommand) (ConfirmationResult, error) { const location = "EmailConfirmation.ConfirmByCode" email, err := domain.NewEmailAddress(command.Email) if err != nil { return ConfirmationResult{}, fmt.Errorf("%s - validate email: %w", location, invalidField(emailPointer, err)) } code, err := domain.ParseVerificationCode(command.Code) if err != nil { return ConfirmationResult{}, fmt.Errorf("%s - validate code: %w", location, invalidField(codePointer, err)) } if err := confirmation.takeCodeAttempt(ctx, email, command.ClientKey); err != nil { return ConfirmationResult{}, fmt.Errorf("%s - limit code confirmation: %w", location, err) } open, found, err := confirmation.findOpenCode(ctx, email) if err != nil { return ConfirmationResult{}, fmt.Errorf("%s - read open code: %w", location, err) } passwordMatches, err := confirmation.codePasswordMatches(ctx, command.Password, open, found) if err != nil { return ConfirmationResult{}, fmt.Errorf("%s - verify registration password: %w", location, err) } now := confirmation.deps.Clock() if !found || !passwordMatches || !codeMatches(confirmation.deps.Keyring, code, open, now) { if found { if _, err := confirmation.deps.Tokens.RecordFailedCodeAttempt(ctx, open.ID, now); err != nil { return ConfirmationResult{}, fmt.Errorf("%s - count failed attempt: %w", location, err) } } return ConfirmationResult{}, fmt.Errorf("%s - code does not confirm the registration: %w", location, ErrVerificationTokenInvalid) } var result ConfirmationResult err = confirmation.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return confirmation.confirmInTransaction(ctx, unit, open.TokenHash, open, &result) }) if err != nil { return ConfirmationResult{}, fmt.Errorf("%s - confirm registration: %w", location, codeOutcomeError(err)) } return result, nil } // takeCodeAttempt counts the request against the client limit, when the request // has a client key, and against the normalized address. The address counter // sees every request, whether or not an account exists. func (confirmation *EmailConfirmation) takeCodeAttempt(ctx context.Context, email domain.EmailAddress, clientKey string) error { const location = "EmailConfirmation.takeCodeAttempt" if clientKey != "" { err := takeRateLimit(ctx, confirmation.deps.Limiter, confirmation.deps.Metrics, ScopeClient, confirmation.deps.Keyring.ClientBucket(clientKey), outbound.RateLimitRule{Window: clientWindow, Limit: confirmation.settings.ClientHourlyLimit}) if err != nil { return fmt.Errorf("%s - take client limit: %w", location, err) } } err := takeRateLimit(ctx, confirmation.deps.Limiter, confirmation.deps.Metrics, ScopeAddress, confirmation.deps.Keyring.EmailBucket(email.Normalized()), outbound.RateLimitRule{Window: addressCodeWindow, Limit: confirmation.settings.EmailHourlyLimit}) if err != nil { return fmt.Errorf("%s - take address limit: %w", location, err) } return nil } // takeRateLimit counts one request against one rule and reports a refusal as // *RateLimitedError, after it notifies the metrics of the scope. func takeRateLimit( ctx context.Context, limiter outbound.RateLimiter, metrics RateLimitMetrics, scope, bucket string, rule outbound.RateLimitRule, ) error { decision, err := limiter.Take(ctx, bucket, rule) if err != nil { return fmt.Errorf("take rate limit: %w", err) } if !decision.Allowed { if metrics != nil { metrics.ObserveIdentityRateLimited(scope) } return &RateLimitedError{RetryAfter: decision.RetryAfter} } return nil } // findOpenCode returns the open code token of the address and whether one // exists. The absence of a token is not an error: it is one of the refusals. func (confirmation *EmailConfirmation) findOpenCode(ctx context.Context, email domain.EmailAddress) (domain.EmailToken, bool, error) { token, err := confirmation.deps.Tokens.FindOpenCodeByAddress(ctx, email) switch { case errors.Is(err, outbound.ErrEmailTokenNotFound): return domain.EmailToken{}, false, nil case err != nil: return domain.EmailToken{}, false, fmt.Errorf("EmailConfirmation.findOpenCode - read token: %w", err) } return token, true, nil } // codePasswordMatches reports whether password is the one chosen for the // registration of the open code. With no open code, or a password outside the // login bounds, it spends the same hashing work on a dummy hash and reports no // match; the work does not depend on whether the address has an account. func (confirmation *EmailConfirmation) codePasswordMatches( ctx context.Context, password string, open domain.EmailToken, found bool, ) (bool, error) { credentials := confirmation.deps.Credentials if _, err := domain.ParseLoginPassword(password); err != nil || !found || open.Pending == nil { err := credentials.VerifyDummyLoginPassword(ctx, password) if err != nil && !errors.Is(err, outbound.ErrPasswordMismatch) { return false, fmt.Errorf("EmailConfirmation.codePasswordMatches - verify dummy hash: %w", err) } return false, nil } err := credentials.VerifyLoginPassword(ctx, password, open.Pending.PasswordHash) switch { case err == nil: return true, nil case errors.Is(err, outbound.ErrPasswordMismatch), errors.Is(err, domain.ErrInvalidPassword): return false, nil default: return false, fmt.Errorf("EmailConfirmation.codePasswordMatches - verify password: %w", err) } } // codeMatches reports whether code is the open code of the token, and whether // both the code and the token are still within their validity. It is false when // there is no open code. func codeMatches(keyring *Keyring, code domain.VerificationCode, open domain.EmailToken, now time.Time) bool { if open.Code == nil || !open.Code.ExpiresAt.After(now) || !open.ExpiresAt.After(now) { return false } return keyring.VerifyVerificationCode(code, open.Code.Hash) } // codeOutcomeError maps the outcome of the code transaction to the single // refusal of the code operation, so an expired token is not reported apart. func codeOutcomeError(err error) error { if errors.Is(err, ErrVerificationTokenExpired) { return ErrVerificationTokenInvalid } return confirmationOutcomeError(err) }