feat(identity): confirm registration email atomically

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 09:12:15 +03:00
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}
}