feat(identity): confirm registration email atomically
This commit is contained in:
1 parent
8e7ce8d71c
commit
fade4e76e4
75 files changed
+4188
-403
No files matched your search
@@ -153,13 +153,15 @@ func (service *Service) GrantAtRegistration(
|
||||
ctx context.Context,
|
||||
repositories outbound.ConsentRepositories,
|
||||
subjectID uuid.UUID,
|
||||
registrationVersion int64,
|
||||
version domain.ConsentTextVersion,
|
||||
) (GrantResult, error) {
|
||||
result, err := service.grant(ctx, repositories, grantRequest{
|
||||
subjectID: subjectID,
|
||||
purpose: domain.ConsentPurposePersonalData,
|
||||
version: version,
|
||||
source: domain.ConsentSourceRegistration,
|
||||
subjectID: subjectID,
|
||||
purpose: domain.ConsentPurposePersonalData,
|
||||
version: version,
|
||||
source: domain.ConsentSourceRegistration,
|
||||
registrationVersion: registrationVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return GrantResult{}, fmt.Errorf("Service.GrantAtRegistration - %w", err)
|
||||
@@ -236,10 +238,11 @@ func (service *Service) GrantInSettingsInNewTransaction(ctx context.Context, inp
|
||||
// grantRequest is a grant of C1, C2, C3, or C5 with its source, which the
|
||||
// public entry points fix.
|
||||
type grantRequest struct {
|
||||
subjectID uuid.UUID
|
||||
purpose domain.ConsentPurpose
|
||||
version domain.ConsentTextVersion
|
||||
source domain.ConsentSource
|
||||
subjectID uuid.UUID
|
||||
purpose domain.ConsentPurpose
|
||||
version domain.ConsentTextVersion
|
||||
source domain.ConsentSource
|
||||
registrationVersion int64
|
||||
}
|
||||
|
||||
func (service *Service) grant(ctx context.Context, repositories outbound.ConsentRepositories, request grantRequest) (GrantResult, error) {
|
||||
@@ -259,12 +262,13 @@ func (service *Service) grant(ctx context.Context, repositories outbound.Consent
|
||||
return GrantResult{}, fmt.Errorf("check text version: %w", err)
|
||||
}
|
||||
grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{
|
||||
SubjectID: request.subjectID,
|
||||
Purpose: request.purpose,
|
||||
TextVersion: text.Version(),
|
||||
TextHash: text.Hash(),
|
||||
Source: request.source,
|
||||
GrantedAt: now,
|
||||
SubjectID: request.subjectID,
|
||||
Purpose: request.purpose,
|
||||
TextVersion: text.Version(),
|
||||
TextHash: text.Hash(),
|
||||
Source: request.source,
|
||||
RegistrationVersion: request.registrationVersion,
|
||||
GrantedAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
return GrantResult{}, fmt.Errorf("build grant: %w", err)
|
||||
|
||||
@@ -71,17 +71,18 @@ func TestGrantAtRegistrationRecordsC1WithTheRegistrationSource(t *testing.T) {
|
||||
harness := newHarness(t)
|
||||
subject := uuid.New()
|
||||
|
||||
result, err := harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, harness.version(domain.ConsentPurposePersonalData))
|
||||
result, err := harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, 1, harness.version(domain.ConsentPurposePersonalData))
|
||||
if err != nil || !result.Created {
|
||||
t.Fatalf("GrantAtRegistration() = %v, %v, want a new record", result.Created, err)
|
||||
}
|
||||
record := result.Record
|
||||
if record.Purpose() != domain.ConsentPurposePersonalData || record.Source() != domain.ConsentSourceRegistration ||
|
||||
record.RegistrationVersion() != 1 ||
|
||||
record.SubjectID() != subject || !record.GrantedAt().Equal(clockStart) {
|
||||
t.Fatalf("GrantAtRegistration() record = %s %s, want the registration C1 at the application clock", record.Purpose(), record.Source())
|
||||
}
|
||||
|
||||
_, err = harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, "c1-1999-01-01")
|
||||
_, err = harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, 1, "c1-1999-01-01")
|
||||
if !errors.Is(err, consent.ErrStaleConsentText) {
|
||||
t.Fatalf("GrantAtRegistration(outdated) error = %v, want ErrStaleConsentText", err)
|
||||
}
|
||||
@@ -315,7 +316,7 @@ func TestPurposesAreIndependent(t *testing.T) {
|
||||
var result consent.GrantResult
|
||||
var err error
|
||||
if purpose == domain.ConsentPurposePersonalData {
|
||||
result, err = harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, harness.version(purpose))
|
||||
result, err = harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, 1, harness.version(purpose))
|
||||
} else {
|
||||
result, err = harness.service.GrantInSettings(t.Context(), harness.repositories, consent.SettingsGrantInput{
|
||||
SubjectID: subject, Purpose: purpose, TextVersion: harness.version(purpose),
|
||||
@@ -621,7 +622,8 @@ func (ledger *fakeLedger) Grant(_ context.Context, grant domain.ConsentGrant) (d
|
||||
hash := grant.TextHash()
|
||||
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
|
||||
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(grant.Purpose()), TextVersion: string(grant.TextVersion()),
|
||||
TextHash: hash[:], Source: string(grant.Source()), State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(),
|
||||
TextHash: hash[:], Source: string(grant.Source()), RegistrationVersion: grant.RegistrationVersion(),
|
||||
State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.ConsentRecord{}, false, err
|
||||
@@ -674,6 +676,17 @@ func (ledger *fakeLedger) Current(_ context.Context, subjectID uuid.UUID, purpos
|
||||
return domain.ConsentRecord{}, outbound.ErrConsentNotFound
|
||||
}
|
||||
|
||||
func (ledger *fakeLedger) LockRegistration(_ context.Context, subjectID uuid.UUID, registrationVersion int64) (domain.ConsentRecord, error) {
|
||||
for index := len(ledger.records) - 1; index >= 0; index-- {
|
||||
if record := ledger.records[index]; record.SubjectID() == subjectID &&
|
||||
record.Purpose() == domain.ConsentPurposePersonalData && record.Source() == domain.ConsentSourceRegistration &&
|
||||
record.RegistrationVersion() == registrationVersion && record.State() == domain.ConsentStateActive {
|
||||
return record, nil
|
||||
}
|
||||
}
|
||||
return domain.ConsentRecord{}, outbound.ErrConsentNotFound
|
||||
}
|
||||
|
||||
func (ledger *fakeLedger) CurrentContact(context.Context, uuid.UUID, uuid.UUID) ([]domain.ConsentRecord, error) {
|
||||
panic("the consent usecase does not read C4")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const confirmationTestPasswordHash = "$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g"
|
||||
|
||||
type confirmationTokenReader struct {
|
||||
outbound.EmailTokenRepository
|
||||
|
||||
token domain.EmailToken
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (repository *confirmationTokenReader) FindByHash(context.Context, domain.SecretTokenHash, domain.EmailTokenPurpose) (domain.EmailToken, error) {
|
||||
repository.calls++
|
||||
return repository.token, repository.err
|
||||
}
|
||||
|
||||
type confirmationTestLimiter struct {
|
||||
keys []string
|
||||
first outbound.RateLimitDecision
|
||||
firstError error
|
||||
}
|
||||
|
||||
func (limiter *confirmationTestLimiter) Take(_ context.Context, key string, _ ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) {
|
||||
limiter.keys = append(limiter.keys, key)
|
||||
if len(limiter.keys) == 1 {
|
||||
return limiter.first, limiter.firstError
|
||||
}
|
||||
return outbound.RateLimitDecision{Allowed: true}, nil
|
||||
}
|
||||
|
||||
type confirmationTestTransactor struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
func (transactor *confirmationTestTransactor) WithinTransaction(context.Context, func(context.Context, outbound.UnitOfWork) error) error {
|
||||
transactor.calls++
|
||||
return errors.New("unexpected transaction")
|
||||
}
|
||||
|
||||
func TestEmailConfirmationKeepsInvalidTokenPrecedenceOverExpiry(t *testing.T) {
|
||||
now := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
|
||||
raw, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expired := now.Add(-time.Second)
|
||||
passwordHash, err := domain.NewPasswordHash(confirmationTestPasswordHash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := domain.NewPendingRegistration(passwordHash, domain.ScenarioCandidate)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
consumedAt := now.Add(-time.Minute)
|
||||
invalidatedAt := now.Add(-time.Minute)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
token domain.EmailToken
|
||||
readError error
|
||||
want error
|
||||
}{
|
||||
{
|
||||
name: "consumed",
|
||||
token: domain.EmailToken{ExpiresAt: expired, ConsumedAt: &consumedAt},
|
||||
want: ErrVerificationTokenInvalid,
|
||||
},
|
||||
{
|
||||
name: "invalidated",
|
||||
token: domain.EmailToken{ExpiresAt: expired, InvalidatedAt: &invalidatedAt},
|
||||
want: ErrVerificationTokenInvalid,
|
||||
},
|
||||
{
|
||||
name: "superseded registration",
|
||||
readError: outbound.ErrEmailTokenInvalidated,
|
||||
want: ErrVerificationTokenInvalid,
|
||||
},
|
||||
{
|
||||
name: "current expired token",
|
||||
token: domain.EmailToken{
|
||||
UserID: uuid.New(), Purpose: domain.EmailTokenPurposeEmailVerification,
|
||||
TokenHash: raw.Hash(), ExpiresAt: expired, Pending: &pending,
|
||||
},
|
||||
want: ErrVerificationTokenExpired,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
tokens := &confirmationTokenReader{token: test.token, err: test.readError}
|
||||
transactor := &confirmationTestTransactor{}
|
||||
limiter := &confirmationTestLimiter{first: outbound.RateLimitDecision{Allowed: true}}
|
||||
keyring, err := NewKeyring([]byte("confirmation key with enough entropy"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = confirmation.Confirm(context.Background(), ConfirmCommand{Token: raw.Reveal(), Password: "correct horse battery staple"})
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("Confirm() error = %v, want %v", err, test.want)
|
||||
}
|
||||
if transactor.calls != 0 {
|
||||
t.Fatalf("transaction calls = %d, want 0", transactor.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmailConfirmationClientLimitRunsBeforeTokenLookup(t *testing.T) {
|
||||
raw, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keyring, err := NewKeyring([]byte("confirmation key with enough entropy"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tokens := &confirmationTokenReader{}
|
||||
transactor := &confirmationTestTransactor{}
|
||||
limiter := &confirmationTestLimiter{first: outbound.RateLimitDecision{Allowed: false, RetryAfter: time.Minute}}
|
||||
confirmation, err := NewEmailConfirmation(ConfirmationDependencies{
|
||||
Transactor: transactor, Tokens: tokens, Credentials: NewCredentials(nil),
|
||||
Limiter: limiter, Keyring: keyring, Clock: time.Now,
|
||||
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = confirmation.Confirm(context.Background(), ConfirmCommand{
|
||||
Token: raw.Reveal(), Password: "correct horse battery staple", ClientKey: "client-key",
|
||||
})
|
||||
var limited *RateLimitedError
|
||||
if !errors.As(err, &limited) || limited.RetryAfter != time.Minute {
|
||||
t.Fatalf("Confirm() error = %v, want one-minute rate limit", err)
|
||||
}
|
||||
if len(limiter.keys) != 1 || limiter.keys[0] != keyring.ClientBucket("client-key") {
|
||||
t.Fatalf("limiter keys = %v, want only the client bucket first", limiter.keys)
|
||||
}
|
||||
if tokens.calls != 0 || transactor.calls != 0 {
|
||||
t.Fatalf("storage calls = lookup %d, transaction %d, want none", tokens.calls, transactor.calls)
|
||||
}
|
||||
}
|
||||
@@ -37,3 +37,18 @@ func (credentials *Credentials) HashNewPassword(ctx context.Context, raw string)
|
||||
}
|
||||
return hash, nil
|
||||
}
|
||||
|
||||
// VerifyLoginPassword normalizes and checks a password with the login bounds.
|
||||
// It does not apply the registration blocklist, so an existing registration
|
||||
// can confirm even when that password is no longer accepted for new accounts.
|
||||
func (credentials *Credentials) VerifyLoginPassword(ctx context.Context, raw string, stored domain.PasswordHash) error {
|
||||
const location = "Credentials.VerifyLoginPassword"
|
||||
password, err := domain.ParseLoginPassword(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - validate password: %w", location, err)
|
||||
}
|
||||
if _, err := credentials.hasher.Verify(ctx, password, stored); err != nil {
|
||||
return fmt.Errorf("%s - verify password: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -12,21 +12,30 @@ import (
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const testPasswordPHC = "$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g"
|
||||
|
||||
// countingHasher records calls so a test can prove that validation stops a
|
||||
// password before any hashing.
|
||||
type countingHasher struct {
|
||||
hashCalls int
|
||||
hashed domain.Password
|
||||
hashCalls int
|
||||
hashed domain.Password
|
||||
verifyCalls int
|
||||
verified domain.Password
|
||||
stored domain.PasswordHash
|
||||
verifyErr error
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) Hash(_ context.Context, password domain.Password) (domain.PasswordHash, error) {
|
||||
hasher.hashCalls++
|
||||
hasher.hashed = password
|
||||
return domain.NewPasswordHash("$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g")
|
||||
return domain.NewPasswordHash(testPasswordPHC)
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) Verify(context.Context, domain.Password, domain.PasswordHash) (bool, error) {
|
||||
return false, errors.New("countingHasher.Verify - not used")
|
||||
func (hasher *countingHasher) Verify(_ context.Context, password domain.Password, stored domain.PasswordHash) (bool, error) {
|
||||
hasher.verifyCalls++
|
||||
hasher.verified = password
|
||||
hasher.stored = stored
|
||||
return false, hasher.verifyErr
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) VerifyDummy(context.Context, domain.Password) error {
|
||||
@@ -81,3 +90,29 @@ func TestHashNewPasswordHashesTheNormalizedPassword(t *testing.T) {
|
||||
t.Fatalf("hasher received %d calls, want one with the NFKC form", hasher.hashCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyLoginPasswordUsesLoginBoundsAndNFKC(t *testing.T) {
|
||||
hasher := &countingHasher{}
|
||||
stored, err := domain.NewPasswordHash(testPasswordPHC)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := NewCredentials(hasher).VerifyLoginPassword(context.Background(), "x", stored); err != nil {
|
||||
t.Fatalf("VerifyLoginPassword() error = %v", err)
|
||||
}
|
||||
if hasher.verifyCalls != 1 || hasher.verified.Reveal() != "x" || hasher.stored.PHC() != stored.PHC() {
|
||||
t.Fatalf("Verify calls = %d, password = %q, stored hash matched = %v", hasher.verifyCalls, hasher.verified.Reveal(), hasher.stored.PHC() == stored.PHC())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyLoginPasswordRejectsEmptyInputBeforeKDF(t *testing.T) {
|
||||
hasher := &countingHasher{}
|
||||
stored, err := domain.NewPasswordHash(testPasswordPHC)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = NewCredentials(hasher).VerifyLoginPassword(context.Background(), "", stored)
|
||||
if !errors.Is(err, domain.ErrInvalidPassword) || hasher.verifyCalls != 0 {
|
||||
t.Fatalf("VerifyLoginPassword(empty) = %v after %d verify calls, want ErrInvalidPassword before KDF", err, hasher.verifyCalls)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,14 @@ var (
|
||||
// ErrInvalidField reports a request value outside its rules.
|
||||
// errors.As with *InvalidFieldError yields the JSON Pointer of the field.
|
||||
ErrInvalidField = errors.New("invalid request field")
|
||||
|
||||
// ErrVerificationTokenInvalid reports an unknown, used, replaced, or
|
||||
// otherwise unusable email verification token.
|
||||
ErrVerificationTokenInvalid = errors.New("verification token invalid")
|
||||
|
||||
// ErrVerificationTokenExpired reports an email verification token past its
|
||||
// expiry time.
|
||||
ErrVerificationTokenExpired = errors.New("verification token expired")
|
||||
)
|
||||
|
||||
// RateLimitedError carries how long the caller waits before a repeat can be
|
||||
|
||||
@@ -19,6 +19,7 @@ const (
|
||||
labelFingerprint = "lincodex/identity/request-fingerprint/v1"
|
||||
labelEmailBucket = "lincodex/identity/email-bucket/v1"
|
||||
labelClientBucket = "lincodex/identity/client-bucket/v1"
|
||||
labelTokenBucket = "lincodex/identity/verification-token-bucket/v1"
|
||||
)
|
||||
|
||||
// Keyring computes the keyed digests of the anonymous identity operations:
|
||||
@@ -31,6 +32,7 @@ type Keyring struct {
|
||||
fingerprintKey []byte
|
||||
bucketKey []byte
|
||||
clientKey []byte
|
||||
tokenKey []byte
|
||||
}
|
||||
|
||||
// NewKeyring derives the purpose keys from secret.
|
||||
@@ -43,6 +45,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
|
||||
fingerprintKey: derive(secret, labelFingerprint),
|
||||
bucketKey: derive(secret, labelEmailBucket),
|
||||
clientKey: derive(secret, labelClientBucket),
|
||||
tokenKey: derive(secret, labelTokenBucket),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -88,3 +91,11 @@ func (keyring *Keyring) ClientBucket(clientKey string) string {
|
||||
mac.Write([]byte(clientKey))
|
||||
return "identity:client:" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// VerificationTokenBucket names the rate limit counter for a raw
|
||||
// verification token without putting the token itself in the limiter store.
|
||||
func (keyring *Keyring) VerificationTokenBucket(rawToken string) string {
|
||||
mac := hmac.New(sha256.New, keyring.tokenKey)
|
||||
mac.Write([]byte(rawToken))
|
||||
return "identity:verification-token:" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
@@ -102,6 +102,7 @@ type RegistrationDependencies struct {
|
||||
const (
|
||||
ScopeAddress = "address"
|
||||
ScopeClient = "client"
|
||||
ScopeToken = "token"
|
||||
)
|
||||
|
||||
// RateLimitMetrics counts refused requests by scope, never by address.
|
||||
@@ -319,7 +320,7 @@ func (registration *Registration) createAccount(ctx context.Context, unit outbou
|
||||
if err := unit.Users().Create(ctx, user); err != nil {
|
||||
return fmt.Errorf("%s - store account: %w", location, err)
|
||||
}
|
||||
if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, user.ID, input.version); err != nil {
|
||||
if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, input.version); err != nil {
|
||||
return fmt.Errorf("%s - record C1: %w", location, err)
|
||||
}
|
||||
pending, err := domain.NewPendingRegistration(input.hash, input.scenario)
|
||||
@@ -353,7 +354,7 @@ func (registration *Registration) reRegister(
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - advance registration: %w", location, err)
|
||||
}
|
||||
if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, advanced.ID, input.version); err != nil {
|
||||
if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, advanced.ID, advanced.RegistrationVersion, input.version); err != nil {
|
||||
return fmt.Errorf("%s - record C1: %w", location, err)
|
||||
}
|
||||
pending, err := domain.NewPendingRegistration(input.hash, input.scenario)
|
||||
|
||||
Reference in new issue
Block a user