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

@@ -411,7 +411,7 @@ func TestProfileSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -0,0 +1,120 @@
package httpadapter
import (
"context"
"errors"
"log/slog"
"net/http"
"testing"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/usecase/identity"
)
const resendPath = "/api/v1/identity/email-verification-requests"
// scriptedRegistration answers every call with its fixed error and records
// the last commands.
type scriptedRegistration struct {
err error
register identity.RegisterCommand
resend identity.ResendCommand
}
func (registration *scriptedRegistration) Register(_ context.Context, command identity.RegisterCommand) error {
registration.register = command
return registration.err
}
func (registration *scriptedRegistration) ResendVerification(_ context.Context, command identity.ResendCommand) error {
registration.resend = command
return registration.err
}
func newIdentityRouter(t *testing.T, registration v1.AccountRegistration) http.Handler {
t.Helper()
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(v1.NewIdentityHandler(registration)))
return newTestRouterWithAPI(t, healthHandler, handler, logger)
}
func TestRegistrationOperationsMapUsecaseOutcomes(t *testing.T) {
registerRequest := identityRequest{
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
headers: map[string]string{"Idempotency-Key": testIdempotencyKey},
}
resendRequest := identityRequest{method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`}
staleConsent := &identity.InvalidFieldError{Pointer: "/consent_c1/text_version", Err: errors.New("stale")}
for _, test := range []struct {
name string
request identityRequest
err error
statusCode int
code api.ProblemCode
pointer string
retryAfter string
}{
{name: "register accepted", request: registerRequest, statusCode: http.StatusAccepted},
{name: "resend accepted", request: resendRequest, statusCode: http.StatusAccepted},
{
name: "register stale consent version", request: registerRequest, err: staleConsent,
statusCode: http.StatusBadRequest, code: api.ProblemCodeValidationFailed, pointer: "/consent_c1/text_version",
},
{
name: "register reused key", request: registerRequest, err: identity.ErrIdempotencyKeyReused,
statusCode: http.StatusUnprocessableEntity, code: api.ProblemCodeIdempotencyKeyReused,
},
{
name: "register limited", request: registerRequest, err: &identity.RateLimitedError{RetryAfter: 1500 * time.Millisecond},
statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "2",
},
{
name: "resend limited", request: resendRequest, err: &identity.RateLimitedError{RetryAfter: 59 * time.Second},
statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "59",
},
{
name: "resend internal failure", request: resendRequest, err: errors.New("database unavailable"),
statusCode: http.StatusInternalServerError, code: api.ProblemCodeInternal,
},
} {
t.Run(test.name, func(t *testing.T) {
response := serveIdentityRequest(t, newIdentityRouter(t, &scriptedRegistration{err: test.err}), test.request)
if test.statusCode == http.StatusAccepted {
if response.Code != http.StatusAccepted || response.Body.String() != `{"status":"accepted"}` {
t.Fatalf("response = %d %s, want the neutral 202", response.Code, response.Body.String())
}
return
}
body := requireProblem(t, response, test.statusCode, test.code)
if test.pointer != "" && (len(body.Errors) != 1 || body.Errors[0].Pointer != test.pointer) {
t.Fatalf("errors = %v, want one error at %s", body.Errors, test.pointer)
}
if got := response.Header().Get("Retry-After"); got != test.retryAfter {
t.Fatalf("Retry-After = %q, want %q", got, test.retryAfter)
}
})
}
}
func TestRegistrationPassesTheRequestToTheUsecase(t *testing.T) {
registration := &scriptedRegistration{}
router := newIdentityRouter(t, registration)
response := serveIdentityRequest(t, router, identityRequest{
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
headers: map[string]string{"Idempotency-Key": testIdempotencyKey},
})
if response.Code != http.StatusAccepted {
t.Fatalf("status = %d: %s", response.Code, response.Body.String())
}
want := identity.RegisterCommand{
IdempotencyKey: testIdempotencyKey, Email: "candidate@example.com", Password: validPassword,
Scenario: "candidate", ConsentTextVersion: "c1-2026-10-01", ClientKey: "192.0.2.1",
}
if registration.register != want {
t.Fatalf("command = %+v, want %+v", registration.register, want)
}
}
@@ -27,7 +27,7 @@ func newMetricsTestRouter(t *testing.T, apiHandler func(*v1.HealthHandler, *prob
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
responder := problem.NewResponder(logger)
collector := metrics.New()
router, err := NewRouter(healthHandler, apiHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, collector, logger)
router, err := NewRouter(healthHandler, apiHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, collector, logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -73,8 +73,10 @@ func ClientIP(trusted []netip.Prefix) func(http.Handler) http.Handler {
// ClientAddr returns the client address that the ClientIP middleware stored.
// The second result is false when the middleware did not run or the peer
// address was not an IP address; a caller must then fail closed, for example
// by sharing one limiter bucket, instead of skipping its limit.
// address was not an IP address. A caller then skips its per-client limit
// and keeps its other limits: a shared "unknown" bucket would let one client
// lock out everyone, which is the worse failure than a missing per-client
// brake. The registration handler does this and counts nothing for it.
func ClientAddr(ctx context.Context) (netip.Addr, bool) {
addr, ok := ctx.Value(clientAddrKey{}).(netip.Addr)
return addr, ok && addr.IsValid()
@@ -275,7 +275,7 @@ func TestOrganizationSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -0,0 +1,22 @@
package problem
import (
"context"
"lincodex/backend/internal/adapter/primary/http/api"
)
// InvalidField is the validation_failed problem for one invalid value that
// only the application can detect, such as a stale consent text version. The
// pointer is a JSON Pointer into the location of the value; the body of the
// problem never echoes the value.
func InvalidField(ctx context.Context, location api.ProblemFieldLocation, pointer string) *api.ProblemStatusCode {
return validationProblem(ctx, []api.ProblemFieldError{fieldError(location, pointer, fieldCodeInvalid)})
}
// RateLimited is the 429 problem with the wait before a retry. The wait is
// rounded up to whole seconds, at least one.
func RateLimited(ctx context.Context, waitSeconds int32) *api.TooManyRequestsHeaders {
problem := New(ctx, api.ProblemCodeRateLimited)
return &api.TooManyRequestsHeaders{RetryAfter: api.NewOptInt32(max(waitSeconds, 1)), Response: problem.Response}
}
@@ -27,7 +27,7 @@ func TestRequestLogNamesTheRouteTemplateAndNoRequestData(t *testing.T) {
logger := slog.New(slog.NewJSONHandler(&logs, nil))
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
responder := problem.NewResponder(logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -4,6 +4,7 @@ import (
"fmt"
"log/slog"
"net/http"
"net/netip"
"github.com/go-chi/chi/v5"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
@@ -27,7 +28,8 @@ const (
// unknown routes under /api to 404, unsupported methods to 405, and any other
// server error or panic to 500 without exposing its text. Operation errors go
// through apiHandler.NewError. security decides every operation that requires
// a session; the generated server answers its rejection, and a request
// a session; trustedProxies are the reverse proxies whose X-Forwarded-For
// is believed; the generated server answers its rejection, and a request
// without the session cookie, with 401 unauthenticated through NewError.
func NewRouter(
health *v1.HealthHandler,
@@ -36,6 +38,7 @@ func NewRouter(
problems *problem.Responder,
collector httpmiddleware.RequestMetrics,
logger *slog.Logger,
trustedProxies []netip.Prefix,
) (http.Handler, error) {
apiServer, err := apiadapter.NewServer(
apiHandler,
@@ -55,6 +58,9 @@ func NewRouter(
// same route template as the metrics, never the raw path or query.
resolveRoute := operationRoute(apiServer)
router.Use(kitmiddleware.RequestID())
// The client address is resolved once, through the trusted proxies only,
// for the per-client rate limits of the handlers.
router.Use(httpmiddleware.ClientIP(trustedProxies))
router.Use(httpmiddleware.RequestLog(logger, resolveRoute, healthPath, readinessPath))
router.Use(httpmiddleware.CollectMetrics(collector, resolveRoute))
router.Group(func(operational chi.Router) {
@@ -393,7 +393,7 @@ func TestGeneratedServerSecurityOrder(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
security := &recordingSecurity{}
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), security, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), security, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -503,7 +503,7 @@ func TestQuestionnaireSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -715,7 +715,7 @@ func TestAssessmentSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -1010,7 +1010,7 @@ func TestNeedSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -1337,7 +1337,7 @@ func TestSupportCaseSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -1803,7 +1803,7 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -1910,7 +1910,7 @@ func TestConsentSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -2021,7 +2021,7 @@ func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) {
getHealthz: func(context.Context) (*api.HealthResponse, error) { panic(panicText) },
}
recorder := &requestRecorder{}
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), recorder, logger)
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), recorder, logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -2198,7 +2198,7 @@ func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler {
func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler, logger *slog.Logger) http.Handler {
t.Helper()
router, err := NewRouter(healthHandler, apiHandler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, apiHandler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -2210,7 +2210,7 @@ func newOverrideRouterWithMetrics(t *testing.T, collector *requestRecorder, getH
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz}
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), collector, logger)
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), collector, logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -32,19 +32,55 @@ type Handler struct {
api.UnimplementedHandler
health *HealthHandler
identity *IdentityHandler
problems *problem.Responder
}
var _ api.Handler = (*Handler)(nil)
func NewHandler(health *HealthHandler, problems *problem.Responder) *Handler {
return &Handler{health: health, problems: problems}
// HandlerOption adds the handler of a business area to Handler.
type HandlerOption func(*Handler)
// WithIdentity serves the registration operations. A nil handler leaves them
// to the embedded api.UnimplementedHandler, as when no database is
// configured.
func WithIdentity(identity *IdentityHandler) HandlerOption {
return func(handler *Handler) { handler.identity = identity }
}
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
handler := &Handler{health: health, problems: problems}
for _, option := range options {
option(handler)
}
return handler
}
func (handler *Handler) GetHealthz(ctx context.Context) (*api.HealthResponse, error) {
return handler.health.GetHealthz(ctx)
}
func (handler *Handler) RegisterAccount(
ctx context.Context,
request *api.RegistrationRequest,
params api.RegisterAccountParams,
) (api.RegisterAccountRes, error) {
if handler.identity == nil {
return handler.UnimplementedHandler.RegisterAccount(ctx, request, params)
}
return handler.identity.RegisterAccount(ctx, request, params)
}
func (handler *Handler) ResendEmailVerification(
ctx context.Context,
request *api.EmailVerificationResendRequest,
) (api.ResendEmailVerificationRes, error) {
if handler.identity == nil {
return handler.UnimplementedHandler.ResendEmailVerification(ctx, request)
}
return handler.identity.ResendEmailVerification(ctx, request)
}
// NewError implements api.Handler for errors returned by operations.
func (handler *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode {
return handler.problems.HandlerError(ctx, err)
@@ -0,0 +1,119 @@
package v1
import (
"context"
"errors"
"math"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/usecase/identity"
)
// AccountRegistration is what IdentityHandler needs from the registration
// usecase.
type AccountRegistration interface {
Register(ctx context.Context, command identity.RegisterCommand) error
ResendVerification(ctx context.Context, command identity.ResendCommand) error
}
// IdentityHandler serves the anonymous registration operations. Both answer
// the same neutral 202 whatever the state of the address; see the contract.
type IdentityHandler struct {
registration AccountRegistration
}
func NewIdentityHandler(registration AccountRegistration) *IdentityHandler {
return &IdentityHandler{registration: registration}
}
func (handler *IdentityHandler) RegisterAccount(
ctx context.Context,
request *api.RegistrationRequest,
params api.RegisterAccountParams,
) (api.RegisterAccountRes, error) {
err := handler.registration.Register(ctx, identity.RegisterCommand{
IdempotencyKey: params.IdempotencyKey,
Email: string(request.Email),
Password: string(request.Password),
Scenario: string(request.Scenario),
ConsentTextVersion: string(request.ConsentC1.TextVersion),
ClientKey: clientKey(ctx),
})
switch {
case err == nil:
return accepted(), nil
case errors.Is(err, identity.ErrInvalidField):
return (*api.RegisterAccountBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
case errors.Is(err, identity.ErrIdempotencyKeyReused):
return (*api.RegisterAccountUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func (handler *IdentityHandler) ResendEmailVerification(
ctx context.Context,
request *api.EmailVerificationResendRequest,
) (api.ResendEmailVerificationRes, error) {
err := handler.registration.ResendVerification(ctx, identity.ResendCommand{
Email: string(request.Email),
ClientKey: clientKey(ctx),
})
switch {
case err == nil:
return accepted(), nil
case errors.Is(err, identity.ErrInvalidField):
return (*api.ResendEmailVerificationBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func accepted() *api.IdentityRequestAccepted {
return &api.IdentityRequestAccepted{Status: api.IdentityRequestAcceptedStatusAccepted}
}
// clientKey is the limiter key of the client network address that the
// ClientIP middleware resolved. Without it, for example when the middleware
// is not mounted, the per-client limit is skipped and only the per-address
// limits apply: a shared bucket would let one client lock everyone out.
func clientKey(ctx context.Context) string {
address, ok := httpmiddleware.ClientAddr(ctx)
if !ok {
return ""
}
return httpmiddleware.LimiterKey(address)
}
func invalidFieldProblem(ctx context.Context, err error) *api.ProblemStatusCode {
field, ok := errors.AsType[*identity.InvalidFieldError](err)
if !ok {
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
}
location := api.ProblemFieldLocationBody
if field.Pointer == "/Idempotency-Key" {
location = api.ProblemFieldLocationHeader
}
return problem.InvalidField(ctx, location, field.Pointer)
}
func rateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) {
limited, ok := errors.AsType[*identity.RateLimitedError](err)
if !ok {
return nil, false
}
return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), true
}
// wholeSeconds rounds a wait up, so a client that waits the stated time is
// not refused again for the remainder.
func wholeSeconds(wait time.Duration) int32 {
return int32(min(math.Ceil(wait.Seconds()), math.MaxInt32))
}
@@ -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
}
@@ -33,6 +33,7 @@ func consumerTestConfig(t *testing.T) config.Config {
settings, err := config.LoadFromEnv(func(key string) (string, bool) {
value, ok := map[string]string{
"SEAWEEDFS_ACCESS_KEY": "test-access",
"IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab",
"SEAWEEDFS_SECRET_KEY": "test-secret",
"EMAIL_PROVIDER": "disabled",
"EMAIL_FROM": "no-reply@example.com",
+119
View File
@@ -0,0 +1,119 @@
package bootstrap
import (
"context"
"crypto/rand"
"fmt"
"log/slog"
"net/netip"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/argon2id"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
redisadapter "lincodex/backend/internal/adapter/secondary/redis"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
// identityPoolMaxConns bounds the connections of the registration requests:
// each holds one for a short transaction, after the password hash is done.
const identityPoolMaxConns = 8
// newTrustedProxies hands the configured reverse proxies to the router.
func newTrustedProxies(settings config.Config) []netip.Prefix { return settings.TrustedProxyCIDRs }
// newAPIHandler composes the handler of the public API from the business
// areas that are built. An area without a handler answers 501.
func newAPIHandler(health *v1.HealthHandler, problems *problem.Responder, identityHandler *v1.IdentityHandler) *v1.Handler {
return v1.NewHandler(health, problems, v1.WithIdentity(identityHandler))
}
// newIdentityHandler builds the registration operations and the PostgreSQL
// pool they own. Nothing connects here, so an unavailable database never
// blocks startup. It returns no handler when DATABASE_URL is unset, and the
// operations then answer 501. The application clock is time.Now.
func newIdentityHandler(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
cache *redisadapter.Cache,
metrics *prometheus.Metrics,
) (*v1.IdentityHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("registration is not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
keyring, err := newIdentityKeyring(settings, logger)
if err != nil {
return nil, nil, err
}
renderer, err := mailtemplate.NewRenderer(settings.AppPublicURL)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create mail renderer: %w", err)
}
// New deliveries are pinned to the transport and account configured now.
account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - mail provider account: %w", err)
}
hasher, err := argon2id.NewHasher(settings.PasswordHashConcurrency)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create password hasher: %w", err)
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, identityPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create pool: %w", err)
}
transactor := postgres.NewTransactor(pool)
registration, err := identity.NewRegistration(identity.RegistrationDependencies{
Transactor: transactor,
ConsentTexts: postgres.NewConsentStore(pool),
Idempotency: postgres.NewIdentityStore(pool).IdempotencyRecords(),
Consents: consent.NewService(transactor, time.Now),
Credentials: identity.NewCredentials(hasher),
Mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(renderer), account, time.Now),
Limiter: cache,
Keyring: keyring,
Clock: time.Now,
Metrics: metrics,
}, identity.RegistrationSettings{
MailMinInterval: settings.VerificationMailMinInterval,
MailDailyLimit: int64(settings.VerificationMailDailyLimit),
ClientHourlyLimit: int64(settings.IdentityClientHourlyLimit),
})
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create registration: %w", err)
}
// The HTTP server stops before this cleanup runs, so no request uses the
// pool while it closes.
return v1.NewIdentityHandler(registration), pool.Close, nil
}
// newIdentityKeyring keys the idempotency scopes and rate limit buckets with
// IDENTITY_KEY_SECRET. Only with IDENTITY_ALLOW_EPHEMERAL_KEY, which the
// configuration check demands for an unset secret, a random one is drawn for
// this process: idempotency records and counters written before a restart no
// longer match, and instances of one deployment do not agree.
func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity.Keyring, error) {
secret := []byte(settings.IdentityKeySecret)
if len(secret) == 0 {
secret = make([]byte, identity.MinKeySecretBytes)
if _, err := rand.Read(secret); err != nil {
return nil, fmt.Errorf("bootstrap.newIdentityKeyring - generate secret: %w", err)
}
logger.Warn("IDENTITY_ALLOW_EPHEMERAL_KEY is set and IDENTITY_KEY_SECRET is not; a random secret is used, so idempotency records and rate limits do not survive a restart")
}
keyring, err := identity.NewKeyring(secret)
if err != nil {
return nil, fmt.Errorf("bootstrap.newIdentityKeyring - create keyring: %w", err)
}
return keyring, nil
}
+1
View File
@@ -30,6 +30,7 @@ func loadMailConfig(t *testing.T, mail map[string]string) config.Config {
t.Helper()
values := map[string]string{
"SEAWEEDFS_ACCESS_KEY": "test-access",
"IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab",
"SEAWEEDFS_SECRET_KEY": "test-secret",
"EMAIL_FROM": "Lincodex <" + testSenderAddress + ">",
"APP_PUBLIC_URL": "http://localhost:8080",
+3 -1
View File
@@ -44,7 +44,9 @@ func initialize(
metrics.New,
newHealthHandler,
problem.NewResponder,
v1.NewHandler,
newAPIHandler,
newTrustedProxies,
newIdentityHandler,
v1.NewDenyAllSecurity,
httpadapter.NewRouter,
newOutboxRelay,
+29 -14
View File
@@ -45,24 +45,18 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
readiness := newReadiness(healthChecker, cache, storage)
healthHandler := newHealthHandler(readiness, config2)
responder := problem.NewResponder(logger)
handler := v1.NewHandler(healthHandler, responder)
denyAllSecurity := v1.NewDenyAllSecurity()
metrics := prometheus.New()
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, denyAllSecurity, responder, metrics, logger)
identityHandler, cleanup4, err := newIdentityHandler(ctx, config2, logger, cache, metrics)
if err != nil {
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
relay, cleanup4, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup5, err := newEventConsumers(ctx, config2, logger, metrics)
handler := newAPIHandler(healthHandler, responder, identityHandler)
denyAllSecurity := v1.NewDenyAllSecurity()
v := newTrustedProxies(config2)
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, denyAllSecurity, responder, metrics, logger, v)
if err != nil {
cleanup4()
cleanup3()
@@ -70,7 +64,15 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
worker, cleanup6, err := newJobWorker(ctx, config2, logger, metrics)
relay, cleanup5, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup6, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup5()
cleanup4()
@@ -79,7 +81,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup7, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
worker, cleanup7, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup6()
cleanup5()
@@ -89,7 +91,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup8, err := newDeliveryMetrics(ctx, config2, logger, metrics)
mailsenderWorker, cleanup8, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup7()
cleanup6()
@@ -100,8 +102,21 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup9, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
return application, func() {
cleanup9()
cleanup8()
cleanup7()
cleanup6()
+29
View File
@@ -32,6 +32,29 @@ func ParseEmailTokenPurpose(value string) (EmailTokenPurpose, error) {
}
}
// PendingRegistration holds the credentials of one registration, which wait
// on the verification token issued for it. A registration of an unverified
// address never changes the account row; confirming a token applies its own
// pending credentials, and only to a caller who proves the password of that
// registration. Nothing here is valid for login before the confirmation.
type PendingRegistration struct {
PasswordHash PasswordHash
Scenario Scenario
OnboardingStep OnboardingStep
}
// NewPendingRegistration builds the pending credentials of a registration
// with the first onboarding step of its scenario.
func NewPendingRegistration(hash PasswordHash, scenario Scenario) (PendingRegistration, error) {
if hash.IsZero() {
return PendingRegistration{}, invalidEmailToken("pending password hash must be built by NewPasswordHash")
}
if _, err := ParseScenario(string(scenario)); err != nil {
return PendingRegistration{}, fmt.Errorf("domain.NewPendingRegistration - validate scenario: %w", err)
}
return PendingRegistration{PasswordHash: hash, Scenario: scenario, OnboardingStep: scenario.InitialOnboardingStep()}, nil
}
// EmailToken is the stored record of a one-time token sent by email. It holds
// only the hash of the raw token. A token ends at most once: it is either
// consumed or invalidated, and it stops working at ExpiresAt.
@@ -45,6 +68,9 @@ type EmailToken struct {
ExpiresAt time.Time
ConsumedAt *time.Time
InvalidatedAt *time.Time
// Pending is set on the verification token of a registration and nil on
// a token that carries no credentials.
Pending *PendingRegistration
}
// NewEmailTokenInput describes a token to issue. RegistrationVersion is the
@@ -56,6 +82,8 @@ type NewEmailTokenInput struct {
RegistrationVersion int64
IssuedAt time.Time
Lifetime time.Duration
// Pending is optional; see PendingRegistration.
Pending *PendingRegistration
}
// NewEmailToken validates input and assigns a UUIDv7 identifier.
@@ -87,6 +115,7 @@ func NewEmailToken(input NewEmailTokenInput) (EmailToken, error) {
RegistrationVersion: input.RegistrationVersion,
CreatedAt: input.IssuedAt,
ExpiresAt: input.IssuedAt.Add(input.Lifetime),
Pending: input.Pending,
}, nil
}
+9 -1
View File
@@ -184,7 +184,15 @@ func (registration Registration) validate(location string) error {
return nil
}
// User is an account. Storage reconstructs it from trusted rows; new accounts
// User is an account. The PasswordHash, Scenario, and OnboardingStep of an
// unverified account are not authoritative: they hold what the first
// registration of the address stored only because the columns are mandatory.
// A repeat registration never changes them; the credentials that count are the
// pending ones on the verification token, and confirming that token applies
// them. No code may authenticate with, or trust the scenario of, an
// unverified account row.
//
// Storage reconstructs it from trusted rows; new accounts
// come from NewUser and changes from its methods.
type User struct {
ID uuid.UUID
@@ -67,6 +67,7 @@ type IdentityRepositories interface {
Users() UserRepository
EmailTokens() EmailTokenRepository
Sessions() SessionRepository
IdempotencyRecords() IdempotencyRepository
}
// UserRepository stores accounts. Lookups by email use the normalized form.
@@ -97,6 +98,18 @@ type UserRepository interface {
// deletes nothing.
UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error)
// AdvanceRegistration starts a new registration of an unverified account
// without changing its password hash, scenario, or onboarding step: the
// new registration carries them on its token (see
// domain.PendingRegistration). It applies only when the stored version
// still equals expectedVersion and the email is unverified, advances
// Version and RegistrationVersion by one in the same statement, sets the
// registration time, and deletes the C1 records with the source
// registration of the earlier registration like UpdateRegistration does;
// the caller grants the new C1 strictly after it. Otherwise it returns
// ErrUserVersionConflict.
AdvanceRegistration(ctx context.Context, id uuid.UUID, expectedVersion int64, at time.Time) (domain.User, error)
// MarkEmailVerified sets the verification time when the account is still
// unverified and still has registrationVersion, and returns the stored
// account. Otherwise it returns ErrUserVersionConflict. A confirmation
@@ -124,6 +137,11 @@ type EmailTokenRepository interface {
// ErrTokenHashConflict for a duplicate hash.
Insert(ctx context.Context, token domain.EmailToken) error
// LatestPending returns the pending credentials of the newest token that
// the registration version of the user has, or false when none carries
// any. A resend copies them to its new token.
LatestPending(ctx context.Context, userID uuid.UUID, registrationVersion int64) (domain.PendingRegistration, bool, error)
// InvalidateActive marks every unconsumed, not yet invalidated token of
// the user and purpose as invalidated at the given time, and returns how
// many it marked.
@@ -174,3 +192,51 @@ type SessionRepository interface {
// how many it revoked.
RevokeAllForUser(ctx context.Context, userID uuid.UUID, at time.Time) (int64, error)
}
// IdempotencyRetention is how long the replay record of a command with an
// Idempotency-Key lives, as the public contract states. After it the key may
// be accepted as new.
const IdempotencyRetention = 24 * time.Hour
// IdempotencyDigestSize is the size of the HMAC-SHA-256 values that identify
// and fingerprint a command.
const IdempotencyDigestSize = 32
// IdempotencyRecord is the replay record of a committed command. Both digests
// are HMAC-SHA-256 values computed with a server secret; the record holds
// neither the key, the email, nor the request body.
type IdempotencyRecord struct {
// Scope identifies the operation, the key, and the principal; for an
// anonymous operation the principal is the normalized email.
Scope [IdempotencyDigestSize]byte
// Fingerprint identifies the request that the key was first used with.
Fingerprint [IdempotencyDigestSize]byte
CreatedAt time.Time
ExpiresAt time.Time
}
// IdempotencyRepository stores the replay records of commands. Reserve runs
// in the transaction of the command it guards, so a stored record always
// belongs to a committed command.
type IdempotencyRepository interface {
// Reserve stores record unless a live record with the same scope exists.
// For a stored record it returns it with created true. For a live record
// it returns that record with created false and stores nothing; the
// caller compares the fingerprints to decide between a replay and a
// reused key. A concurrent Reserve with the same scope waits until the
// transaction of the first ends. A record past ExpiresAt is replaced.
// Every method that takes a time rejects the zero time.
Reserve(ctx context.Context, record IdempotencyRecord) (stored IdempotencyRecord, created bool, err error)
// Find returns the live record with the scope at the given time, or
// ErrIdempotencyRecordNotFound.
Find(ctx context.Context, scope [IdempotencyDigestSize]byte, at time.Time) (IdempotencyRecord, error)
// PurgeExpired deletes at most limit records that expired at or before
// the given time and returns how many it deleted. It never waits for a
// locked record.
PurgeExpired(ctx context.Context, at time.Time, limit int32) (int64, error)
}
// ErrIdempotencyRecordNotFound reports that no live record has the scope.
var ErrIdempotencyRecordNotFound = errors.New("idempotency record not found")
@@ -0,0 +1,39 @@
package outbound
import (
"context"
"errors"
"time"
)
// ErrInvalidRateLimitRule reports a rule without a positive window or limit,
// or a take without a key or a rule.
var ErrInvalidRateLimitRule = errors.New("invalid rate limit rule")
// RateLimitRule allows at most Limit takes per fixed Window. The window of a
// key starts with its first take and ends Window later.
type RateLimitRule struct {
Window time.Duration
Limit int64
}
// RateLimitDecision is the outcome of Take.
type RateLimitDecision struct {
// Allowed reports that the take was counted against every rule.
Allowed bool
// RetryAfter is, for a refused take, how long until every rule that
// refused it admits another one. It is zero for an allowed take.
RetryAfter time.Duration
}
// RateLimiter counts requests of one caller key against fixed windows. The
// counters are ephemeral: a restart or a flush of the store resets them, so
// a limiter is an abuse brake, never a record of what happened.
type RateLimiter interface {
// Take counts one request of key against every rule at once. It counts
// nothing when any rule refuses, so refused requests do not extend a
// window. The key is an opaque string that must not hold personal data
// in clear form; callers pass a keyed digest. A store failure returns
// an error and the caller decides how to fail.
Take(ctx context.Context, key string, rules ...RateLimitRule) (RateLimitDecision, error)
}
@@ -0,0 +1,51 @@
package identity
import (
"errors"
"fmt"
"time"
)
var (
// ErrRateLimited reports a request refused by the per-address limit.
// errors.As with *RateLimitedError yields the wait.
ErrRateLimited = errors.New("rate limit exceeded")
// ErrIdempotencyKeyReused reports a key that was first used with another
// request body for the same address.
ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request")
// 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")
)
// RateLimitedError carries how long the caller waits before a repeat can be
// accepted. It matches ErrRateLimited.
type RateLimitedError struct {
RetryAfter time.Duration
}
func (err *RateLimitedError) Error() string {
return fmt.Sprintf("rate limit exceeded, retry after %s", err.RetryAfter)
}
func (err *RateLimitedError) Unwrap() error { return ErrRateLimited }
// InvalidFieldError names the body field that failed and why, without the
// value. Pointer is the JSON Pointer of the field in the request body. It
// matches ErrInvalidField and also the domain error it wraps.
type InvalidFieldError struct {
Pointer string
Err error
}
func (err *InvalidFieldError) Error() string {
return fmt.Sprintf("invalid request field %s: %v", err.Pointer, err.Err)
}
func (err *InvalidFieldError) Unwrap() []error { return []error{ErrInvalidField, err.Err} }
func invalidField(pointer string, cause error) error {
return &InvalidFieldError{Pointer: pointer, Err: cause}
}
@@ -0,0 +1,90 @@
package identity
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"lincodex/backend/internal/port/outbound"
)
// MinKeySecretBytes is the shortest secret that NewKeyring accepts.
const MinKeySecretBytes = 32
// Domain-separation labels. Each purpose gets its own key derived from the
// one secret, so a digest made for one purpose never matches another.
const (
labelIdempotencyScope = "lincodex/identity/idempotency-scope/v1"
labelFingerprint = "lincodex/identity/request-fingerprint/v1"
labelEmailBucket = "lincodex/identity/email-bucket/v1"
labelClientBucket = "lincodex/identity/client-bucket/v1"
)
// Keyring computes the keyed digests of the anonymous identity operations:
// the idempotency scope, the request fingerprint, and the rate limit bucket
// of an email address. All of them are HMAC-SHA-256 values, so what the
// stores hold can neither confirm that an address is registered nor serve as
// an offline check of a password without the server secret.
type Keyring struct {
scopeKey []byte
fingerprintKey []byte
bucketKey []byte
clientKey []byte
}
// NewKeyring derives the purpose keys from secret.
func NewKeyring(secret []byte) (*Keyring, error) {
if len(secret) < MinKeySecretBytes {
return nil, fmt.Errorf("identity.NewKeyring - secret must have at least %d bytes", MinKeySecretBytes)
}
return &Keyring{
scopeKey: derive(secret, labelIdempotencyScope),
fingerprintKey: derive(secret, labelFingerprint),
bucketKey: derive(secret, labelEmailBucket),
clientKey: derive(secret, labelClientBucket),
}, nil
}
func derive(secret []byte, label string) []byte {
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(label))
return mac.Sum(nil)
}
// IdempotencyScope scopes a key by the operation, the key, and the
// normalized email. The parts are joined with NUL, which none of them can
// contain: operation names and keys are limited to printable ASCII and the
// email is printable ASCII.
func (keyring *Keyring) IdempotencyScope(operation, key, normalizedEmail string) [outbound.IdempotencyDigestSize]byte {
mac := hmac.New(sha256.New, keyring.scopeKey)
mac.Write([]byte(operation))
mac.Write([]byte{0})
mac.Write([]byte(key))
mac.Write([]byte{0})
mac.Write([]byte(normalizedEmail))
return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil))
}
// Fingerprint identifies a request by its canonical body.
func (keyring *Keyring) Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte {
mac := hmac.New(sha256.New, keyring.fingerprintKey)
mac.Write(canonicalBody)
return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil))
}
// EmailBucket names the rate limit counters of one address, whether or not
// an account exists for it, so a refusal does not reveal an account.
func (keyring *Keyring) EmailBucket(normalizedEmail string) string {
mac := hmac.New(sha256.New, keyring.bucketKey)
mac.Write([]byte(normalizedEmail))
return "identity:email:" + hex.EncodeToString(mac.Sum(nil))
}
// ClientBucket names the rate limit counters of one client from its opaque
// key, so the store never holds a network address in clear form.
func (keyring *Keyring) ClientBucket(clientKey string) string {
mac := hmac.New(sha256.New, keyring.clientKey)
mac.Write([]byte(clientKey))
return "identity:client:" + hex.EncodeToString(mac.Sum(nil))
}
@@ -0,0 +1,520 @@
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"
)
// 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, 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 (TASK-054).
// 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, 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)
}