feat(identity): confirm registration email atomically
This commit is contained in:
1 parent
8e7ce8d71c
commit
fade4e76e4
75 files changed
+4188
-403
No files matched your search
@@ -594,10 +594,18 @@ func (s *Server) handleCancelMyInvitationRequest(args [1]string, argsEscaped boo
|
||||
//
|
||||
// The server looks up the token by its hash and, in one transaction, checks that it is unused, not
|
||||
// expired, and bound to the current registration version, marks it used, and marks the email verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token answers
|
||||
// verification_token_expired; an unknown, used, replaced, or superseded token answers
|
||||
// verification_token_invalid; neither changes anything. For both, the client offers a new link and
|
||||
// sign-in, because the address may already be verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token of the current
|
||||
// registration answers verification_token_expired; an unknown, used, replaced, or superseded token
|
||||
// answers verification_token_invalid, even when that token is also expired. Neither refusal changes
|
||||
// anything. For both, the client offers a new link and sign-in, because the address may already be
|
||||
// verified.
|
||||
//
|
||||
// Confirmation also requires the password chosen for the registration that issued this token. A token
|
||||
// from a replaced registration cannot apply another registration's password or scenario. The server
|
||||
// checks the password against the token's pending password hash before consuming the token, then
|
||||
// applies that token's password, scenario, and onboarding step only if the current registration's C1
|
||||
// consent matches its registration version. A wrong password or token without pending registration
|
||||
// data answers verification_token_invalid and leaves the account and token unchanged.
|
||||
//
|
||||
// A repeated confirmation with an already used token is not an idempotent 200: exactly one request may
|
||||
// succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after
|
||||
@@ -606,7 +614,8 @@ func (s *Server) handleCancelMyInvitationRequest(args [1]string, argsEscaped boo
|
||||
// Success does not start a session: the link may be opened on another device or by a mail scanner, and
|
||||
// a session must come only from the password. The response returns the scenario and the saved
|
||||
// onboarding step so the client can continue after sign-in. The operation is rate-limited and requires
|
||||
// an allowed Origin.
|
||||
// an allowed Origin. Missing Origin, the special value `null`, or an Origin other than the configured
|
||||
// public application origin answers csrf_check_failed.
|
||||
//
|
||||
// POST /api/v1/identity/email-verifications
|
||||
func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
@@ -680,6 +689,16 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h
|
||||
ID: "ConfirmEmail",
|
||||
}
|
||||
)
|
||||
params, err := decodeConfirmEmailParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
request, rawBody, close, err := s.decodeConfirmEmailRequest(r)
|
||||
@@ -707,13 +726,18 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h
|
||||
OperationID: "ConfirmEmail",
|
||||
Body: request,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{},
|
||||
Raw: r,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "Origin",
|
||||
In: "header",
|
||||
}: params.Origin,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = *EmailVerificationRequest
|
||||
Params = struct{}
|
||||
Params = ConfirmEmailParams
|
||||
Response = ConfirmEmailRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
@@ -723,14 +747,14 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
nil,
|
||||
unpackConfirmEmailParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.ConfirmEmail(ctx, request)
|
||||
response, err = s.h.ConfirmEmail(ctx, request, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.ConfirmEmail(ctx, request)
|
||||
response, err = s.h.ConfirmEmail(ctx, request, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
@@ -9199,12 +9223,14 @@ func (s *Server) handleRaiseOrganizationInvitationSalaryRequest(args [2]string,
|
||||
//
|
||||
// - New email: the server creates an unverified account with the scenario and the first onboarding
|
||||
// step, records C1 with its text version and text hash, stores only the hash of a one-time
|
||||
// verification token, and queues the verification message, all in one transaction.
|
||||
// verification token plus the pending registration credentials, and queues the verification
|
||||
// message, all in one transaction.
|
||||
// - Registered but not verified: the server treats the request as a new registration of that address.
|
||||
// In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1
|
||||
// record, advances the registration version, invalidates every earlier verification token, and
|
||||
// queues a message with a new token. A pre-registration with someone else's password therefore
|
||||
// never survives the address owner's own registration.
|
||||
// In one transaction it advances the registration version, replaces the C1 record, invalidates
|
||||
// every earlier verification token, and queues a message with a new token carrying the pending
|
||||
// password hash, scenario, and onboarding step. The account's saved credentials and scenario change
|
||||
// only when the address owner confirms that token with its registration password, so a
|
||||
// pre-registration with someone else's password cannot take over the account.
|
||||
// - Verified: nothing changes. The server may queue a rate-limited "you already have an account"
|
||||
// notice to the address.
|
||||
//
|
||||
|
||||
@@ -12353,10 +12353,15 @@ func (s *EmailVerificationRequest) encodeFields(e *jx.Encoder) {
|
||||
e.FieldStart("token")
|
||||
s.Token.Encode(e)
|
||||
}
|
||||
{
|
||||
e.FieldStart("password")
|
||||
e.Str(s.Password)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfEmailVerificationRequest = [1]string{
|
||||
var jsonFieldsNameOfEmailVerificationRequest = [2]string{
|
||||
0: "token",
|
||||
1: "password",
|
||||
}
|
||||
|
||||
// Decode decodes EmailVerificationRequest from json.
|
||||
@@ -12378,6 +12383,18 @@ func (s *EmailVerificationRequest) Decode(d *jx.Decoder) error {
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"token\"")
|
||||
}
|
||||
case "password":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Password = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"password\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
@@ -12388,7 +12405,7 @@ func (s *EmailVerificationRequest) Decode(d *jx.Decoder) error {
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000001,
|
||||
0b00000011,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
|
||||
@@ -315,6 +315,98 @@ func decodeCancelMyInvitationParams(args [1]string, argsEscaped bool, r *http.Re
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ConfirmEmailParams is parameters of ConfirmEmail operation.
|
||||
type ConfirmEmailParams struct {
|
||||
// The exact configured public application origin. This optional parameter is read by the server as
|
||||
// empty when absent, so the operation answers csrf_check_failed rather than treating a missing Origin
|
||||
// as an allowed request.
|
||||
Origin OptString `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackConfirmEmailParams(packed middleware.Parameters) (params ConfirmEmailParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "Origin",
|
||||
In: "header",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Origin = v.(OptString)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeConfirmEmailParams(args [0]string, argsEscaped bool, r *http.Request) (params ConfirmEmailParams, _ error) {
|
||||
h := uri.NewHeaderDecoder(r.Header)
|
||||
// Decode header: Origin.
|
||||
if err := func() error {
|
||||
cfg := uri.HeaderParameterDecodingConfig{
|
||||
Name: "Origin",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.HasParam(cfg); err == nil {
|
||||
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotOriginVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotOriginVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Origin.SetTo(paramsDotOriginVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Origin.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 2048,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "Origin",
|
||||
In: "header",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// CreateMyAssessmentAttemptParams is parameters of CreateMyAssessmentAttempt operation.
|
||||
type CreateMyAssessmentAttemptParams struct {
|
||||
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
|
||||
|
||||
@@ -15,7 +15,7 @@ var (
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn7AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
"POST": "Content-Type,Origin",
|
||||
}
|
||||
rn57AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key",
|
||||
|
||||
@@ -5602,10 +5602,15 @@ func (s *DirectionCode) UnmarshalText(data []byte) error {
|
||||
|
||||
type EmailAddress string
|
||||
|
||||
// Token from the email verification link.
|
||||
// One-time token copied from the verification link and the password chosen for the registration that
|
||||
// issued it. The password is never included in the link.
|
||||
// Ref: #/components/schemas/EmailVerificationRequest
|
||||
type EmailVerificationRequest struct {
|
||||
Token VerificationToken `json:"token"`
|
||||
// Password chosen for the registration that issued this token. It is sent in the request body and
|
||||
// never appears in the verification link. The server applies NFKC normalization and the login length
|
||||
// bounds, without reapplying the current new-registration blocklist.
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// GetToken returns the value of Token.
|
||||
@@ -5613,11 +5618,21 @@ func (s *EmailVerificationRequest) GetToken() VerificationToken {
|
||||
return s.Token
|
||||
}
|
||||
|
||||
// GetPassword returns the value of Password.
|
||||
func (s *EmailVerificationRequest) GetPassword() string {
|
||||
return s.Password
|
||||
}
|
||||
|
||||
// SetToken sets the value of Token.
|
||||
func (s *EmailVerificationRequest) SetToken(val VerificationToken) {
|
||||
s.Token = val
|
||||
}
|
||||
|
||||
// SetPassword sets the value of Password.
|
||||
func (s *EmailVerificationRequest) SetPassword(val string) {
|
||||
s.Password = val
|
||||
}
|
||||
|
||||
// Address that should receive a new verification link.
|
||||
// Ref: #/components/schemas/EmailVerificationResendRequest
|
||||
type EmailVerificationResendRequest struct {
|
||||
|
||||
@@ -107,10 +107,18 @@ type Handler interface {
|
||||
//
|
||||
// The server looks up the token by its hash and, in one transaction, checks that it is unused, not
|
||||
// expired, and bound to the current registration version, marks it used, and marks the email verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token answers
|
||||
// verification_token_expired; an unknown, used, replaced, or superseded token answers
|
||||
// verification_token_invalid; neither changes anything. For both, the client offers a new link and
|
||||
// sign-in, because the address may already be verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token of the current
|
||||
// registration answers verification_token_expired; an unknown, used, replaced, or superseded token
|
||||
// answers verification_token_invalid, even when that token is also expired. Neither refusal changes
|
||||
// anything. For both, the client offers a new link and sign-in, because the address may already be
|
||||
// verified.
|
||||
//
|
||||
// Confirmation also requires the password chosen for the registration that issued this token. A token
|
||||
// from a replaced registration cannot apply another registration's password or scenario. The server
|
||||
// checks the password against the token's pending password hash before consuming the token, then
|
||||
// applies that token's password, scenario, and onboarding step only if the current registration's C1
|
||||
// consent matches its registration version. A wrong password or token without pending registration
|
||||
// data answers verification_token_invalid and leaves the account and token unchanged.
|
||||
//
|
||||
// A repeated confirmation with an already used token is not an idempotent 200: exactly one request may
|
||||
// succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after
|
||||
@@ -119,10 +127,11 @@ type Handler interface {
|
||||
// Success does not start a session: the link may be opened on another device or by a mail scanner, and
|
||||
// a session must come only from the password. The response returns the scenario and the saved
|
||||
// onboarding step so the client can continue after sign-in. The operation is rate-limited and requires
|
||||
// an allowed Origin.
|
||||
// an allowed Origin. Missing Origin, the special value `null`, or an Origin other than the configured
|
||||
// public application origin answers csrf_check_failed.
|
||||
//
|
||||
// POST /api/v1/identity/email-verifications
|
||||
ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (ConfirmEmailRes, error)
|
||||
ConfirmEmail(ctx context.Context, req *EmailVerificationRequest, params ConfirmEmailParams) (ConfirmEmailRes, error)
|
||||
// CreateMyAssessmentAttempt implements CreateMyAssessmentAttempt operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
|
||||
@@ -1150,12 +1159,14 @@ type Handler interface {
|
||||
//
|
||||
// - New email: the server creates an unverified account with the scenario and the first onboarding
|
||||
// step, records C1 with its text version and text hash, stores only the hash of a one-time
|
||||
// verification token, and queues the verification message, all in one transaction.
|
||||
// verification token plus the pending registration credentials, and queues the verification
|
||||
// message, all in one transaction.
|
||||
// - Registered but not verified: the server treats the request as a new registration of that address.
|
||||
// In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1
|
||||
// record, advances the registration version, invalidates every earlier verification token, and
|
||||
// queues a message with a new token. A pre-registration with someone else's password therefore
|
||||
// never survives the address owner's own registration.
|
||||
// In one transaction it advances the registration version, replaces the C1 record, invalidates
|
||||
// every earlier verification token, and queues a message with a new token carrying the pending
|
||||
// password hash, scenario, and onboarding step. The account's saved credentials and scenario change
|
||||
// only when the address owner confirms that token with its registration password, so a
|
||||
// pre-registration with someone else's password cannot take over the account.
|
||||
// - Verified: nothing changes. The server may queue a rate-limited "you already have an account"
|
||||
// notice to the address.
|
||||
//
|
||||
|
||||
@@ -118,10 +118,18 @@ func (UnimplementedHandler) CancelMyInvitation(ctx context.Context, req *Invitat
|
||||
//
|
||||
// The server looks up the token by its hash and, in one transaction, checks that it is unused, not
|
||||
// expired, and bound to the current registration version, marks it used, and marks the email verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token answers
|
||||
// verification_token_expired; an unknown, used, replaced, or superseded token answers
|
||||
// verification_token_invalid; neither changes anything. For both, the client offers a new link and
|
||||
// sign-in, because the address may already be verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token of the current
|
||||
// registration answers verification_token_expired; an unknown, used, replaced, or superseded token
|
||||
// answers verification_token_invalid, even when that token is also expired. Neither refusal changes
|
||||
// anything. For both, the client offers a new link and sign-in, because the address may already be
|
||||
// verified.
|
||||
//
|
||||
// Confirmation also requires the password chosen for the registration that issued this token. A token
|
||||
// from a replaced registration cannot apply another registration's password or scenario. The server
|
||||
// checks the password against the token's pending password hash before consuming the token, then
|
||||
// applies that token's password, scenario, and onboarding step only if the current registration's C1
|
||||
// consent matches its registration version. A wrong password or token without pending registration
|
||||
// data answers verification_token_invalid and leaves the account and token unchanged.
|
||||
//
|
||||
// A repeated confirmation with an already used token is not an idempotent 200: exactly one request may
|
||||
// succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after
|
||||
@@ -130,10 +138,11 @@ func (UnimplementedHandler) CancelMyInvitation(ctx context.Context, req *Invitat
|
||||
// Success does not start a session: the link may be opened on another device or by a mail scanner, and
|
||||
// a session must come only from the password. The response returns the scenario and the saved
|
||||
// onboarding step so the client can continue after sign-in. The operation is rate-limited and requires
|
||||
// an allowed Origin.
|
||||
// an allowed Origin. Missing Origin, the special value `null`, or an Origin other than the configured
|
||||
// public application origin answers csrf_check_failed.
|
||||
//
|
||||
// POST /api/v1/identity/email-verifications
|
||||
func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (r ConfirmEmailRes, _ error) {
|
||||
func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerificationRequest, params ConfirmEmailParams) (r ConfirmEmailRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
@@ -1278,12 +1287,14 @@ func (UnimplementedHandler) RaiseOrganizationInvitationSalary(ctx context.Contex
|
||||
//
|
||||
// - New email: the server creates an unverified account with the scenario and the first onboarding
|
||||
// step, records C1 with its text version and text hash, stores only the hash of a one-time
|
||||
// verification token, and queues the verification message, all in one transaction.
|
||||
// verification token plus the pending registration credentials, and queues the verification
|
||||
// message, all in one transaction.
|
||||
// - Registered but not verified: the server treats the request as a new registration of that address.
|
||||
// In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1
|
||||
// record, advances the registration version, invalidates every earlier verification token, and
|
||||
// queues a message with a new token. A pre-registration with someone else's password therefore
|
||||
// never survives the address owner's own registration.
|
||||
// In one transaction it advances the registration version, replaces the C1 record, invalidates
|
||||
// every earlier verification token, and queues a message with a new token carrying the pending
|
||||
// password hash, scenario, and onboarding step. The account's saved credentials and scenario change
|
||||
// only when the address owner confirms that token with its registration password, so a
|
||||
// pre-registration with someone else's password cannot take over the account.
|
||||
// - Verified: nothing changes. The server may queue a rate-limited "you already have an account"
|
||||
// notice to the address.
|
||||
//
|
||||
|
||||
@@ -5871,6 +5871,29 @@ func (s *EmailVerificationRequest) Validate() error {
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 128,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.Password)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "password",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"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/domain"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
const confirmationPath = "/api/v1/identity/email-verifications"
|
||||
|
||||
type scriptedConfirmation struct {
|
||||
err error
|
||||
command identity.ConfirmCommand
|
||||
result identity.ConfirmationResult
|
||||
calls int
|
||||
}
|
||||
|
||||
func (confirmation *scriptedConfirmation) Confirm(_ context.Context, command identity.ConfirmCommand) (identity.ConfirmationResult, error) {
|
||||
confirmation.calls++
|
||||
confirmation.command = command
|
||||
return confirmation.result, confirmation.err
|
||||
}
|
||||
|
||||
func newConfirmationRouter(t *testing.T, confirmation v1.EmailConfirmation) http.Handler {
|
||||
t.Helper()
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
||||
identityHandler := v1.NewIdentityHandler(nil, v1.WithEmailConfirmation(confirmation, "https://app.example"))
|
||||
handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(identityHandler))
|
||||
return newTestRouterWithAPI(t, healthHandler, handler, logger)
|
||||
}
|
||||
|
||||
func TestConfirmEmailRequiresConfiguredOriginBeforeUsecase(t *testing.T) {
|
||||
confirmation := &scriptedConfirmation{}
|
||||
router := newConfirmationRouter(t, confirmation)
|
||||
body := `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
origin string
|
||||
set bool
|
||||
}{
|
||||
{name: "missing"},
|
||||
{name: "null", origin: "null", set: true},
|
||||
{name: "foreign", origin: "https://foreign.example", set: true},
|
||||
{name: "same host with different port", origin: "https://app.example:443", set: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
before := confirmation.calls
|
||||
headers := map[string]string{}
|
||||
if test.set {
|
||||
headers["Origin"] = test.origin
|
||||
}
|
||||
response := serveIdentityRequest(t, router, identityRequest{
|
||||
method: http.MethodPost, path: confirmationPath, body: body, headers: headers,
|
||||
})
|
||||
requireProblem(t, response, http.StatusForbidden, api.ProblemCodeCsrfCheckFailed)
|
||||
if confirmation.calls != before {
|
||||
t.Fatal("confirmation usecase ran before the origin check")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmEmailPassesRequestAndReturnsSavedDestination(t *testing.T) {
|
||||
confirmation := &scriptedConfirmation{result: identity.ConfirmationResult{
|
||||
Scenario: domain.ScenarioCandidate,
|
||||
OnboardingStep: domain.OnboardingStepCandidateProfile,
|
||||
}}
|
||||
router := newConfirmationRouter(t, confirmation)
|
||||
token := strings.Repeat("A", 64)
|
||||
password := `correct "quoted" horse battery staple`
|
||||
requestBody, err := json.Marshal(struct {
|
||||
Token string `json:"token"`
|
||||
Password string `json:"password"`
|
||||
}{Token: token, Password: password})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response := serveIdentityRequest(t, router, identityRequest{
|
||||
method: http.MethodPost,
|
||||
path: confirmationPath,
|
||||
body: string(requestBody),
|
||||
headers: map[string]string{"Origin": "https://app.example"},
|
||||
})
|
||||
if response.Code != http.StatusOK || response.Header().Get("Set-Cookie") != "" {
|
||||
t.Fatalf("response = %d, Set-Cookie %q, body %s", response.Code, response.Header().Get("Set-Cookie"), response.Body.String())
|
||||
}
|
||||
var result map[string]any
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if result["email_verified"] != true || result["scenario"] != "candidate" || result["onboarding_step"] != "candidate_profile" {
|
||||
t.Fatalf("response body = %v", result)
|
||||
}
|
||||
if confirmation.calls != 1 || confirmation.command.Token != token || confirmation.command.Password != password || confirmation.command.ClientKey == "" {
|
||||
t.Fatalf("confirmation call = %d, command %+v", confirmation.calls, confirmation.command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmEmailRequiresPassword(t *testing.T) {
|
||||
confirmation := &scriptedConfirmation{}
|
||||
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
|
||||
method: http.MethodPost,
|
||||
path: confirmationPath,
|
||||
body: `{"token":"` + strings.Repeat("A", 64) + `"}`,
|
||||
headers: map[string]string{"Origin": "https://app.example"},
|
||||
})
|
||||
requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
|
||||
if confirmation.calls != 0 {
|
||||
t.Fatal("confirmation usecase ran without the required registration password")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmEmailMapsExpectedUsecaseFailures(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
err error
|
||||
statusCode int
|
||||
code api.ProblemCode
|
||||
retryAfter string
|
||||
}{
|
||||
{name: "invalid token", err: identity.ErrVerificationTokenInvalid, statusCode: http.StatusBadRequest, code: api.ProblemCodeVerificationTokenInvalid},
|
||||
{name: "expired token", err: identity.ErrVerificationTokenExpired, statusCode: http.StatusBadRequest, code: api.ProblemCodeVerificationTokenExpired},
|
||||
{name: "limited", err: &identity.RateLimitedError{RetryAfter: 1500 * time.Millisecond}, statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "2"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
confirmation := &scriptedConfirmation{err: test.err}
|
||||
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
|
||||
method: http.MethodPost,
|
||||
path: confirmationPath,
|
||||
body: `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`,
|
||||
headers: map[string]string{"Origin": "https://app.example"},
|
||||
})
|
||||
requireProblem(t, response, test.statusCode, test.code)
|
||||
if got := response.Header().Get("Retry-After"); got != test.retryAfter {
|
||||
t.Fatalf("Retry-After = %q, want %q", got, test.retryAfter)
|
||||
}
|
||||
if confirmation.calls != 1 {
|
||||
t.Fatalf("confirmation calls = %d, want 1", confirmation.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmEmailDoesNotConvertUnexpectedUsecaseErrors(t *testing.T) {
|
||||
confirmation := &scriptedConfirmation{err: errors.New("storage unavailable")}
|
||||
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
|
||||
method: http.MethodPost,
|
||||
path: confirmationPath,
|
||||
body: `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`,
|
||||
headers: map[string]string{"Origin": "https://app.example"},
|
||||
})
|
||||
requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
|
||||
if strings.Contains(response.Body.String(), "storage unavailable") {
|
||||
t.Fatal("internal error text leaked into the response")
|
||||
}
|
||||
}
|
||||
@@ -180,7 +180,7 @@ func TestIdentityOperationsBeforeImplementation(t *testing.T) {
|
||||
name: "public email confirmation",
|
||||
request: identityRequest{
|
||||
method: http.MethodPost, path: "/api/v1/identity/email-verifications",
|
||||
body: `{"token":"q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE"}`,
|
||||
body: `{"token":"q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE","password":"correct horse battery staple"}`,
|
||||
},
|
||||
statusCode: http.StatusNotImplemented,
|
||||
code: api.ProblemCodeNotImplemented,
|
||||
|
||||
@@ -81,6 +81,17 @@ func (handler *Handler) ResendEmailVerification(
|
||||
return handler.identity.ResendEmailVerification(ctx, request)
|
||||
}
|
||||
|
||||
func (handler *Handler) ConfirmEmail(
|
||||
ctx context.Context,
|
||||
request *api.EmailVerificationRequest,
|
||||
params api.ConfirmEmailParams,
|
||||
) (api.ConfirmEmailRes, error) {
|
||||
if handler.identity == nil || handler.identity.confirmation == nil {
|
||||
return handler.UnimplementedHandler.ConfirmEmail(ctx, request, params)
|
||||
}
|
||||
return handler.identity.ConfirmEmail(ctx, request, params)
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
@@ -19,14 +20,37 @@ type AccountRegistration interface {
|
||||
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
|
||||
// EmailConfirmation is what IdentityHandler needs from the confirmation usecase.
|
||||
type EmailConfirmation interface {
|
||||
Confirm(ctx context.Context, command identity.ConfirmCommand) (identity.ConfirmationResult, error)
|
||||
}
|
||||
|
||||
func NewIdentityHandler(registration AccountRegistration) *IdentityHandler {
|
||||
return &IdentityHandler{registration: registration}
|
||||
// IdentityHandlerOption configures an optional identity operation.
|
||||
type IdentityHandlerOption func(*IdentityHandler)
|
||||
|
||||
// IdentityHandler serves anonymous registration, resend, and confirmation
|
||||
// operations.
|
||||
type IdentityHandler struct {
|
||||
registration AccountRegistration
|
||||
confirmation EmailConfirmation
|
||||
confirmationOrigin string
|
||||
}
|
||||
|
||||
func NewIdentityHandler(registration AccountRegistration, options ...IdentityHandlerOption) *IdentityHandler {
|
||||
handler := &IdentityHandler{registration: registration}
|
||||
for _, option := range options {
|
||||
option(handler)
|
||||
}
|
||||
return handler
|
||||
}
|
||||
|
||||
// WithEmailConfirmation serves ConfirmEmail and compares Origin with the
|
||||
// configured public application origin. The request Host is never trusted.
|
||||
func WithEmailConfirmation(confirmation EmailConfirmation, publicOrigin string) IdentityHandlerOption {
|
||||
return func(handler *IdentityHandler) {
|
||||
handler.confirmation = confirmation
|
||||
handler.confirmationOrigin = publicOrigin
|
||||
}
|
||||
}
|
||||
|
||||
func (handler *IdentityHandler) RegisterAccount(
|
||||
@@ -60,6 +84,9 @@ func (handler *IdentityHandler) ResendEmailVerification(
|
||||
ctx context.Context,
|
||||
request *api.EmailVerificationResendRequest,
|
||||
) (api.ResendEmailVerificationRes, error) {
|
||||
if handler.registration == nil {
|
||||
return nil, errors.New("IdentityHandler.ResendEmailVerification - registration is not configured")
|
||||
}
|
||||
err := handler.registration.ResendVerification(ctx, identity.ResendCommand{
|
||||
Email: string(request.Email),
|
||||
ClientKey: clientKey(ctx),
|
||||
@@ -76,6 +103,42 @@ func (handler *IdentityHandler) ResendEmailVerification(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (handler *IdentityHandler) ConfirmEmail(
|
||||
ctx context.Context,
|
||||
request *api.EmailVerificationRequest,
|
||||
params api.ConfirmEmailParams,
|
||||
) (api.ConfirmEmailRes, error) {
|
||||
if handler.confirmation == nil {
|
||||
return nil, errors.New("IdentityHandler.ConfirmEmail - confirmation is not configured")
|
||||
}
|
||||
origin, ok := params.Origin.Get()
|
||||
if !ok || strings.TrimSpace(origin) == "" || origin != handler.confirmationOrigin {
|
||||
return (*api.ConfirmEmailForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
|
||||
result, err := handler.confirmation.Confirm(ctx, identity.ConfirmCommand{
|
||||
Token: string(request.Token),
|
||||
Password: request.Password,
|
||||
ClientKey: clientKey(ctx),
|
||||
})
|
||||
switch {
|
||||
case err == nil:
|
||||
return &api.EmailVerificationResult{
|
||||
EmailVerified: api.EmailVerificationResultEmailVerifiedTrue,
|
||||
Scenario: api.AccountScenario(result.Scenario),
|
||||
OnboardingStep: api.OnboardingStep(result.OnboardingStep),
|
||||
}, nil
|
||||
case errors.Is(err, identity.ErrVerificationTokenInvalid):
|
||||
return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenInvalid).Response), nil
|
||||
case errors.Is(err, identity.ErrVerificationTokenExpired):
|
||||
return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenExpired).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}
|
||||
}
|
||||
|
||||
@@ -144,7 +144,11 @@ func (ledger consentLedger) Grant(ctx context.Context, grant domain.ConsentGrant
|
||||
TextVersion: string(grant.TextVersion()),
|
||||
TextHash: hash[:],
|
||||
Source: string(grant.Source()),
|
||||
GrantedAt: pgTime(grant.GrantedAt()),
|
||||
RegistrationVersion: pgtype.Int8{
|
||||
Int64: grant.RegistrationVersion(),
|
||||
Valid: grant.RegistrationVersion() > 0,
|
||||
},
|
||||
GrantedAt: pgTime(grant.GrantedAt()),
|
||||
})
|
||||
if err == nil {
|
||||
record, err := consentRecordFromRow(consentRecordRow(row))
|
||||
@@ -251,6 +255,25 @@ func (ledger consentLedger) Current(ctx context.Context, subjectID uuid.UUID, pu
|
||||
return consentRecordFromRow(consentRecordRow(row))
|
||||
}
|
||||
|
||||
func (ledger consentLedger) LockRegistration(
|
||||
ctx context.Context,
|
||||
subjectID uuid.UUID,
|
||||
registrationVersion int64,
|
||||
) (domain.ConsentRecord, error) {
|
||||
const location = "consentLedger.LockRegistration"
|
||||
if subjectID == uuid.Nil || registrationVersion <= 0 {
|
||||
return domain.ConsentRecord{}, fmt.Errorf("%s - subject and registration version must be set: %w", location, domain.ErrInvalidConsent)
|
||||
}
|
||||
row, err := ledger.queries.LockRegistrationConsentRecord(ctx, sqlc.LockRegistrationConsentRecordParams{
|
||||
SubjectID: pgUUID(subjectID),
|
||||
RegistrationVersion: pgtype.Int8{Int64: registrationVersion, Valid: true},
|
||||
})
|
||||
if err != nil {
|
||||
return domain.ConsentRecord{}, fmt.Errorf("%s - lock registration C1: %w", location, mapConsentNoRows(err, outbound.ErrConsentNotFound))
|
||||
}
|
||||
return consentRecordFromRow(consentRecordRow(row))
|
||||
}
|
||||
|
||||
func (ledger consentLedger) CurrentContact(ctx context.Context, subjectID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) {
|
||||
rows, err := ledger.queries.ListCurrentContactConsentRecords(ctx, sqlc.ListCurrentContactConsentRecordsParams{
|
||||
SubjectID: pgUUID(subjectID),
|
||||
@@ -312,6 +335,7 @@ type consentRecordRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -331,6 +355,7 @@ func consentRecordFromRow(row consentRecordRow) (domain.ConsentRecord, error) {
|
||||
TextVersion: row.TextVersion,
|
||||
TextHash: row.TextHash,
|
||||
Source: row.Source,
|
||||
RegistrationVersion: optionalConsentRegistrationVersion(row.RegistrationVersion),
|
||||
State: row.State,
|
||||
GrantedAt: row.GrantedAt.Time,
|
||||
RevokedAt: optionalTime(row.RevokedAt),
|
||||
@@ -347,6 +372,13 @@ func consentRecordFromRow(row consentRecordRow) (domain.ConsentRecord, error) {
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func optionalConsentRegistrationVersion(value pgtype.Int8) int64 {
|
||||
if !value.Valid {
|
||||
return 0
|
||||
}
|
||||
return value.Int64
|
||||
}
|
||||
|
||||
func consentRecordsFromRows[Row any](rows []Row, convert func(Row) consentRecordRow) ([]domain.ConsentRecord, error) {
|
||||
records := make([]domain.ConsentRecord, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
|
||||
@@ -152,14 +152,15 @@ func TestConsentRecordFromRowMapsNullableScope(t *testing.T) {
|
||||
}
|
||||
|
||||
personalData, err := consentRecordFromRow(consentRecordRow{
|
||||
ID: pgUUID(uuid.Must(uuid.NewV7())),
|
||||
SubjectID: pgUUID(subject),
|
||||
Purpose: "c1",
|
||||
TextVersion: "c1-2026-10-01",
|
||||
TextHash: hash[:],
|
||||
Source: "registration",
|
||||
GrantedAt: pgTime(grantedAt),
|
||||
State: "active",
|
||||
ID: pgUUID(uuid.Must(uuid.NewV7())),
|
||||
SubjectID: pgUUID(subject),
|
||||
Purpose: "c1",
|
||||
TextVersion: "c1-2026-10-01",
|
||||
TextHash: hash[:],
|
||||
Source: "registration",
|
||||
RegistrationVersion: pgtype.Int8{Int64: 1, Valid: true},
|
||||
GrantedAt: pgTime(grantedAt),
|
||||
State: "active",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("consentRecordFromRow(C1) error = %v", err)
|
||||
|
||||
@@ -274,6 +274,34 @@ func (repository userRepository) MarkEmailVerified(
|
||||
return userFromRow(row)
|
||||
}
|
||||
|
||||
func (repository userRepository) ConfirmEmail(
|
||||
ctx context.Context,
|
||||
id uuid.UUID,
|
||||
registrationVersion int64,
|
||||
pending domain.PendingRegistration,
|
||||
at time.Time,
|
||||
) (domain.User, error) {
|
||||
const location = "userRepository.ConfirmEmail"
|
||||
if err := requireTime(location, at, domain.ErrInvalidUser); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if pending.PasswordHash.IsZero() || !pending.Scenario.AllowsStep(pending.OnboardingStep) {
|
||||
return domain.User{}, fmt.Errorf("%s - pending registration was not built by domain.NewPendingRegistration: %w", location, domain.ErrInvalidUser)
|
||||
}
|
||||
row, err := repository.queries.ConfirmUserEmail(ctx, sqlc.ConfirmUserEmailParams{
|
||||
ID: pgUUID(id),
|
||||
RegistrationVersion: registrationVersion,
|
||||
PasswordHash: pending.PasswordHash.PHC(),
|
||||
Scenario: string(pending.Scenario),
|
||||
OnboardingStep: string(pending.OnboardingStep),
|
||||
VerifiedAt: pgTime(at),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("%s - apply pending registration: %w", location, mapNoRows(err, outbound.ErrUserVersionConflict))
|
||||
}
|
||||
return userFromRow(row)
|
||||
}
|
||||
|
||||
func (repository userRepository) DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error) {
|
||||
if err := requireTime("userRepository.DeleteUnverifiedRegisteredBefore", cutoff, domain.ErrInvalidUser); err != nil {
|
||||
return 0, err
|
||||
@@ -342,6 +370,35 @@ type emailTokenRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (repository emailTokenRepository) FindByHash(
|
||||
ctx context.Context,
|
||||
hash domain.SecretTokenHash,
|
||||
purpose domain.EmailTokenPurpose,
|
||||
) (domain.EmailToken, error) {
|
||||
const location = "emailTokenRepository.FindByHash"
|
||||
if hash.IsZero() {
|
||||
return domain.EmailToken{}, fmt.Errorf("%s - token hash must be set: %w", location, domain.ErrInvalidEmailToken)
|
||||
}
|
||||
if _, err := domain.ParseEmailTokenPurpose(string(purpose)); err != nil {
|
||||
return domain.EmailToken{}, fmt.Errorf("%s - validate purpose: %w", location, err)
|
||||
}
|
||||
row, err := repository.queries.GetEmailTokenByHash(ctx, sqlc.GetEmailTokenByHashParams{
|
||||
TokenHash: hash[:],
|
||||
Purpose: string(purpose),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.EmailToken{}, fmt.Errorf("%s - select email token: %w", location, mapNoRows(err, outbound.ErrEmailTokenNotFound))
|
||||
}
|
||||
owner, err := repository.queries.GetUserByID(ctx, row.UserID)
|
||||
if err != nil {
|
||||
return domain.EmailToken{}, fmt.Errorf("%s - read token owner: %w", location, mapNoRows(err, outbound.ErrEmailTokenInvalidated))
|
||||
}
|
||||
if owner.RegistrationVersion != row.RegistrationVersion {
|
||||
return domain.EmailToken{}, fmt.Errorf("%s - token belongs to an earlier registration: %w", location, outbound.ErrEmailTokenInvalidated)
|
||||
}
|
||||
return emailTokenFromRow(row)
|
||||
}
|
||||
|
||||
func (repository emailTokenRepository) Insert(ctx context.Context, token domain.EmailToken) error {
|
||||
if token.ID == uuid.Nil || token.TokenHash.IsZero() {
|
||||
return fmt.Errorf("emailTokenRepository.Insert - token was not built by domain.NewEmailToken: %w", domain.ErrInvalidEmailToken)
|
||||
@@ -445,7 +502,7 @@ func (repository emailTokenRepository) Consume(
|
||||
ConsumedAt: pgTime(at),
|
||||
})
|
||||
if err == nil {
|
||||
return emailTokenFromRow(row)
|
||||
return emailTokenFromRow(sqlc.EmailToken(row))
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.EmailToken{}, fmt.Errorf("emailTokenRepository.Consume - update email token: %w", mapIdentityError(err))
|
||||
|
||||
@@ -52,6 +52,7 @@ SELECT
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -81,6 +82,7 @@ type GetContactConsentRecordByInvitationRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -102,6 +104,7 @@ func (q *Queries) GetContactConsentRecordByInvitation(ctx context.Context, arg G
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -123,6 +126,7 @@ SELECT
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -154,6 +158,7 @@ type GetCurrentConsentRecordRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -176,6 +181,7 @@ func (q *Queries) GetCurrentConsentRecord(ctx context.Context, arg GetCurrentCon
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -234,6 +240,7 @@ SELECT
|
||||
record.text_version,
|
||||
record.text_hash,
|
||||
record.source,
|
||||
record.registration_version,
|
||||
record.organization_id,
|
||||
record.organization_name,
|
||||
record.field_set,
|
||||
@@ -277,6 +284,7 @@ type GetUnrevokedConsentRecordByVersionRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -298,6 +306,7 @@ func (q *Queries) GetUnrevokedConsentRecordByVersion(ctx context.Context, arg Ge
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -319,6 +328,7 @@ INSERT INTO consent_records (
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
granted_at
|
||||
) VALUES (
|
||||
$1,
|
||||
@@ -327,7 +337,8 @@ INSERT INTO consent_records (
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7
|
||||
$7::bigint,
|
||||
$8
|
||||
)
|
||||
ON CONFLICT (subject_id, purpose, text_version)
|
||||
WHERE revoked_at IS NULL AND purpose <> 'c4'
|
||||
@@ -339,6 +350,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -364,13 +376,14 @@ RETURNING
|
||||
`
|
||||
|
||||
type InsertConsentRecordParams struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
GrantedAt pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
GrantedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type InsertConsentRecordRow struct {
|
||||
@@ -380,6 +393,7 @@ type InsertConsentRecordRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -402,6 +416,7 @@ func (q *Queries) InsertConsentRecord(ctx context.Context, arg InsertConsentReco
|
||||
arg.TextVersion,
|
||||
arg.TextHash,
|
||||
arg.Source,
|
||||
arg.RegistrationVersion,
|
||||
arg.GrantedAt,
|
||||
)
|
||||
var i InsertConsentRecordRow
|
||||
@@ -412,6 +427,7 @@ func (q *Queries) InsertConsentRecord(ctx context.Context, arg InsertConsentReco
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -433,6 +449,7 @@ INSERT INTO consent_records (
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -446,6 +463,7 @@ INSERT INTO consent_records (
|
||||
$3,
|
||||
$4,
|
||||
'invitation_acceptance',
|
||||
NULL,
|
||||
$5,
|
||||
$6,
|
||||
$7::text [],
|
||||
@@ -462,6 +480,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -493,6 +512,7 @@ type InsertContactConsentRecordRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -528,6 +548,7 @@ func (q *Queries) InsertContactConsentRecord(ctx context.Context, arg InsertCont
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -550,6 +571,7 @@ WITH ledger AS (
|
||||
record.text_version,
|
||||
record.text_hash,
|
||||
record.source,
|
||||
record.registration_version,
|
||||
record.organization_id,
|
||||
record.organization_name,
|
||||
record.field_set,
|
||||
@@ -584,6 +606,7 @@ SELECT
|
||||
ledger.text_version,
|
||||
ledger.text_hash,
|
||||
ledger.source,
|
||||
ledger.registration_version,
|
||||
ledger.organization_id,
|
||||
ledger.organization_name,
|
||||
ledger.field_set,
|
||||
@@ -622,6 +645,7 @@ type ListConsentRecordsRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -662,6 +686,7 @@ func (q *Queries) ListConsentRecords(ctx context.Context, arg ListConsentRecords
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -690,6 +715,7 @@ SELECT
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -720,6 +746,7 @@ type ListCurrentContactConsentRecordsRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -747,6 +774,7 @@ func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg List
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -767,6 +795,83 @@ func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg List
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockRegistrationConsentRecord = `-- name: LockRegistrationConsentRecord :one
|
||||
SELECT
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'active'::text AS state
|
||||
FROM consent_records
|
||||
WHERE
|
||||
subject_id = $1
|
||||
AND purpose = 'c1'
|
||||
AND source = 'registration'
|
||||
AND registration_version = $2
|
||||
AND revoked_at IS NULL
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type LockRegistrationConsentRecordParams struct {
|
||||
SubjectID pgtype.UUID
|
||||
RegistrationVersion pgtype.Int8
|
||||
}
|
||||
|
||||
type LockRegistrationConsentRecordRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
InvitationID pgtype.UUID
|
||||
InvitationTermsVersion pgtype.Int8
|
||||
GrantedAt pgtype.Timestamptz
|
||||
RevokedAt pgtype.Timestamptz
|
||||
RevocationSource pgtype.Text
|
||||
State string
|
||||
}
|
||||
|
||||
// Locks the active registration C1 while its pending registration is applied.
|
||||
func (q *Queries) LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error) {
|
||||
row := q.db.QueryRow(ctx, lockRegistrationConsentRecord, arg.SubjectID, arg.RegistrationVersion)
|
||||
var i LockRegistrationConsentRecordRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const revokeConsentRecords = `-- name: RevokeConsentRecords :many
|
||||
UPDATE consent_records
|
||||
SET
|
||||
@@ -784,6 +889,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -809,6 +915,7 @@ type RevokeConsentRecordsRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -844,6 +951,7 @@ func (q *Queries) RevokeConsentRecords(ctx context.Context, arg RevokeConsentRec
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -881,6 +989,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -906,6 +1015,7 @@ type RevokeContactConsentRecordsRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -940,6 +1050,7 @@ func (q *Queries) RevokeContactConsentRecords(ctx context.Context, arg RevokeCon
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
|
||||
@@ -109,37 +109,146 @@ func (q *Queries) AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRe
|
||||
return i, err
|
||||
}
|
||||
|
||||
const consumeEmailToken = `-- name: ConsumeEmailToken :one
|
||||
UPDATE email_tokens AS token
|
||||
SET consumed_at = $1
|
||||
FROM users AS owner
|
||||
const confirmUserEmail = `-- name: ConfirmUserEmail :one
|
||||
UPDATE users
|
||||
SET
|
||||
password_hash = $1,
|
||||
scenario = $2,
|
||||
onboarding_step = $3,
|
||||
email_verified_at = $4,
|
||||
updated_at = $4,
|
||||
version = version + 1
|
||||
WHERE
|
||||
token.token_hash = $2
|
||||
AND token.purpose = $3
|
||||
AND token.consumed_at IS NULL
|
||||
AND token.invalidated_at IS NULL
|
||||
AND token.expires_at > $1
|
||||
AND owner.id = token.user_id
|
||||
AND owner.registration_version = token.registration_version
|
||||
id = $5
|
||||
AND registration_version = $6
|
||||
AND email_verified_at IS NULL
|
||||
RETURNING
|
||||
token.id,
|
||||
token.user_id,
|
||||
token.purpose,
|
||||
token.token_hash,
|
||||
token.registration_version,
|
||||
token.created_at,
|
||||
token.expires_at,
|
||||
token.consumed_at,
|
||||
token.invalidated_at,
|
||||
token.pending_password_hash,
|
||||
token.pending_scenario,
|
||||
token.pending_onboarding_step
|
||||
id,
|
||||
email,
|
||||
email_normalized,
|
||||
password_hash,
|
||||
scenario,
|
||||
onboarding_step,
|
||||
email_verified_at,
|
||||
registration_version,
|
||||
last_registered_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
`
|
||||
|
||||
type ConfirmUserEmailParams struct {
|
||||
PasswordHash string
|
||||
Scenario string
|
||||
OnboardingStep string
|
||||
VerifiedAt pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
RegistrationVersion int64
|
||||
}
|
||||
|
||||
// Applies the registration carried by its token and verifies the address in
|
||||
// one optimistic update. The caller holds the token lock and checks the
|
||||
// matching C1 in the same transaction.
|
||||
func (q *Queries) ConfirmUserEmail(ctx context.Context, arg ConfirmUserEmailParams) (User, error) {
|
||||
row := q.db.QueryRow(ctx, confirmUserEmail,
|
||||
arg.PasswordHash,
|
||||
arg.Scenario,
|
||||
arg.OnboardingStep,
|
||||
arg.VerifiedAt,
|
||||
arg.ID,
|
||||
arg.RegistrationVersion,
|
||||
)
|
||||
var i User
|
||||
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
|
||||
WITH candidate AS MATERIALIZED (
|
||||
SELECT
|
||||
token.id,
|
||||
token.user_id,
|
||||
token.purpose,
|
||||
token.token_hash,
|
||||
token.registration_version,
|
||||
token.created_at,
|
||||
token.expires_at,
|
||||
token.pending_password_hash,
|
||||
token.pending_scenario,
|
||||
token.pending_onboarding_step
|
||||
FROM email_tokens AS token
|
||||
INNER JOIN users AS owner ON owner.id = token.user_id
|
||||
WHERE
|
||||
token.token_hash = $1
|
||||
AND token.purpose = $2
|
||||
AND token.consumed_at IS NULL
|
||||
AND token.invalidated_at IS NULL
|
||||
AND token.expires_at > $3
|
||||
AND owner.registration_version = token.registration_version
|
||||
FOR UPDATE OF token
|
||||
),
|
||||
|
||||
consumed AS (
|
||||
UPDATE email_tokens AS token
|
||||
SET
|
||||
consumed_at = $3,
|
||||
pending_password_hash = NULL,
|
||||
pending_scenario = NULL,
|
||||
pending_onboarding_step = NULL
|
||||
FROM candidate
|
||||
WHERE token.id = candidate.id
|
||||
RETURNING token.id, token.consumed_at, token.invalidated_at
|
||||
)
|
||||
|
||||
SELECT
|
||||
candidate.id,
|
||||
candidate.user_id,
|
||||
candidate.purpose,
|
||||
candidate.token_hash,
|
||||
candidate.registration_version,
|
||||
candidate.created_at,
|
||||
candidate.expires_at,
|
||||
consumed.consumed_at,
|
||||
consumed.invalidated_at,
|
||||
candidate.pending_password_hash,
|
||||
candidate.pending_scenario,
|
||||
candidate.pending_onboarding_step
|
||||
FROM candidate
|
||||
INNER JOIN consumed ON consumed.id = candidate.id
|
||||
`
|
||||
|
||||
type ConsumeEmailTokenParams struct {
|
||||
ConsumedAt pgtype.Timestamptz
|
||||
TokenHash []byte
|
||||
Purpose string
|
||||
ConsumedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ConsumeEmailTokenRow 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
|
||||
PendingPasswordHash pgtype.Text
|
||||
PendingScenario pgtype.Text
|
||||
PendingOnboardingStep pgtype.Text
|
||||
}
|
||||
|
||||
// Consumes a token in one statement. Concurrent callers queue on the token
|
||||
@@ -151,9 +260,9 @@ type ConsumeEmailTokenParams struct {
|
||||
// The confirmation guarantee therefore needs MarkUserEmailVerified with the
|
||||
// returned registration version in the same transaction, rolled back when it
|
||||
// matches no row.
|
||||
func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error) {
|
||||
row := q.db.QueryRow(ctx, consumeEmailToken, arg.ConsumedAt, arg.TokenHash, arg.Purpose)
|
||||
var i EmailToken
|
||||
func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error) {
|
||||
row := q.db.QueryRow(ctx, consumeEmailToken, arg.TokenHash, arg.Purpose, arg.ConsumedAt)
|
||||
var i ConsumeEmailTokenRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.UserID,
|
||||
@@ -339,6 +448,52 @@ func (q *Queries) GetActiveSessionByTokenHash(ctx context.Context, arg GetActive
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getEmailTokenByHash = `-- name: GetEmailTokenByHash :one
|
||||
SELECT
|
||||
id,
|
||||
user_id,
|
||||
purpose,
|
||||
token_hash,
|
||||
registration_version,
|
||||
created_at,
|
||||
expires_at,
|
||||
consumed_at,
|
||||
invalidated_at,
|
||||
pending_password_hash,
|
||||
pending_scenario,
|
||||
pending_onboarding_step
|
||||
FROM email_tokens
|
||||
WHERE token_hash = $1
|
||||
AND purpose = $2
|
||||
`
|
||||
|
||||
type GetEmailTokenByHashParams struct {
|
||||
TokenHash []byte
|
||||
Purpose string
|
||||
}
|
||||
|
||||
// Reads a token before password verification; Consume rechecks it in the
|
||||
// confirmation transaction and clears pending credentials when it succeeds.
|
||||
func (q *Queries) GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error) {
|
||||
row := q.db.QueryRow(ctx, getEmailTokenByHash, arg.TokenHash, arg.Purpose)
|
||||
var i EmailToken
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.UserID,
|
||||
&i.Purpose,
|
||||
&i.TokenHash,
|
||||
&i.RegistrationVersion,
|
||||
&i.CreatedAt,
|
||||
&i.ExpiresAt,
|
||||
&i.ConsumedAt,
|
||||
&i.InvalidatedAt,
|
||||
&i.PendingPasswordHash,
|
||||
&i.PendingScenario,
|
||||
&i.PendingOnboardingStep,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getEmailTokenState = `-- name: GetEmailTokenState :one
|
||||
SELECT
|
||||
token.consumed_at,
|
||||
|
||||
@@ -126,6 +126,7 @@ type ConsentRecord struct {
|
||||
GrantedAt pgtype.Timestamptz
|
||||
RevokedAt pgtype.Timestamptz
|
||||
RevocationSource pgtype.Text
|
||||
RegistrationVersion pgtype.Int8
|
||||
}
|
||||
|
||||
type ConsentText struct {
|
||||
|
||||
@@ -78,6 +78,10 @@ type Querier interface {
|
||||
// the lease owner and the attempt, so a worker that lost its lease cannot
|
||||
// complete the job.
|
||||
CompleteScheduledJob(ctx context.Context, arg CompleteScheduledJobParams) (int64, error)
|
||||
// Applies the registration carried by its token and verifies the address in
|
||||
// one optimistic update. The caller holds the token lock and checks the
|
||||
// matching C1 in the same transaction.
|
||||
ConfirmUserEmail(ctx context.Context, arg ConfirmUserEmailParams) (User, error)
|
||||
// Consumes a token in one statement. Concurrent callers queue on the token
|
||||
// row lock; under READ COMMITTED each waiter re-checks the WHERE clause
|
||||
// against the committed row, so exactly one of them updates it. The join
|
||||
@@ -87,7 +91,7 @@ type Querier interface {
|
||||
// The confirmation guarantee therefore needs MarkUserEmailVerified with the
|
||||
// returned registration version in the same transaction, rolled back when it
|
||||
// matches no row.
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error)
|
||||
// Counts the hiding records of one candidate for the settings read.
|
||||
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
|
||||
// Counts the families of a category that have at least one published
|
||||
@@ -171,6 +175,9 @@ type Querier interface {
|
||||
// version published after it. The unique (policy_key, version) index serves
|
||||
// the backward scan.
|
||||
GetEffectivePolicyVersion(ctx context.Context, arg GetEffectivePolicyVersionParams) (PolicyVersion, error)
|
||||
// Reads a token before password verification; Consume rechecks it in the
|
||||
// confirmation transaction and clears pending credentials when it succeeds.
|
||||
GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error)
|
||||
// Explains why ConsumeEmailToken matched no row.
|
||||
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
|
||||
GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error)
|
||||
@@ -397,6 +404,8 @@ type Querier interface {
|
||||
// because aggregate writers check the expected version, so scanning without a
|
||||
// position watermark cannot overtake an earlier version.
|
||||
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
|
||||
// Locks the active registration C1 while its pending registration is applied.
|
||||
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
|
||||
// Notes that the first request of a claimed delivery is about to start, by the
|
||||
// database clock, and clears the count of worker failures: the claim and the
|
||||
// preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted
|
||||
|
||||
@@ -39,9 +39,8 @@ 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 counts identity requests the limiter refused, by
|
||||
// scope: address, client, or token. No address, email, or key is a label.
|
||||
identityRateLimited *client.CounterVec
|
||||
}
|
||||
|
||||
@@ -95,7 +94,7 @@ func newMailMetrics() mailMetrics {
|
||||
}, []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.",
|
||||
Help: "Identity requests refused with 429 by the limiter, by scope: address (per email address), client (per network address), or token (per verification token). 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",
|
||||
@@ -107,7 +106,7 @@ func newMailMetrics() mailMetrics {
|
||||
for _, reason := range domain.DeliveryCancelReasons() {
|
||||
metrics.senderCancelled.WithLabelValues(string(reason))
|
||||
}
|
||||
for _, scope := range []string{IdentityScopeAddress, IdentityScopeClient} {
|
||||
for _, scope := range []string{IdentityScopeAddress, IdentityScopeClient, IdentityScopeToken} {
|
||||
metrics.identityRateLimited.WithLabelValues(scope)
|
||||
}
|
||||
return metrics
|
||||
@@ -117,12 +116,13 @@ func newMailMetrics() mailMetrics {
|
||||
const (
|
||||
IdentityScopeAddress = "address"
|
||||
IdentityScopeClient = "client"
|
||||
IdentityScopeToken = "token"
|
||||
)
|
||||
|
||||
// ObserveIdentityRateLimited counts one refused identity request. A scope
|
||||
// outside the two known ones counts as address, so the label stays bounded.
|
||||
// outside the known scopes counts as address, so the label stays bounded.
|
||||
func (metrics *Metrics) ObserveIdentityRateLimited(scope string) {
|
||||
if scope != IdentityScopeClient {
|
||||
if scope != IdentityScopeClient && scope != IdentityScopeToken {
|
||||
scope = IdentityScopeAddress
|
||||
}
|
||||
metrics.mail.identityRateLimited.WithLabelValues(scope).Inc()
|
||||
|
||||
@@ -44,10 +44,12 @@ func TestIdentityRateLimitRefusalsAreCountedByBoundedScope(t *testing.T) {
|
||||
metrics := New()
|
||||
metrics.ObserveIdentityRateLimited(IdentityScopeClient)
|
||||
metrics.ObserveIdentityRateLimited(IdentityScopeAddress)
|
||||
metrics.ObserveIdentityRateLimited(IdentityScopeToken)
|
||||
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`)
|
||||
requireSeries(t, body, `lincodex_identity_rate_limit_refusals_total{scope="token"} 1`)
|
||||
if strings.Contains(body, "203.0.113.9") {
|
||||
t.Fatal("an unknown scope became a label value")
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user