feat(identity): register accounts and resend verification mail
This commit is contained in:
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
|
||||
}
|
||||
Reference in new issue
Block a user