feat(identity): confirm the email address with a six-digit code from the message
This commit is contained in:
1 parent
c94434cd09
commit
d365a05c96
87 files changed
+4764
-224
No files matched your search
@@ -0,0 +1,191 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
codeTestSecret = "code confirmation test key with enough entropy"
|
||||
codeTestEmailLimit = 10
|
||||
codeTestClientLimit = 30
|
||||
)
|
||||
|
||||
// codeTestStore models the verification token row that the confirmation
|
||||
// reads and writes: the open code, its failed attempts, and the closing
|
||||
// outcomes of consumption and burning.
|
||||
type codeTestStore struct {
|
||||
outbound.EmailTokenRepository
|
||||
|
||||
token domain.EmailToken
|
||||
missing bool
|
||||
attempts int
|
||||
recorded int
|
||||
closed bool
|
||||
consumed bool
|
||||
invalidated bool
|
||||
}
|
||||
|
||||
func (store *codeTestStore) FindByHash(_ context.Context, hash domain.SecretTokenHash, _ domain.EmailTokenPurpose) (domain.EmailToken, error) {
|
||||
if store.missing || hash != store.token.TokenHash {
|
||||
return domain.EmailToken{}, outbound.ErrEmailTokenNotFound
|
||||
}
|
||||
token := store.token
|
||||
if store.consumed {
|
||||
consumedAt := token.CreatedAt
|
||||
token.ConsumedAt = &consumedAt
|
||||
}
|
||||
if store.invalidated {
|
||||
invalidatedAt := token.CreatedAt
|
||||
token.InvalidatedAt = &invalidatedAt
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (store *codeTestStore) FindOpenCodeByAddress(context.Context, domain.EmailAddress) (domain.EmailToken, error) {
|
||||
if store.missing || store.closed || store.token.Code == nil {
|
||||
return domain.EmailToken{}, outbound.ErrEmailTokenNotFound
|
||||
}
|
||||
return store.token, nil
|
||||
}
|
||||
|
||||
func (store *codeTestStore) RecordFailedCodeAttempt(_ context.Context, id uuid.UUID, _ time.Time) (bool, error) {
|
||||
if store.missing || store.closed || id != store.token.ID {
|
||||
return false, nil
|
||||
}
|
||||
store.recorded++
|
||||
store.attempts++
|
||||
if store.attempts >= domain.VerificationCodeMaxFailedAttempts {
|
||||
store.closed = true
|
||||
store.invalidated = true
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Consume closes the token the way the link path does, so the code and the
|
||||
// link share one consumption.
|
||||
func (store *codeTestStore) Consume(_ context.Context, hash domain.SecretTokenHash, _ domain.EmailTokenPurpose, at time.Time) (domain.EmailToken, error) {
|
||||
switch {
|
||||
case store.missing || hash != store.token.TokenHash:
|
||||
return domain.EmailToken{}, outbound.ErrEmailTokenNotFound
|
||||
case store.consumed:
|
||||
return domain.EmailToken{}, outbound.ErrEmailTokenConsumed
|
||||
case store.invalidated:
|
||||
return domain.EmailToken{}, outbound.ErrEmailTokenInvalidated
|
||||
case !store.token.ExpiresAt.After(at):
|
||||
return domain.EmailToken{}, outbound.ErrEmailTokenExpired
|
||||
}
|
||||
store.closed = true
|
||||
store.consumed = true
|
||||
token := store.token
|
||||
token.ConsumedAt = &at
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// codeTestUnit gives the confirmation the four repositories a successful
|
||||
// transaction uses. Any other accessor panics, which keeps the test honest.
|
||||
type codeTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
store *codeTestStore
|
||||
}
|
||||
|
||||
func (unit codeTestUnit) EmailTokens() outbound.EmailTokenRepository { return unit.store }
|
||||
|
||||
func (unit codeTestUnit) Users() outbound.UserRepository { return codeTestUsers{store: unit.store} }
|
||||
|
||||
func (unit codeTestUnit) ConsentLedger() outbound.ConsentLedger { return codeTestLedger{} }
|
||||
|
||||
func (unit codeTestUnit) Outbox() outbound.OutboxWriter { return codeTestOutbox{} }
|
||||
|
||||
type codeTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
store *codeTestStore
|
||||
}
|
||||
|
||||
func (users codeTestUsers) ConfirmEmail(_ context.Context, id uuid.UUID, _ int64, _ domain.PendingRegistration, at time.Time) (domain.User, error) {
|
||||
return domain.User{
|
||||
ID: id,
|
||||
Scenario: domain.ScenarioCandidate,
|
||||
OnboardingStep: domain.OnboardingStepCandidateConsents,
|
||||
EmailVerifiedAt: &at,
|
||||
Version: 2,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type codeTestLedger struct {
|
||||
outbound.ConsentLedger
|
||||
}
|
||||
|
||||
func (codeTestLedger) LockRegistration(context.Context, uuid.UUID, int64) (domain.ConsentRecord, error) {
|
||||
return domain.ConsentRecord{}, nil
|
||||
}
|
||||
|
||||
type codeTestOutbox struct{}
|
||||
|
||||
func (codeTestOutbox) Append(context.Context, ...domain.DomainEvent) error { return nil }
|
||||
|
||||
type codeTestTransactor struct {
|
||||
unit outbound.UnitOfWork
|
||||
calls int
|
||||
}
|
||||
|
||||
func (transactor *codeTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
|
||||
transactor.calls++
|
||||
return work(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
// codeTestLimiter records every key and refuses when deny is set.
|
||||
type codeTestLimiter struct {
|
||||
keys []string
|
||||
rules [][]outbound.RateLimitRule
|
||||
deny bool
|
||||
}
|
||||
|
||||
func (limiter *codeTestLimiter) Take(_ context.Context, key string, rules ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) {
|
||||
limiter.keys = append(limiter.keys, key)
|
||||
limiter.rules = append(limiter.rules, rules)
|
||||
if limiter.deny {
|
||||
return outbound.RateLimitDecision{Allowed: false, RetryAfter: time.Minute}, nil
|
||||
}
|
||||
return outbound.RateLimitDecision{Allowed: true}, nil
|
||||
}
|
||||
|
||||
type codeFixture struct {
|
||||
now time.Time
|
||||
keyring *Keyring
|
||||
raw domain.SecretToken
|
||||
code domain.VerificationCode
|
||||
store *codeTestStore
|
||||
hasher *countingHasher
|
||||
limiter *codeTestLimiter
|
||||
transactor *codeTestTransactor
|
||||
confirmation *EmailConfirmation
|
||||
}
|
||||
|
||||
func newCodeFixture(t *testing.T) *codeFixture {
|
||||
t.Helper()
|
||||
now := time.Date(2026, time.October, 9, 12, 0, 0, 0, time.UTC)
|
||||
keyring, err := NewKeyring([]byte(codeTestSecret))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, err := domain.ParseVerificationCode("482915")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
passwordHash, err := domain.NewPasswordHash(confirmationTestPasswordHash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := domain.NewPendingRegistration(passwordHash, domain.ScenarioCandidate)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err := domain.NewEmailToken(domain.NewEmailTokenInput{
|
||||
UserID: uuid.New(),
|
||||
Purpose: domain.EmailTokenPurposeEmailVerification,
|
||||
TokenHash: raw.Hash(),
|
||||
RegistrationVersion: 1,
|
||||
IssuedAt: now,
|
||||
Lifetime: 24 * time.Hour,
|
||||
CodeHash: keyring.VerificationCodeDigest(code),
|
||||
CodeLifetime: domain.VerificationCodeLifetime,
|
||||
Pending: &pending,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := &codeTestStore{token: token}
|
||||
hasher := &countingHasher{}
|
||||
limiter := &codeTestLimiter{}
|
||||
transactor := &codeTestTransactor{unit: codeTestUnit{store: store}}
|
||||
confirmation, err := NewEmailConfirmation(ConfirmationDependencies{
|
||||
Transactor: transactor,
|
||||
Tokens: store,
|
||||
Credentials: NewCredentials(hasher),
|
||||
Limiter: limiter,
|
||||
Keyring: keyring,
|
||||
Clock: func() time.Time { return now },
|
||||
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: codeTestClientLimit, EmailHourlyLimit: codeTestEmailLimit})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &codeFixture{
|
||||
now: now, keyring: keyring, raw: raw, code: code, store: store, hasher: hasher,
|
||||
limiter: limiter, transactor: transactor, confirmation: confirmation,
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture *codeFixture) command(code, password string) ConfirmCodeCommand {
|
||||
return ConfirmCodeCommand{Email: "Candidate@Example.com", Code: code, Password: password, ClientKey: "client-key"}
|
||||
}
|
||||
|
||||
func wrongCodeFor(code domain.VerificationCode) string {
|
||||
if code.Reveal() == "000000" {
|
||||
return "000001"
|
||||
}
|
||||
return "000000"
|
||||
}
|
||||
|
||||
func requireInvalidCode(t *testing.T, err error) {
|
||||
t.Helper()
|
||||
if !errors.Is(err, ErrVerificationTokenInvalid) {
|
||||
t.Fatalf("ConfirmByCode() error = %v, want ErrVerificationTokenInvalid", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmByCodeRejectsMalformedFieldsBeforeAnyLookup(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
email string
|
||||
code string
|
||||
pointer string
|
||||
}{
|
||||
{name: "email", email: "not-an-address", code: "482915", pointer: emailPointer},
|
||||
{name: "short code", email: "candidate@example.com", code: "48291", pointer: codePointer},
|
||||
{name: "long code", email: "candidate@example.com", code: "4829156", pointer: codePointer},
|
||||
{name: "letters", email: "candidate@example.com", code: "48291A", pointer: codePointer},
|
||||
{name: "spaces", email: "candidate@example.com", code: " 482915", pointer: codePointer},
|
||||
{name: "empty", email: "candidate@example.com", code: "", pointer: codePointer},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
_, err := fixture.confirmation.ConfirmByCode(context.Background(), ConfirmCodeCommand{
|
||||
Email: test.email, Code: test.code, Password: "correct horse battery staple", ClientKey: "client-key",
|
||||
})
|
||||
var field *InvalidFieldError
|
||||
if !errors.As(err, &field) || field.Pointer != test.pointer {
|
||||
t.Fatalf("ConfirmByCode() error = %v, want invalid field %s", err, test.pointer)
|
||||
}
|
||||
if len(fixture.limiter.keys) != 0 || fixture.store.recorded != 0 || fixture.hasher.verifyCalls+fixture.hasher.dummyCalls != 0 {
|
||||
t.Fatal("a malformed request reached the limiter, the store, or the hasher")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmByCodeChecksTheClientAndAddressLimitsBeforeTheLookup(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
fixture.limiter.deny = true
|
||||
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command("482915", "correct horse battery staple"))
|
||||
var limited *RateLimitedError
|
||||
if !errors.As(err, &limited) || limited.RetryAfter != time.Minute {
|
||||
t.Fatalf("ConfirmByCode() error = %v, want rate limit", err)
|
||||
}
|
||||
if len(fixture.limiter.keys) != 1 || fixture.limiter.keys[0] != fixture.keyring.ClientBucket("client-key") {
|
||||
t.Fatalf("limiter keys = %v, want the client bucket only", fixture.limiter.keys)
|
||||
}
|
||||
fixture.limiter.keys = nil
|
||||
fixture.limiter.rules = nil
|
||||
if _, err := fixture.confirmation.ConfirmByCode(context.Background(), ConfirmCodeCommand{
|
||||
Email: "Candidate@Example.com", Code: "482915", Password: "correct horse battery staple",
|
||||
}); !errors.As(err, &limited) {
|
||||
t.Fatalf("ConfirmByCode() without client key error = %v, want the address rate limit", err)
|
||||
}
|
||||
if got, want := fixture.limiter.keys[0], fixture.keyring.EmailBucket("candidate@example.com"); got != want {
|
||||
t.Fatalf("address bucket = %q, want the normalized address bucket", got)
|
||||
}
|
||||
rule := fixture.limiter.rules[0]
|
||||
if len(rule) != 1 || rule[0].Window != time.Hour || rule[0].Limit != codeTestEmailLimit {
|
||||
t.Fatalf("address rule = %+v, want one hour and the login limit", rule)
|
||||
}
|
||||
if fixture.store.recorded != 0 || fixture.hasher.dummyCalls+fixture.hasher.verifyCalls != 0 {
|
||||
t.Fatal("a refused request reached the store or the hasher")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmByCodeRefusesAnUnknownAddressWithTheSameWork(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
fixture.store.missing = true
|
||||
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
|
||||
requireInvalidCode(t, err)
|
||||
if fixture.hasher.dummyCalls != 1 || fixture.hasher.verifyCalls != 0 {
|
||||
t.Fatalf("hasher calls = dummy %d, verify %d; want one dummy comparison", fixture.hasher.dummyCalls, fixture.hasher.verifyCalls)
|
||||
}
|
||||
if fixture.store.recorded != 0 || fixture.transactor.calls != 0 {
|
||||
t.Fatal("an unknown address counted an attempt or opened a transaction")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmByCodeWrongCodeBurnsTheTokenOnTheFifthAttempt(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
wrong := wrongCodeFor(fixture.code)
|
||||
for attempt := 1; attempt <= domain.VerificationCodeMaxFailedAttempts; attempt++ {
|
||||
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(wrong, "correct horse battery staple"))
|
||||
requireInvalidCode(t, err)
|
||||
if closed := fixture.store.closed; closed != (attempt == domain.VerificationCodeMaxFailedAttempts) {
|
||||
t.Fatalf("after attempt %d the token closed = %v", attempt, closed)
|
||||
}
|
||||
}
|
||||
if fixture.store.recorded != domain.VerificationCodeMaxFailedAttempts {
|
||||
t.Fatalf("counted attempts = %d, want %d", fixture.store.recorded, domain.VerificationCodeMaxFailedAttempts)
|
||||
}
|
||||
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
|
||||
requireInvalidCode(t, err)
|
||||
if fixture.transactor.calls != 0 {
|
||||
t.Fatal("the right code confirmed after the token was burned")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmByCodeWrongPasswordWithTheRightCodeIsRefusedAndCounted(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
fixture.hasher.verifyErr = outbound.ErrPasswordMismatch
|
||||
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "a wrong password for this registration"))
|
||||
requireInvalidCode(t, err)
|
||||
if fixture.hasher.verifyCalls != 1 || fixture.store.recorded != 1 || fixture.transactor.calls != 0 {
|
||||
t.Fatalf("verify %d, counted %d, transactions %d", fixture.hasher.verifyCalls, fixture.store.recorded, fixture.transactor.calls)
|
||||
}
|
||||
if fixture.store.closed {
|
||||
t.Fatal("one wrong password closed the token")
|
||||
}
|
||||
}
|
||||
|
||||
// An attacker who registered someone else's address knows the password of the
|
||||
// registration but not the code, which goes only to the address owner.
|
||||
func TestConfirmByCodeAttackerRegistrationNeedsTheOwnersCode(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(wrongCodeFor(fixture.code), "correct horse battery staple"))
|
||||
requireInvalidCode(t, err)
|
||||
if fixture.store.recorded != 1 || fixture.store.closed {
|
||||
t.Fatalf("counted %d, closed %v; want one counted attempt and an open token", fixture.store.recorded, fixture.store.closed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmByCodeRefusesAnExpiredCode(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
fixture.confirmation.deps.Clock = func() time.Time { return fixture.now.Add(domain.VerificationCodeLifetime + time.Second) }
|
||||
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
|
||||
requireInvalidCode(t, err)
|
||||
if errors.Is(err, ErrVerificationTokenExpired) {
|
||||
t.Fatal("an expired code reported its own refusal")
|
||||
}
|
||||
if fixture.store.recorded != 1 || fixture.transactor.calls != 0 {
|
||||
t.Fatalf("counted %d, transactions %d", fixture.store.recorded, fixture.transactor.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmByCodeMalformedPasswordDoesNotSkipTheHashingWork(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
for _, password := range []string{"", strings.Repeat("p", 129)} {
|
||||
fixture.hasher.dummyCalls = 0
|
||||
fixture.hasher.verifyCalls = 0
|
||||
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), password))
|
||||
requireInvalidCode(t, err)
|
||||
if fixture.hasher.dummyCalls != 1 || fixture.hasher.verifyCalls != 0 {
|
||||
t.Fatalf("password length %d: hasher calls dummy %d, verify %d", len(password), fixture.hasher.dummyCalls, fixture.hasher.verifyCalls)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmByCodeConsumesTheTokenAndBlocksLaterUse(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
result, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
|
||||
if err != nil {
|
||||
t.Fatalf("ConfirmByCode() error = %v", err)
|
||||
}
|
||||
if result.Scenario != domain.ScenarioCandidate || result.OnboardingStep != domain.OnboardingStepCandidateConsents {
|
||||
t.Fatalf("result = %+v", result)
|
||||
}
|
||||
if !fixture.store.consumed || fixture.transactor.calls != 1 {
|
||||
t.Fatalf("consumed %v, transactions %d", fixture.store.consumed, fixture.transactor.calls)
|
||||
}
|
||||
_, err = fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
|
||||
requireInvalidCode(t, err)
|
||||
_, err = fixture.confirmation.Confirm(context.Background(), ConfirmCommand{Token: fixture.raw.Reveal(), Password: "correct horse battery staple"})
|
||||
requireInvalidCode(t, err)
|
||||
}
|
||||
|
||||
// The link consumes the same token, so a code confirmation after it is refused.
|
||||
func TestLinkConfirmationBurnsTheCode(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
if _, err := fixture.confirmation.Confirm(context.Background(), ConfirmCommand{
|
||||
Token: fixture.raw.Reveal(), Password: "correct horse battery staple", ClientKey: "client-key",
|
||||
}); err != nil {
|
||||
t.Fatalf("Confirm() error = %v", err)
|
||||
}
|
||||
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
|
||||
requireInvalidCode(t, err)
|
||||
if fixture.transactor.calls != 1 {
|
||||
t.Fatalf("transactions = %d, want only the link confirmation", fixture.transactor.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerificationCodeSettingsMustBePositive(t *testing.T) {
|
||||
fixture := newCodeFixture(t)
|
||||
_, err := NewEmailConfirmation(ConfirmationDependencies{
|
||||
Transactor: fixture.transactor, Tokens: fixture.store, Credentials: NewCredentials(fixture.hasher),
|
||||
Limiter: fixture.limiter, Keyring: fixture.keyring, Clock: time.Now,
|
||||
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 30})
|
||||
if err == nil {
|
||||
t.Fatal("NewEmailConfirmation() accepted a missing address limit")
|
||||
}
|
||||
}
|
||||
@@ -31,11 +31,14 @@ type ConfirmationDependencies struct {
|
||||
Metrics RateLimitMetrics
|
||||
}
|
||||
|
||||
// ConfirmationSettings contains the attempt limits for one token and one
|
||||
// client. The client limit matches registration and resend.
|
||||
// ConfirmationSettings contains the attempt limits for one token, one client,
|
||||
// and one normalized address. The client limit matches registration and
|
||||
// resend. The address limit is the login limit: code confirmation draws on the
|
||||
// same hourly budget as login for the address.
|
||||
type ConfirmationSettings struct {
|
||||
TokenHourlyLimit int64
|
||||
ClientHourlyLimit int64
|
||||
EmailHourlyLimit int64
|
||||
}
|
||||
|
||||
// EmailConfirmation confirms the address and applies the credentials of the
|
||||
@@ -52,7 +55,7 @@ func NewEmailConfirmation(deps ConfirmationDependencies, settings ConfirmationSe
|
||||
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:
|
||||
case settings.TokenHourlyLimit < 1, settings.ClientHourlyLimit < 1, settings.EmailHourlyLimit < 1:
|
||||
return nil, errors.New("identity.NewEmailConfirmation - confirmation limits must be positive")
|
||||
}
|
||||
return &EmailConfirmation{deps: deps, settings: settings}, nil
|
||||
@@ -114,6 +117,8 @@ func (confirmation *EmailConfirmation) Confirm(ctx context.Context, command Conf
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// confirmationOutcomeError maps the storage outcome of a link confirmation to
|
||||
// the public refusals. Expiry is reported as its own refusal.
|
||||
func confirmationOutcomeError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, outbound.ErrEmailTokenExpired):
|
||||
|
||||
@@ -108,7 +108,7 @@ func TestEmailConfirmationKeepsInvalidTokenPrecedenceOverExpiry(t *testing.T) {
|
||||
confirmation, err := NewEmailConfirmation(ConfirmationDependencies{
|
||||
Transactor: transactor, Tokens: tokens, Credentials: NewCredentials(nil),
|
||||
Limiter: limiter, Keyring: keyring, Clock: func() time.Time { return now },
|
||||
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20})
|
||||
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20, EmailHourlyLimit: 10})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -138,7 +138,7 @@ func TestEmailConfirmationClientLimitRunsBeforeTokenLookup(t *testing.T) {
|
||||
confirmation, err := NewEmailConfirmation(ConfirmationDependencies{
|
||||
Transactor: transactor, Tokens: tokens, Credentials: NewCredentials(nil),
|
||||
Limiter: limiter, Keyring: keyring, Clock: time.Now,
|
||||
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20})
|
||||
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20, EmailHourlyLimit: 10})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ const (
|
||||
labelEmailBucket = "lincodex/identity/email-bucket/v1"
|
||||
labelClientBucket = "lincodex/identity/client-bucket/v1"
|
||||
labelTokenBucket = "lincodex/identity/verification-token-bucket/v1"
|
||||
labelVerificationCode = "lincodex/identity/verification-code/v1"
|
||||
labelSessionCSRF = "lincodex/identity/session-csrf/v1"
|
||||
labelCandidateView = "lincodex/identity/candidate-view/v1"
|
||||
|
||||
@@ -45,6 +46,7 @@ type Keyring struct {
|
||||
bucketKey []byte
|
||||
clientKey []byte
|
||||
tokenKey []byte
|
||||
codeKey []byte
|
||||
sessionCSRFKey []byte
|
||||
candidateViewKey []byte
|
||||
answerKey []byte
|
||||
@@ -64,6 +66,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
|
||||
bucketKey: derive(secret, labelEmailBucket),
|
||||
clientKey: derive(secret, labelClientBucket),
|
||||
tokenKey: derive(secret, labelTokenBucket),
|
||||
codeKey: derive(secret, labelVerificationCode),
|
||||
sessionCSRFKey: derive(secret, labelSessionCSRF),
|
||||
candidateViewKey: derive(secret, labelCandidateView),
|
||||
answerKey: derive(secret, labelAnswerFingerprint),
|
||||
@@ -148,6 +151,26 @@ func (keyring *Keyring) VerificationTokenBucket(rawToken string) string {
|
||||
return "identity:verification-token:" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// VerificationCodeDigest keys a six-digit verification code under the code
|
||||
// purpose key. The code space holds only a million values, so an unkeyed digest
|
||||
// could be reversed by enumeration; the keyed digest cannot be checked offline
|
||||
// without the server secret.
|
||||
func (keyring *Keyring) VerificationCodeDigest(code domain.VerificationCode) domain.VerificationCodeHash {
|
||||
mac := hmac.New(sha256.New, keyring.codeKey)
|
||||
mac.Write([]byte(code.Reveal()))
|
||||
return domain.VerificationCodeHash(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// VerifyVerificationCode compares a supplied code with a stored digest in
|
||||
// constant time.
|
||||
func (keyring *Keyring) VerifyVerificationCode(code domain.VerificationCode, stored domain.VerificationCodeHash) bool {
|
||||
if code.IsZero() || stored.IsZero() {
|
||||
return false
|
||||
}
|
||||
computed := keyring.VerificationCodeDigest(code)
|
||||
return hmac.Equal(computed[:], stored[:])
|
||||
}
|
||||
|
||||
// SessionCSRF derives a synchronizer token for exactly one session. The
|
||||
// purpose key and message are both domain-separated from every other keyring
|
||||
// use, and only the encoded result is returned to the HTTP adapter.
|
||||
|
||||
@@ -143,3 +143,41 @@ func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t
|
||||
t.Fatal("the cursor signature shares a key with the idempotency scope")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerificationCodeDigestIsKeyedAndPurposeSeparated(t *testing.T) {
|
||||
keyring, err := NewKeyring([]byte("keyring test secret with enough entropy"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other, err := NewKeyring([]byte("another keyring secret with enough entropy"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, err := domain.ParseVerificationCode("482915")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := keyring.VerificationCodeDigest(code)
|
||||
if digest != keyring.VerificationCodeDigest(code) {
|
||||
t.Fatal("the same code gives different digests under one key")
|
||||
}
|
||||
if digest == other.VerificationCodeDigest(code) {
|
||||
t.Fatal("two server secrets give the same digest for one code")
|
||||
}
|
||||
if digest == domain.VerificationCodeHash(sha256.Sum256([]byte("482915"))) {
|
||||
t.Fatal("the stored digest is an unkeyed SHA-256 of the code")
|
||||
}
|
||||
if !keyring.VerifyVerificationCode(code, digest) {
|
||||
t.Fatal("VerifyVerificationCode() rejected the matching code")
|
||||
}
|
||||
wrong, err := domain.ParseVerificationCode("482916")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if keyring.VerifyVerificationCode(wrong, digest) {
|
||||
t.Fatal("VerifyVerificationCode() accepted a wrong code")
|
||||
}
|
||||
if keyring.VerifyVerificationCode(domain.VerificationCode{}, digest) || keyring.VerifyVerificationCode(code, domain.VerificationCodeHash{}) {
|
||||
t.Fatal("VerifyVerificationCode() accepted a missing code or digest")
|
||||
}
|
||||
}
|
||||
@@ -365,7 +365,9 @@ func (registration *Registration) reRegister(
|
||||
}
|
||||
|
||||
// issueVerification stores a new token bound to the current registration
|
||||
// version and queues its message, in the caller's transaction.
|
||||
// version and queues its message, in the caller's transaction. The message
|
||||
// carries a six-digit code next to the link; storage keeps only the keyed digest
|
||||
// of the code, which ends with the token or after the code lifetime.
|
||||
func (registration *Registration) issueVerification(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
@@ -383,6 +385,10 @@ func (registration *Registration) issueVerification(
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - generate token: %w", location, err)
|
||||
}
|
||||
code, err := domain.NewVerificationCode()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - generate code: %w", location, err)
|
||||
}
|
||||
token, err := domain.NewEmailToken(domain.NewEmailTokenInput{
|
||||
UserID: user.ID,
|
||||
Purpose: domain.EmailTokenPurposeEmailVerification,
|
||||
@@ -390,6 +396,8 @@ func (registration *Registration) issueVerification(
|
||||
RegistrationVersion: user.RegistrationVersion,
|
||||
IssuedAt: now,
|
||||
Lifetime: lifetime.Duration(),
|
||||
CodeHash: registration.deps.Keyring.VerificationCodeDigest(code),
|
||||
CodeLifetime: domain.VerificationCodeLifetime,
|
||||
Pending: pending,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -399,10 +407,12 @@ func (registration *Registration) issueVerification(
|
||||
return fmt.Errorf("%s - store token: %w", location, err)
|
||||
}
|
||||
_, err = registration.deps.Mailer.EnqueueVerification(ctx, unit, notification.TokenMailRequest{
|
||||
Recipient: user.Email,
|
||||
Token: token,
|
||||
RawToken: raw,
|
||||
Lifetime: lifetime,
|
||||
Recipient: user.Email,
|
||||
Token: token,
|
||||
RawToken: raw,
|
||||
Lifetime: lifetime,
|
||||
Code: code,
|
||||
CodeLifetime: domain.VerificationCodeLifetime,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - queue message: %w", location, err)
|
||||
|
||||
Reference in new issue
Block a user