feat(identity): register accounts and resend verification mail

This commit is contained in:
shira committed 2026-10-06 23:59:51 +03:00
1 parent 5e202ac972
commit 4436f626a3
55 files changed
+3227 -88

No files matched your search

@@ -0,0 +1,107 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/port/outbound"
)
type idempotencyRepository struct {
queries *sqlc.Queries
}
func (repository idempotencyRepository) Reserve(
ctx context.Context,
record outbound.IdempotencyRecord,
) (outbound.IdempotencyRecord, bool, error) {
const location = "idempotencyRepository.Reserve"
if err := requireTime(location, record.CreatedAt, outbound.ErrIdempotencyRecordNotFound); err != nil {
return outbound.IdempotencyRecord{}, false, err
}
if !record.ExpiresAt.After(record.CreatedAt) {
return outbound.IdempotencyRecord{}, false, errors.New(location + " - expiry must be after creation")
}
row, err := repository.queries.ReserveIdempotencyRecord(ctx, sqlc.ReserveIdempotencyRecordParams{
ScopeHash: record.Scope[:],
Fingerprint: record.Fingerprint[:],
CreatedAt: pgTime(record.CreatedAt),
ExpiresAt: pgTime(record.ExpiresAt),
})
if err == nil {
return idempotencyFromRow(location, row.ScopeHash, row.Fingerprint, row.CreatedAt.Time, row.ExpiresAt.Time, true)
}
if !isNoRows(err) {
return outbound.IdempotencyRecord{}, false, fmt.Errorf("%s - store record: %w", location, mapIdentityError(err))
}
// A live record with the scope exists and was left as it is. It is
// visible now: a concurrent writer committed before this statement
// returned.
existing, err := repository.Find(ctx, record.Scope, record.CreatedAt)
if err != nil {
return outbound.IdempotencyRecord{}, false, fmt.Errorf("%s - read live record: %w", location, err)
}
return existing, false, nil
}
func (repository idempotencyRepository) Find(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
at time.Time,
) (outbound.IdempotencyRecord, error) {
const location = "idempotencyRepository.Find"
if err := requireTime(location, at, outbound.ErrIdempotencyRecordNotFound); err != nil {
return outbound.IdempotencyRecord{}, err
}
row, err := repository.queries.GetLiveIdempotencyRecord(ctx, sqlc.GetLiveIdempotencyRecordParams{
ScopeHash: scope[:],
At: pgTime(at),
})
if err != nil {
return outbound.IdempotencyRecord{}, fmt.Errorf("%s - select record: %w", location, mapNoRows(err, outbound.ErrIdempotencyRecordNotFound))
}
record, _, err := idempotencyFromRow(location, row.ScopeHash, row.Fingerprint, row.CreatedAt.Time, row.ExpiresAt.Time, false)
return record, err
}
func (repository idempotencyRepository) PurgeExpired(ctx context.Context, at time.Time, limit int32) (int64, error) {
const location = "idempotencyRepository.PurgeExpired"
if err := requireTime(location, at, outbound.ErrIdempotencyRecordNotFound); err != nil {
return 0, err
}
if limit <= 0 {
return 0, errors.New(location + " - limit must be positive")
}
deleted, err := repository.queries.PurgeExpiredIdempotencyRecords(ctx, sqlc.PurgeExpiredIdempotencyRecordsParams{
At: pgTime(at),
BatchLimit: limit,
})
if err != nil {
return 0, fmt.Errorf("%s - delete records: %w", location, mapIdentityError(err))
}
return deleted, nil
}
func idempotencyFromRow(
location string,
scope, fingerprint []byte,
createdAt, expiresAt time.Time,
created bool,
) (outbound.IdempotencyRecord, bool, error) {
record := outbound.IdempotencyRecord{CreatedAt: createdAt, ExpiresAt: expiresAt}
if len(scope) != outbound.IdempotencyDigestSize || len(fingerprint) != outbound.IdempotencyDigestSize {
return outbound.IdempotencyRecord{}, false, errors.New(location + " - stored digest has an unexpected size")
}
copy(record.Scope[:], scope)
copy(record.Fingerprint[:], fingerprint)
return record, created, nil
}
func isNoRows(err error) bool {
return errors.Is(err, pgx.ErrNoRows)
}
@@ -97,6 +97,14 @@ func (store *IdentityStore) Sessions() outbound.SessionRepository {
return sessionRepository{queries: store.queries}
}
func (store *IdentityStore) IdempotencyRecords() outbound.IdempotencyRepository {
return idempotencyRepository{queries: store.queries}
}
func (unit *UnitOfWork) IdempotencyRecords() outbound.IdempotencyRepository {
return idempotencyRepository{queries: unit.queries}
}
func (unit *UnitOfWork) Users() outbound.UserRepository {
return userRepository{queries: unit.queries}
}
@@ -226,6 +234,26 @@ func (repository userRepository) UpdateRegistration(ctx context.Context, user do
return userFromRow(sqlc.User(row))
}
func (repository userRepository) AdvanceRegistration(
ctx context.Context,
id uuid.UUID,
expectedVersion int64,
at time.Time,
) (domain.User, error) {
if err := requireTime("userRepository.AdvanceRegistration", at, domain.ErrInvalidUser); err != nil {
return domain.User{}, err
}
row, err := repository.queries.AdvanceUserRegistration(ctx, sqlc.AdvanceUserRegistrationParams{
ID: pgUUID(id),
ExpectedVersion: expectedVersion,
RegisteredAt: pgTime(at),
})
if err != nil {
return domain.User{}, fmt.Errorf("userRepository.AdvanceRegistration - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict))
}
return userFromRow(sqlc.User(row))
}
func (repository userRepository) MarkEmailVerified(
ctx context.Context,
id uuid.UUID,
@@ -318,7 +346,7 @@ func (repository emailTokenRepository) Insert(ctx context.Context, token domain.
if token.ID == uuid.Nil || token.TokenHash.IsZero() {
return fmt.Errorf("emailTokenRepository.Insert - token was not built by domain.NewEmailToken: %w", domain.ErrInvalidEmailToken)
}
err := repository.queries.InsertEmailToken(ctx, sqlc.InsertEmailTokenParams{
params := sqlc.InsertEmailTokenParams{
ID: pgUUID(token.ID),
UserID: pgUUID(token.UserID),
Purpose: string(token.Purpose),
@@ -326,13 +354,62 @@ func (repository emailTokenRepository) Insert(ctx context.Context, token domain.
RegistrationVersion: token.RegistrationVersion,
CreatedAt: pgTime(token.CreatedAt),
ExpiresAt: pgTime(token.ExpiresAt),
})
if err != nil {
}
if pending := token.Pending; pending != nil {
params.PendingPasswordHash = pgtype.Text{String: pending.PasswordHash.PHC(), Valid: true}
params.PendingScenario = pgtype.Text{String: string(pending.Scenario), Valid: true}
params.PendingOnboardingStep = pgtype.Text{String: string(pending.OnboardingStep), Valid: true}
}
if err := repository.queries.InsertEmailToken(ctx, params); err != nil {
return fmt.Errorf("emailTokenRepository.Insert - insert email token: %w", mapIdentityError(err))
}
return nil
}
func (repository emailTokenRepository) LatestPending(
ctx context.Context,
userID uuid.UUID,
registrationVersion int64,
) (domain.PendingRegistration, bool, error) {
row, err := repository.queries.GetLatestPendingRegistration(ctx, sqlc.GetLatestPendingRegistrationParams{
UserID: pgUUID(userID),
Purpose: string(domain.EmailTokenPurposeEmailVerification),
RegistrationVersion: registrationVersion,
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.PendingRegistration{}, false, nil
}
if err != nil {
return domain.PendingRegistration{}, false, fmt.Errorf("emailTokenRepository.LatestPending - select pending registration: %w", mapIdentityError(err))
}
pending, err := pendingFromColumns(row.PendingPasswordHash, row.PendingScenario, row.PendingOnboardingStep)
if err != nil {
return domain.PendingRegistration{}, false, err
}
return *pending, true, nil
}
// pendingFromColumns decodes the pending credentials of a token row; nil when
// the token carries none.
func pendingFromColumns(hash, scenario, step pgtype.Text) (*domain.PendingRegistration, error) {
if !hash.Valid {
return nil, nil
}
passwordHash, err := domain.NewPasswordHash(hash.String)
if err != nil {
return nil, fmt.Errorf("postgres.pendingFromColumns - decode password hash: %w", err)
}
parsedScenario, err := domain.ParseScenario(scenario.String)
if err != nil {
return nil, fmt.Errorf("postgres.pendingFromColumns - decode scenario: %w", err)
}
parsedStep, err := domain.ParseOnboardingStep(step.String)
if err != nil {
return nil, fmt.Errorf("postgres.pendingFromColumns - decode onboarding step: %w", err)
}
return &domain.PendingRegistration{PasswordHash: passwordHash, Scenario: parsedScenario, OnboardingStep: parsedStep}, nil
}
func (repository emailTokenRepository) InvalidateActive(
ctx context.Context,
userID uuid.UUID,
@@ -416,7 +493,12 @@ func emailTokenFromRow(row sqlc.EmailToken) (domain.EmailToken, error) {
if err != nil {
return domain.EmailToken{}, err
}
pending, err := pendingFromColumns(row.PendingPasswordHash, row.PendingScenario, row.PendingOnboardingStep)
if err != nil {
return domain.EmailToken{}, err
}
return domain.EmailToken{
Pending: pending,
ID: uuid.UUID(row.ID.Bytes),
UserID: uuid.UUID(row.UserID.Bytes),
Purpose: purpose,
@@ -11,6 +11,104 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const advanceUserRegistration = `-- name: AdvanceUserRegistration :one
WITH updated AS (
UPDATE users
SET
registration_version = registration_version + 1,
last_registered_at = $1,
updated_at = $1,
version = version + 1
WHERE
users.id = $2
AND users.version = $3
AND users.email_verified_at IS NULL
RETURNING
users.id,
users.email,
users.email_normalized,
users.password_hash,
users.scenario,
users.onboarding_step,
users.email_verified_at,
users.registration_version,
users.last_registered_at,
users.version,
users.created_at,
users.updated_at
),
discarded_consent AS (
DELETE FROM consent_records
USING updated
WHERE
consent_records.subject_id = updated.id
AND consent_records.purpose = 'c1'
AND consent_records.source = 'registration'
)
SELECT
updated.id,
updated.email,
updated.email_normalized,
updated.password_hash,
updated.scenario,
updated.onboarding_step,
updated.email_verified_at,
updated.registration_version,
updated.last_registered_at,
updated.version,
updated.created_at,
updated.updated_at
FROM updated
`
type AdvanceUserRegistrationParams struct {
RegisteredAt pgtype.Timestamptz
ID pgtype.UUID
ExpectedVersion int64
}
type AdvanceUserRegistrationRow struct {
ID pgtype.UUID
Email string
EmailNormalized string
PasswordHash string
Scenario string
OnboardingStep string
EmailVerifiedAt pgtype.Timestamptz
RegistrationVersion int64
LastRegisteredAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Starts a new registration of an unverified account without touching its
// credentials, scenario, or onboarding step: the new registration carries
// them on its verification token. Advances the registration version, which
// ends every earlier token, and deletes the registration C1 of the earlier
// registrant like UpdateUserRegistration does.
func (q *Queries) AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error) {
row := q.db.QueryRow(ctx, advanceUserRegistration, arg.RegisteredAt, arg.ID, arg.ExpectedVersion)
var i AdvanceUserRegistrationRow
err := row.Scan(
&i.ID,
&i.Email,
&i.EmailNormalized,
&i.PasswordHash,
&i.Scenario,
&i.OnboardingStep,
&i.EmailVerifiedAt,
&i.RegistrationVersion,
&i.LastRegisteredAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const consumeEmailToken = `-- name: ConsumeEmailToken :one
UPDATE email_tokens AS token
SET consumed_at = $1
@@ -32,7 +130,10 @@ RETURNING
token.created_at,
token.expires_at,
token.consumed_at,
token.invalidated_at
token.invalidated_at,
token.pending_password_hash,
token.pending_scenario,
token.pending_onboarding_step
`
type ConsumeEmailTokenParams struct {
@@ -63,6 +164,9 @@ func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenPa
&i.ExpiresAt,
&i.ConsumedAt,
&i.InvalidatedAt,
&i.PendingPasswordHash,
&i.PendingScenario,
&i.PendingOnboardingStep,
)
return i, err
}
@@ -273,6 +377,71 @@ func (q *Queries) GetEmailTokenState(ctx context.Context, arg GetEmailTokenState
return i, err
}
const getLatestPendingRegistration = `-- name: GetLatestPendingRegistration :one
SELECT
pending_password_hash,
pending_scenario,
pending_onboarding_step
FROM email_tokens
WHERE
user_id = $1
AND purpose = $2
AND registration_version = $3
AND pending_password_hash IS NOT NULL
ORDER BY created_at DESC, id DESC
LIMIT 1
`
type GetLatestPendingRegistrationParams struct {
UserID pgtype.UUID
Purpose string
RegistrationVersion int64
}
type GetLatestPendingRegistrationRow struct {
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
// The pending credentials of the newest token of a registration, for a
// resend, which issues its token with the same credentials.
func (q *Queries) GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error) {
row := q.db.QueryRow(ctx, getLatestPendingRegistration, arg.UserID, arg.Purpose, arg.RegistrationVersion)
var i GetLatestPendingRegistrationRow
err := row.Scan(&i.PendingPasswordHash, &i.PendingScenario, &i.PendingOnboardingStep)
return i, err
}
const getLiveIdempotencyRecord = `-- name: GetLiveIdempotencyRecord :one
SELECT
scope_hash,
fingerprint,
created_at,
expires_at
FROM idempotency_records
WHERE
scope_hash = $1
AND expires_at > $2
`
type GetLiveIdempotencyRecordParams struct {
ScopeHash []byte
At pgtype.Timestamptz
}
func (q *Queries) GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error) {
row := q.db.QueryRow(ctx, getLiveIdempotencyRecord, arg.ScopeHash, arg.At)
var i IdempotencyRecord
err := row.Scan(
&i.ScopeHash,
&i.Fingerprint,
&i.CreatedAt,
&i.ExpiresAt,
)
return i, err
}
const getUserByEmailNormalized = `-- name: GetUserByEmailNormalized :one
SELECT
id,
@@ -357,7 +526,10 @@ INSERT INTO email_tokens (
token_hash,
registration_version,
created_at,
expires_at
expires_at,
pending_password_hash,
pending_scenario,
pending_onboarding_step
) VALUES (
$1,
$2,
@@ -365,18 +537,24 @@ INSERT INTO email_tokens (
$4,
$5,
$6,
$7
$7,
$8,
$9,
$10
)
`
type InsertEmailTokenParams struct {
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error {
@@ -388,6 +566,9 @@ func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenPara
arg.RegistrationVersion,
arg.CreatedAt,
arg.ExpiresAt,
arg.PendingPasswordHash,
arg.PendingScenario,
arg.PendingOnboardingStep,
)
return err
}
@@ -496,7 +677,12 @@ func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) error {
const invalidateActiveEmailTokens = `-- name: InvalidateActiveEmailTokens :execrows
UPDATE email_tokens
SET invalidated_at = $1
SET
invalidated_at = $1,
-- An invalidated token keeps no password hash: it can never be confirmed.
pending_password_hash = NULL,
pending_scenario = NULL,
pending_onboarding_step = NULL
WHERE
user_id = $2
AND purpose = $3
@@ -571,6 +757,83 @@ func (q *Queries) MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVe
return i, err
}
const purgeExpiredIdempotencyRecords = `-- name: PurgeExpiredIdempotencyRecords :execrows
DELETE FROM idempotency_records
WHERE scope_hash IN (
SELECT stale.scope_hash
FROM idempotency_records AS stale
WHERE stale.expires_at <= $1
ORDER BY stale.expires_at
LIMIT $2
FOR UPDATE SKIP LOCKED
)
`
type PurgeExpiredIdempotencyRecordsParams struct {
At pgtype.Timestamptz
BatchLimit int32
}
// Deletes at most batch_limit expired records. Locked rows are skipped, so
// the statement never waits for a concurrent reservation.
func (q *Queries) PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error) {
result, err := q.db.Exec(ctx, purgeExpiredIdempotencyRecords, arg.At, arg.BatchLimit)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const reserveIdempotencyRecord = `-- name: ReserveIdempotencyRecord :one
INSERT INTO idempotency_records (
scope_hash,
fingerprint,
created_at,
expires_at
) VALUES (
$1,
$2,
$3,
$4
)
ON CONFLICT (scope_hash) DO UPDATE
SET
fingerprint = excluded.fingerprint,
created_at = excluded.created_at,
expires_at = excluded.expires_at
WHERE idempotency_records.expires_at <= excluded.created_at
RETURNING scope_hash, fingerprint, created_at, expires_at
`
type ReserveIdempotencyRecordParams struct {
ScopeHash []byte
Fingerprint []byte
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
}
// Stores the replay record of a command. A record whose retention has passed
// is replaced, so the key is accepted as new after the retention. A live
// record is left as it is and nothing is returned; the caller then reads it
// with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait
// on the row of the first one until its transaction ends.
func (q *Queries) ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error) {
row := q.db.QueryRow(ctx, reserveIdempotencyRecord,
arg.ScopeHash,
arg.Fingerprint,
arg.CreatedAt,
arg.ExpiresAt,
)
var i IdempotencyRecord
err := row.Scan(
&i.ScopeHash,
&i.Fingerprint,
&i.CreatedAt,
&i.ExpiresAt,
)
return i, err
}
const revokeSession = `-- name: RevokeSession :execrows
UPDATE sessions
SET revoked_at = $1
@@ -163,15 +163,25 @@ type DeliveryAttempt struct {
}
type EmailToken struct {
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ConsumedAt pgtype.Timestamptz
InvalidatedAt pgtype.Timestamptz
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ConsumedAt pgtype.Timestamptz
InvalidatedAt pgtype.Timestamptz
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
type IdempotencyRecord struct {
ScopeHash []byte
Fingerprint []byte
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
}
type MailQuotaReservation struct {
@@ -22,6 +22,12 @@ type Querier interface {
// returns for a stale version or for an account without a profile, which the
// caller answers as a version conflict.
AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error)
// Starts a new registration of an unverified account without touching its
// credentials, scenario, or onboarding step: the new registration carries
// them on its verification token. Advances the registration version, which
// ends every earlier token, and deletes the registration C1 of the earlier
// registrant like UpdateUserRegistration does.
AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error)
// Cancels a job that has not finished. A job whose handler transaction is
// in progress holds its row lock, so the statement waits for it: after the
// handler committed the job is done and nothing is canceled; otherwise the
@@ -163,7 +169,11 @@ type Querier interface {
// for the account's own view of its mail. It selects no address and no
// content. The recipient index narrows the scan to the account's rows.
GetLatestDeliveryStatus(ctx context.Context, arg GetLatestDeliveryStatusParams) (GetLatestDeliveryStatusRow, error)
// The pending credentials of the newest token of a registration, for a
// resend, which issues its token with the same credentials.
GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error)
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error)
// Reads the usage of the day and the month window without locking.
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
// Reads the membership of one account in one organization, in any state.
@@ -366,6 +376,9 @@ type Querier interface {
// the publication time set by the guard trigger. No row means the version
// was not a draft any more.
PublishAssessmentFamily(ctx context.Context, arg PublishAssessmentFamilyParams) (AssessmentFamily, error)
// Deletes at most batch_limit expired records. Locked rows are skipped, so
// the statement never waits for a concurrent reservation.
PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error)
// Reads the profile row of an account together with every claim in one
// statement, so the version and the claims come from one snapshot: a save that
// commits between two separate reads could pair version N with the claims of
@@ -419,6 +432,12 @@ type Querier interface {
// the job did not cause the failure. The same guard as the completion
// applies, one (id, attempt) pair per job. It returns the IDs it released.
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
// Stores the replay record of a command. A record whose retention has passed
// is replaced, so the key is accepted as new after the retention. A live
// record is left as it is and nothing is returned; the caller then reads it
// with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait
// on the row of the first one until its transaction ends.
ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error)
RetireAssessmentFamily(ctx context.Context, arg RetireAssessmentFamilyParams) (AssessmentFamily, error)
// Revokes every unrevoked record of a purpose other than C4, superseded ones
// included, and returns them. A revocation time before the grant time, from
@@ -39,6 +39,10 @@ type mailMetrics struct {
// senderCancelled counts deliveries that the sending worker ended without
// sending, by cancel reason, a closed set from the domain.
senderCancelled *client.CounterVec
// identityRateLimited counts registration and resend requests that the
// identity limiter refused, by scope: address or client. No address,
// email, or key is ever a label.
identityRateLimited *client.CounterVec
}
// deliveryKinds and deliveryStatuses list the series that always exist, so a
@@ -89,6 +93,10 @@ func newMailMetrics() mailMetrics {
Name: "lincodex_mail_sender_cancelled_total",
Help: "Deliveries that the mail sending worker of this process ended without sending, by cancel reason. content_invalid and processing_failed mean a broken row or a defect.",
}, []string{"reason"}),
identityRateLimited: client.NewCounterVec(client.CounterOpts{
Name: "lincodex_identity_rate_limit_refusals_total",
Help: "Registration and verification resend requests refused with 429 by the identity limiter, by scope: address (per email address) or client (per network address). A large share of client refusals hints at a broken proxy chain, where many clients share one address; a rise of address refusals can mean a targeted lockout of one address.",
}, []string{"scope"}),
senderRunning: client.NewGauge(client.GaugeOpts{
Name: "lincodex_mail_sender_running",
Help: "1 while the mail sending loop of this process runs, 0 while it does not, for example with EMAIL_PROVIDER=disabled or after shutdown began.",
@@ -99,14 +107,32 @@ func newMailMetrics() mailMetrics {
for _, reason := range domain.DeliveryCancelReasons() {
metrics.senderCancelled.WithLabelValues(string(reason))
}
for _, scope := range []string{IdentityScopeAddress, IdentityScopeClient} {
metrics.identityRateLimited.WithLabelValues(scope)
}
return metrics
}
// The scopes of the identity rate limit refusal counter.
const (
IdentityScopeAddress = "address"
IdentityScopeClient = "client"
)
// ObserveIdentityRateLimited counts one refused identity request. A scope
// outside the two known ones counts as address, so the label stays bounded.
func (metrics *Metrics) ObserveIdentityRateLimited(scope string) {
if scope != IdentityScopeClient {
scope = IdentityScopeAddress
}
metrics.mail.identityRateLimited.WithLabelValues(scope).Inc()
}
func (mail mailMetrics) collectors() []client.Collector {
return []client.Collector{
mail.deliveries, mail.oldestDuePendingAge, mail.lastSuccess,
mail.quotaUsed, mail.quotaLimit, mail.quotaProviderExhausted,
mail.senderRunning, mail.senderCancelled,
mail.senderRunning, mail.senderCancelled, mail.identityRateLimited,
}
}
@@ -39,3 +39,16 @@ func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) {
t.Fatal("an arbitrary reason became a label")
}
}
func TestIdentityRateLimitRefusalsAreCountedByBoundedScope(t *testing.T) {
metrics := New()
metrics.ObserveIdentityRateLimited(IdentityScopeClient)
metrics.ObserveIdentityRateLimited(IdentityScopeAddress)
metrics.ObserveIdentityRateLimited("203.0.113.9")
body := scrape(t, metrics)
requireSeries(t, body, `lincodex_identity_rate_limit_refusals_total{scope="client"} 1`)
requireSeries(t, body, `lincodex_identity_rate_limit_refusals_total{scope="address"} 2`)
if strings.Contains(body, "203.0.113.9") {
t.Fatal("an unknown scope became a label value")
}
}
@@ -0,0 +1,86 @@
package redis
import (
"context"
"fmt"
"strconv"
"time"
"github.com/redis/go-redis/v9"
"lincodex/backend/internal/port/outbound"
)
// takeScript counts one request against every rule atomically. KEYS holds one
// counter per rule and ARGV holds the limit and the window in milliseconds of
// each rule, in the same order. It returns 0 when the request was counted and
// otherwise the milliseconds until every refusing rule admits it again; a
// refused request changes nothing, so it does not extend a window. A counter
// without an expiry, which a crash outside this script could never leave,
// still gets one, and a counter with 0 ms left counts as 1 ms, so a refusal
// never reports a zero wait.
var takeScript = redis.NewScript(`
local retry = 0
for index, key in ipairs(KEYS) do
local limit = tonumber(ARGV[2 * index - 1])
local window = tonumber(ARGV[2 * index])
local used = tonumber(redis.call('GET', key) or '0')
if used >= limit then
local remaining = redis.call('PTTL', key)
if remaining < 0 then
redis.call('PEXPIRE', key, window)
remaining = window
elseif remaining == 0 then
remaining = 1
end
if remaining > retry then
retry = remaining
end
end
end
if retry > 0 then
return retry
end
for index, key in ipairs(KEYS) do
local count = redis.call('INCR', key)
if count == 1 or redis.call('PTTL', key) < 0 then
redis.call('PEXPIRE', key, ARGV[2 * index])
end
end
return 0
`)
const rateLimitKeyPrefix = "ratelimit:"
var _ outbound.RateLimiter = (*Cache)(nil)
// Take implements outbound.RateLimiter with one fixed-window counter per
// rule, named by the key and the window length, so two rules of one key never
// share a counter.
func (cache *Cache) Take(ctx context.Context, key string, rules ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) {
if key == "" || len(rules) == 0 {
return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - key and at least one rule are required: %w", outbound.ErrInvalidRateLimitRule)
}
keys := make([]string, 0, len(rules))
arguments := make([]any, 0, 2*len(rules))
for _, rule := range rules {
if rule.Limit <= 0 || rule.Window < time.Millisecond {
return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - limit must be positive and window at least 1ms: %w", outbound.ErrInvalidRateLimitRule)
}
windowMillis := rule.Window.Milliseconds()
// The key is a hash tag, so every counter of one caller maps to one
// cluster slot, as a multi-key script needs.
keys = append(keys, rateLimitKeyPrefix+"{"+key+"}:"+strconv.FormatInt(windowMillis, 10))
arguments = append(arguments, rule.Limit, windowMillis)
}
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
defer cancel()
retryMillis, err := takeScript.Run(ctx, cache.client, keys, arguments...).Int64()
if err != nil {
return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - run script: %w", err)
}
if retryMillis == 0 {
return outbound.RateLimitDecision{Allowed: true}, nil
}
return outbound.RateLimitDecision{RetryAfter: time.Duration(retryMillis) * time.Millisecond}, nil
}