Files
lincodex/backend/internal/usecase/identity/code_confirmation_test.go
T

438 lines
16 KiB
Go

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")
}
}