522 lines
21 KiB
Go
522 lines
21 KiB
Go
package identity
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/consent"
|
|
"lincodex/backend/internal/usecase/notification"
|
|
)
|
|
|
|
const (
|
|
// registerOperation names RegisterAccount in the idempotency scope.
|
|
registerOperation = "RegisterAccount"
|
|
|
|
// maxIdempotencyKeyLength is the longest Idempotency-Key of the contract.
|
|
maxIdempotencyKeyLength = 255
|
|
|
|
// maxTransactionAttempts bounds the retries of a registration or a resend
|
|
// after a lost race: a concurrent registration of the same address, a
|
|
// concurrent re-registration, or a deadlock. Each retry reads the account
|
|
// again, so it takes the branch that matches the winner.
|
|
maxTransactionAttempts = 3
|
|
|
|
// purgeBatch is how many expired idempotency records one registration
|
|
// removes, so the table stays bounded without a separate job.
|
|
purgeBatch = 10
|
|
|
|
idempotencyKeyPointer = "/Idempotency-Key"
|
|
consentTextVersionPointer = "/consent_c1/text_version"
|
|
emailPointer = "/email"
|
|
passwordPointer = "/password"
|
|
scenarioPointer = "/scenario"
|
|
)
|
|
|
|
// RegistrationSettings holds the limits of the verification mail to one
|
|
// address. The registration and every resend count against both rules, so
|
|
// registering again and then resending cannot send more than the daily limit.
|
|
type RegistrationSettings struct {
|
|
// MailMinInterval is the shortest time between two verification messages
|
|
// to one address.
|
|
MailMinInterval time.Duration
|
|
// MailDailyLimit is the number of verification messages to one address in
|
|
// a window of 24 hours that starts with the first of them.
|
|
MailDailyLimit int64
|
|
// ClientHourlyLimit is the number of registrations and resends per client
|
|
// in a window of one hour. It applies only to a request that carries a
|
|
// client key.
|
|
ClientHourlyLimit int64
|
|
}
|
|
|
|
const (
|
|
// mailDailyWindow is the window of RegistrationSettings.MailDailyLimit.
|
|
mailDailyWindow = 24 * time.Hour
|
|
// clientWindow is the window of RegistrationSettings.ClientHourlyLimit.
|
|
clientWindow = time.Hour
|
|
)
|
|
|
|
func (settings RegistrationSettings) mailRules() []outbound.RateLimitRule {
|
|
return []outbound.RateLimitRule{
|
|
{Window: settings.MailMinInterval, Limit: 1},
|
|
{Window: mailDailyWindow, Limit: settings.MailDailyLimit},
|
|
}
|
|
}
|
|
|
|
func (settings RegistrationSettings) validate() error {
|
|
switch {
|
|
case settings.MailMinInterval < time.Millisecond || settings.MailMinInterval >= mailDailyWindow:
|
|
return errors.New("mail minimum interval must be at least one millisecond and shorter than the daily window")
|
|
case settings.MailDailyLimit < 1:
|
|
return errors.New("mail daily limit must be positive")
|
|
case settings.ClientHourlyLimit < 1:
|
|
return errors.New("client hourly limit must be positive")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RegistrationDependencies are the collaborators of Registration. Every
|
|
// field is required.
|
|
type RegistrationDependencies struct {
|
|
Transactor outbound.Transactor
|
|
// ConsentTexts and Idempotency read outside a transaction: the consent
|
|
// text check and the replay check run before the registration
|
|
// transaction starts.
|
|
ConsentTexts outbound.ConsentRepositories
|
|
Idempotency outbound.IdempotencyRepository
|
|
Consents *consent.Service
|
|
Credentials *Credentials
|
|
Mailer *notification.ServiceMailer
|
|
Limiter outbound.RateLimiter
|
|
Keyring *Keyring
|
|
Clock func() time.Time
|
|
// Metrics receives the refusals of the limiter. Optional.
|
|
Metrics RateLimitMetrics
|
|
}
|
|
|
|
// Scopes of a limiter refusal, as the metric labels them.
|
|
const (
|
|
ScopeAddress = "address"
|
|
ScopeClient = "client"
|
|
ScopeToken = "token"
|
|
)
|
|
|
|
// RateLimitMetrics counts refused requests by scope, never by address.
|
|
type RateLimitMetrics interface {
|
|
ObserveIdentityRateLimited(scope string)
|
|
}
|
|
|
|
// Registration registers accounts and resends the verification message. It
|
|
// holds no state; the same instance serves concurrent callers.
|
|
//
|
|
// Neither operation reveals whether an address belongs to an account: the
|
|
// outcome, the response, and the rate limit depend on the request alone,
|
|
// never on the stored accounts. Registration also computes the password hash
|
|
// on every branch before it reads the account.
|
|
type Registration struct {
|
|
deps RegistrationDependencies
|
|
settings RegistrationSettings
|
|
}
|
|
|
|
// NewRegistration checks the dependencies and settings once, so a wiring
|
|
// mistake fails at startup and not at the first request.
|
|
func NewRegistration(deps RegistrationDependencies, settings RegistrationSettings) (*Registration, error) {
|
|
switch {
|
|
case deps.Transactor == nil, deps.ConsentTexts == nil, deps.Idempotency == nil, deps.Consents == nil,
|
|
deps.Credentials == nil, deps.Mailer == nil, deps.Limiter == nil, deps.Keyring == nil, deps.Clock == nil:
|
|
return nil, errors.New("identity.NewRegistration - every dependency must be set")
|
|
}
|
|
if err := settings.validate(); err != nil {
|
|
return nil, fmt.Errorf("identity.NewRegistration - validate settings: %w", err)
|
|
}
|
|
return &Registration{deps: deps, settings: settings}, nil
|
|
}
|
|
|
|
// RegisterCommand is the content of a registration request, unvalidated.
|
|
type RegisterCommand struct {
|
|
IdempotencyKey string
|
|
Email string
|
|
Password string
|
|
Scenario string
|
|
// ConsentTextVersion is the version of the C1 text the user accepted.
|
|
ConsentTextVersion string
|
|
// ClientKey identifies the client for the per-client limit, for example
|
|
// the limiter key of its network address. Empty skips that limit. It is
|
|
// opaque, is only ever keyed-hashed here, and is never stored or logged.
|
|
ClientKey string
|
|
}
|
|
|
|
// ResendCommand is the content of a resend request, unvalidated.
|
|
type ResendCommand struct {
|
|
Email string
|
|
// ClientKey is as in RegisterCommand.
|
|
ClientKey string
|
|
}
|
|
|
|
// registerInput is a validated command.
|
|
type registerInput struct {
|
|
email domain.EmailAddress
|
|
scenario domain.Scenario
|
|
version domain.ConsentTextVersion
|
|
hash domain.PasswordHash
|
|
record outbound.IdempotencyRecord
|
|
fingerprint [outbound.IdempotencyDigestSize]byte
|
|
}
|
|
|
|
// Register handles one registration request. A nil result means the neutral
|
|
// acceptance, whatever the state of the address: a new account was created, a
|
|
// pending registration was replaced, a verified account was left alone, or
|
|
// the request replays an earlier identical one.
|
|
//
|
|
// Errors: *InvalidFieldError for a value outside its rules, including a C1
|
|
// text version that is no longer current; ErrIdempotencyKeyReused;
|
|
// *RateLimitedError; anything else is an internal failure.
|
|
//
|
|
// Order: validation, replay check, rate limit, password hash, transaction.
|
|
// A replay does not consume the limit, so a client that retries a lost
|
|
// answer is not refused for it.
|
|
func (registration *Registration) Register(ctx context.Context, command RegisterCommand) error {
|
|
const location = "Registration.Register"
|
|
input, err := registration.validateRegister(ctx, command)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - validate request: %w", location, err)
|
|
}
|
|
existing, err := registration.deps.Idempotency.Find(ctx, input.record.Scope, registration.deps.Clock())
|
|
switch {
|
|
case err == nil:
|
|
return replayOrReject(location, existing, input.fingerprint)
|
|
case !errors.Is(err, outbound.ErrIdempotencyRecordNotFound):
|
|
return fmt.Errorf("%s - read idempotency record: %w", location, err)
|
|
}
|
|
if err := registration.takeMailSlot(ctx, input.email, command.ClientKey); err != nil {
|
|
return fmt.Errorf("%s - limit verification mail: %w", location, err)
|
|
}
|
|
// The hash is computed on every branch, before the account is read, so
|
|
// the time of the response does not tell a new address from a known one.
|
|
input.hash, err = registration.deps.Credentials.HashNewPassword(ctx, command.Password)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - hash password: %w", location, err)
|
|
}
|
|
err = registration.inTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
return registration.registerInTransaction(ctx, unit, input)
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("%s - register in transaction: %w", location, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (registration *Registration) validateRegister(ctx context.Context, command RegisterCommand) (registerInput, error) {
|
|
if command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeyLength {
|
|
return registerInput{}, invalidField(idempotencyKeyPointer, errors.New("key must have 1 to 255 characters"))
|
|
}
|
|
email, err := domain.NewEmailAddress(command.Email)
|
|
if err != nil {
|
|
return registerInput{}, invalidField(emailPointer, err)
|
|
}
|
|
if _, err := domain.NewPassword(command.Password); err != nil {
|
|
return registerInput{}, invalidField(passwordPointer, err)
|
|
}
|
|
scenario, err := domain.ParseScenario(command.Scenario)
|
|
if err != nil {
|
|
return registerInput{}, invalidField(scenarioPointer, err)
|
|
}
|
|
version, err := domain.ParseConsentTextVersion(command.ConsentTextVersion)
|
|
if err != nil {
|
|
return registerInput{}, invalidField(consentTextVersionPointer, err)
|
|
}
|
|
// The check runs before any lookup of the address, so a stale version
|
|
// fails the same way for a new and for a known address.
|
|
_, err = registration.deps.Consents.CheckTextVersion(ctx, registration.deps.ConsentTexts, domain.ConsentPurposePersonalData, version)
|
|
if errors.Is(err, consent.ErrStaleConsentText) {
|
|
return registerInput{}, invalidField(consentTextVersionPointer, err)
|
|
}
|
|
if err != nil {
|
|
return registerInput{}, fmt.Errorf("check consent text version: %w", err)
|
|
}
|
|
fingerprint, err := registration.fingerprint(command)
|
|
if err != nil {
|
|
return registerInput{}, err
|
|
}
|
|
now := registration.deps.Clock()
|
|
return registerInput{
|
|
email: email,
|
|
scenario: scenario,
|
|
version: version,
|
|
fingerprint: fingerprint,
|
|
record: outbound.IdempotencyRecord{
|
|
Scope: registration.deps.Keyring.IdempotencyScope(registerOperation, command.IdempotencyKey, email.Normalized()),
|
|
Fingerprint: fingerprint,
|
|
CreatedAt: now,
|
|
ExpiresAt: now.Add(outbound.IdempotencyRetention),
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
// fingerprint is the HMAC of the canonical body: a JSON array of the fields
|
|
// in a fixed order, with the values as the client sent them.
|
|
func (registration *Registration) fingerprint(command RegisterCommand) ([outbound.IdempotencyDigestSize]byte, error) {
|
|
canonical, err := json.Marshal([]string{command.Email, command.Password, command.Scenario, command.ConsentTextVersion})
|
|
if err != nil {
|
|
return [outbound.IdempotencyDigestSize]byte{}, fmt.Errorf("encode canonical body: %w", err)
|
|
}
|
|
return registration.deps.Keyring.Fingerprint(canonical), nil
|
|
}
|
|
|
|
func replayOrReject(location string, existing outbound.IdempotencyRecord, fingerprint [outbound.IdempotencyDigestSize]byte) error {
|
|
if existing.Fingerprint != fingerprint {
|
|
return fmt.Errorf("%s - compare fingerprints: %w", location, ErrIdempotencyKeyReused)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// registerInTransaction applies one registration. The idempotency record is
|
|
// reserved first: a concurrent request with the same scope then waits for
|
|
// this transaction and replays its outcome.
|
|
func (registration *Registration) registerInTransaction(ctx context.Context, unit outbound.UnitOfWork, input registerInput) error {
|
|
const location = "Registration.registerInTransaction"
|
|
now := registration.deps.Clock()
|
|
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, input.record)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - reserve idempotency record: %w", location, err)
|
|
}
|
|
if !created {
|
|
return replayOrReject(location, stored, input.fingerprint)
|
|
}
|
|
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, now, purgeBatch); err != nil {
|
|
return fmt.Errorf("%s - purge expired idempotency records: %w", location, err)
|
|
}
|
|
user, err := unit.Users().GetByEmail(ctx, input.email)
|
|
switch {
|
|
case errors.Is(err, outbound.ErrUserNotFound):
|
|
return registration.createAccount(ctx, unit, input, now)
|
|
case err != nil:
|
|
return fmt.Errorf("%s - read account: %w", location, err)
|
|
case user.EmailVerified():
|
|
// A verified account never changes and nothing is sent: the notice
|
|
// "you already have an account" is not implemented, see the
|
|
// architecture document.
|
|
return nil
|
|
default:
|
|
return registration.reRegister(ctx, unit, input, user, now)
|
|
}
|
|
}
|
|
|
|
func (registration *Registration) createAccount(ctx context.Context, unit outbound.UnitOfWork, input registerInput, now time.Time) error {
|
|
const location = "Registration.createAccount"
|
|
user, err := domain.NewUser(domain.Registration{
|
|
Email: input.email,
|
|
PasswordHash: input.hash,
|
|
Scenario: input.scenario,
|
|
RegisteredAt: now,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build account: %w", location, err)
|
|
}
|
|
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, user.RegistrationVersion, input.version); err != nil {
|
|
return fmt.Errorf("%s - record C1: %w", location, err)
|
|
}
|
|
pending, err := domain.NewPendingRegistration(input.hash, input.scenario)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build pending registration: %w", location, err)
|
|
}
|
|
return registration.issueVerification(ctx, unit, user, now, &pending)
|
|
}
|
|
|
|
// reRegister starts a new registration of an unverified address. It never
|
|
// changes the credentials, scenario, or onboarding step of the account row:
|
|
// the new registration carries its own on its verification token, and
|
|
// confirming a token applies only the credentials of that token.
|
|
// So neither the first nor the latest registrant of an address can make its
|
|
// owner adopt a password the owner did not choose. The lock order of the
|
|
// identity repositories applies: tokens first, then the account.
|
|
// AdvanceRegistration deletes the earlier C1 of this account, so the new C1 is
|
|
// granted strictly after it.
|
|
func (registration *Registration) reRegister(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
input registerInput,
|
|
user domain.User,
|
|
now time.Time,
|
|
) error {
|
|
const location = "Registration.reRegister"
|
|
if _, err := unit.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, now); err != nil {
|
|
return fmt.Errorf("%s - invalidate earlier tokens: %w", location, err)
|
|
}
|
|
advanced, err := unit.Users().AdvanceRegistration(ctx, user.ID, user.Version, now)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - advance registration: %w", location, err)
|
|
}
|
|
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)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build pending registration: %w", location, err)
|
|
}
|
|
return registration.issueVerification(ctx, unit, advanced, now, &pending)
|
|
}
|
|
|
|
// issueVerification stores a new token bound to the current registration
|
|
// version and queues its message, in the caller's transaction.
|
|
func (registration *Registration) issueVerification(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
user domain.User,
|
|
now time.Time,
|
|
pending *domain.PendingRegistration,
|
|
) error {
|
|
const location = "Registration.issueVerification"
|
|
policy, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, now)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read product policy: %w", location, err)
|
|
}
|
|
lifetime := policy.Policy().Identity.VerificationTokenLifetime
|
|
raw, err := domain.NewSecretToken()
|
|
if err != nil {
|
|
return fmt.Errorf("%s - generate token: %w", location, err)
|
|
}
|
|
token, err := domain.NewEmailToken(domain.NewEmailTokenInput{
|
|
UserID: user.ID,
|
|
Purpose: domain.EmailTokenPurposeEmailVerification,
|
|
TokenHash: raw.Hash(),
|
|
RegistrationVersion: user.RegistrationVersion,
|
|
IssuedAt: now,
|
|
Lifetime: lifetime.Duration(),
|
|
Pending: pending,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build token: %w", location, err)
|
|
}
|
|
if err := unit.EmailTokens().Insert(ctx, token); err != nil {
|
|
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,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("%s - queue message: %w", location, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ResendVerification issues a new verification token for an unverified
|
|
// account and queues its message. The explicit replacement policy: every
|
|
// unused token of the account is invalidated before the new one is stored, so
|
|
// at most one verification link works at a time, and the registration
|
|
// version of the account does not change.
|
|
//
|
|
// A nil result is the neutral acceptance, for an unknown address, a verified
|
|
// one, and an unverified one alike. The rate limit counts the request before
|
|
// the account is read, so a refusal says nothing about the account; it
|
|
// returns *RateLimitedError.
|
|
func (registration *Registration) ResendVerification(ctx context.Context, command ResendCommand) error {
|
|
const location = "Registration.ResendVerification"
|
|
email, err := domain.NewEmailAddress(command.Email)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - validate request: %w", location, invalidField(emailPointer, err))
|
|
}
|
|
if err := registration.takeMailSlot(ctx, email, command.ClientKey); err != nil {
|
|
return fmt.Errorf("%s - limit verification mail: %w", location, err)
|
|
}
|
|
err = registration.inTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
return registration.resendInTransaction(ctx, unit, email)
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("%s - resend in transaction: %w", location, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (registration *Registration) resendInTransaction(ctx context.Context, unit outbound.UnitOfWork, email domain.EmailAddress) error {
|
|
const location = "Registration.resendInTransaction"
|
|
user, err := unit.Users().GetByEmail(ctx, email)
|
|
switch {
|
|
case errors.Is(err, outbound.ErrUserNotFound):
|
|
return nil
|
|
case err != nil:
|
|
return fmt.Errorf("%s - read account: %w", location, err)
|
|
case user.EmailVerified():
|
|
return nil
|
|
}
|
|
now := registration.deps.Clock()
|
|
// A resend keeps the credentials of the registration it resends for.
|
|
var pending *domain.PendingRegistration
|
|
latest, found, err := unit.EmailTokens().LatestPending(ctx, user.ID, user.RegistrationVersion)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read pending credentials: %w", location, err)
|
|
}
|
|
if found {
|
|
pending = &latest
|
|
}
|
|
if pending == nil {
|
|
// No token of this registration carries credentials, which only a
|
|
// token that was invalidated concurrently can cause. A token without
|
|
// them could never be confirmed, so none is issued; the next
|
|
// registration of the address starts over.
|
|
return nil
|
|
}
|
|
if _, err := unit.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, now); err != nil {
|
|
return fmt.Errorf("%s - invalidate earlier tokens: %w", location, err)
|
|
}
|
|
return registration.issueVerification(ctx, unit, user, now, pending)
|
|
}
|
|
|
|
// takeMailSlot counts the request against the per-client rule, when the
|
|
// request has a client key, and then against the per-address rules. The
|
|
// address counters see every request, whether or not an account exists, so a
|
|
// refusal does not reveal an account. A refused request counts nothing in the
|
|
// rule that refused it.
|
|
func (registration *Registration) takeMailSlot(ctx context.Context, email domain.EmailAddress, clientKey string) error {
|
|
if clientKey != "" {
|
|
err := registration.take(ctx, ScopeClient, registration.deps.Keyring.ClientBucket(clientKey),
|
|
outbound.RateLimitRule{Window: clientWindow, Limit: registration.settings.ClientHourlyLimit})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return registration.take(ctx, ScopeAddress, registration.deps.Keyring.EmailBucket(email.Normalized()), registration.settings.mailRules()...)
|
|
}
|
|
|
|
func (registration *Registration) take(ctx context.Context, scope, bucket string, rules ...outbound.RateLimitRule) error {
|
|
decision, err := registration.deps.Limiter.Take(ctx, bucket, rules...)
|
|
if err != nil {
|
|
return fmt.Errorf("take rate limit: %w", err)
|
|
}
|
|
if !decision.Allowed {
|
|
if registration.deps.Metrics != nil {
|
|
registration.deps.Metrics.ObserveIdentityRateLimited(scope)
|
|
}
|
|
return &RateLimitedError{RetryAfter: decision.RetryAfter}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// inTransaction runs work and repeats it, up to maxTransactionAttempts times
|
|
// in total, after a lost race. Every repeat reads the account again, so it is
|
|
// safe: the first attempt rolled back completely.
|
|
func (registration *Registration) inTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
|
|
for attempt := 1; ; attempt++ {
|
|
err := registration.deps.Transactor.WithinTransaction(ctx, work)
|
|
if err == nil || !retryable(err) || attempt >= maxTransactionAttempts || ctx.Err() != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
func retryable(err error) bool {
|
|
return errors.Is(err, outbound.ErrEmailTaken) ||
|
|
errors.Is(err, outbound.ErrUserVersionConflict) ||
|
|
errors.Is(err, outbound.ErrTransactionConflict)
|
|
}
|