feat(identity): confirm the email address with a six-digit code from the message

This commit is contained in:
shira committed 2026-10-10 00:52:46 +03:00
1 parent c94434cd09
commit d365a05c96
87 files changed
+4764 -224

No files matched your search

@@ -23,6 +23,7 @@ var regexMap = map[string]ogenregex.Regexp{
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"),
"^[0-9]{6}$": ogenregex.MustCompile("^[0-9]{6}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
@@ -1015,6 +1015,201 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h
}
}
// handleConfirmEmailByCodeRequest handles ConfirmEmailByCode operation.
//
// Public operation without a session. The verification message carries a six-digit code next to the
// link. The client sends the address, the code, and the password chosen for the registration that
// issued the code, so the user types only the code after registration. A reloaded page has no password
// in memory, so it asks for the address, the password, and the code together.
//
// The server finds the newest open verification token of the unverified account with this normalized
// address, whose registration is current and which carries a code. It compares the keyed digest of the
// code with the stored digest, checks the password against the token's pending password hash, and
// checks that the code has not expired. The code lives 30 minutes, or until the token ends if the
// token ends sooner. When all three checks pass, the server consumes the token, verifies the email,
// and applies the pending credentials in one transaction, exactly as the link confirmation does, and
// answers 200 with the same body. Success does not start a session.
//
// Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an
// unknown address, an address without an open code, a wrong code, an expired code, a wrong password,
// or a code that was burned. This keeps the answer from showing which addresses have a pending
// registration. Every failed attempt of an open code counts against that token. The fifth failed
// attempt burns the token: the code and the link stop working, and the user must request a new
// message. A refused attempt changes nothing else.
//
// The same refusal is returned after the rate limits are checked. The operation is limited per client
// address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email
// (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with
// Retry-After. A body that does not match the contract, such as a code that is not six digits, answers
// 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires
// an Origin equal to the configured public application origin and answers 403 `csrf_check_failed`
// otherwise.
//
// POST /api/v1/identity/email-verifications/code
func (s *Server) handleConfirmEmailByCodeRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ConfirmEmailByCode"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/identity/email-verifications/code"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ConfirmEmailByCodeOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: ConfirmEmailByCodeOperation,
ID: "ConfirmEmailByCode",
}
)
params, err := decodeConfirmEmailByCodeParams(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.decodeConfirmEmailByCodeRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response ConfirmEmailByCodeRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ConfirmEmailByCodeOperation,
OperationSummary: "Verify an email with the six-digit code from the verification message.",
OperationID: "ConfirmEmailByCode",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "Origin",
In: "header",
}: params.Origin,
},
Raw: r,
}
type (
Request = *EmailVerificationCodeRequest
Params = ConfirmEmailByCodeParams
Response = ConfirmEmailByCodeRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackConfirmEmailByCodeParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ConfirmEmailByCode(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.ConfirmEmailByCode(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeConfirmEmailByCodeResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleCreateMyAssessmentAttemptRequest handles CreateMyAssessmentAttempt operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -13,6 +13,10 @@ type CancelMyInvitationRes interface {
cancelMyInvitationRes()
}
type ConfirmEmailByCodeRes interface {
confirmEmailByCodeRes()
}
type ConfirmEmailRes interface {
confirmEmailRes()
}
@@ -15417,6 +15417,82 @@ func (s *ConfirmEmailBadRequest) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes ConfirmEmailByCodeBadRequest as json.
func (s *ConfirmEmailByCodeBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ConfirmEmailByCodeBadRequest from json.
func (s *ConfirmEmailByCodeBadRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConfirmEmailByCodeBadRequest to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = ConfirmEmailByCodeBadRequest(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ConfirmEmailByCodeBadRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConfirmEmailByCodeBadRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ConfirmEmailByCodeForbidden as json.
func (s *ConfirmEmailByCodeForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ConfirmEmailByCodeForbidden from json.
func (s *ConfirmEmailByCodeForbidden) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConfirmEmailByCodeForbidden to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = ConfirmEmailByCodeForbidden(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ConfirmEmailByCodeForbidden) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConfirmEmailByCodeForbidden) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ConfirmEmailForbidden as json.
func (s *ConfirmEmailForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
@@ -19271,6 +19347,132 @@ func (s *EmailAddress) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *EmailVerificationCodeRequest) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *EmailVerificationCodeRequest) encodeFields(e *jx.Encoder) {
{
e.FieldStart("email")
s.Email.Encode(e)
}
{
e.FieldStart("code")
s.Code.Encode(e)
}
{
e.FieldStart("password")
e.Str(s.Password)
}
}
var jsonFieldsNameOfEmailVerificationCodeRequest = [3]string{
0: "email",
1: "code",
2: "password",
}
// Decode decodes EmailVerificationCodeRequest from json.
func (s *EmailVerificationCodeRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode EmailVerificationCodeRequest to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "email":
requiredBitSet[0] |= 1 << 0
if err := func() error {
if err := s.Email.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"email\"")
}
case "code":
requiredBitSet[0] |= 1 << 1
if err := func() error {
if err := s.Code.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"code\"")
}
case "password":
requiredBitSet[0] |= 1 << 2
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)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode EmailVerificationCodeRequest")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfEmailVerificationCodeRequest) {
name = jsonFieldsNameOfEmailVerificationCodeRequest[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *EmailVerificationCodeRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *EmailVerificationCodeRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *EmailVerificationRequest) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -62758,6 +62960,46 @@ func (s *UpdateOrganizationUnauthorized) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes VerificationCode as json.
func (s VerificationCode) Encode(e *jx.Encoder) {
unwrapped := string(s)
e.Str(unwrapped)
}
// Decode decodes VerificationCode from json.
func (s *VerificationCode) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode VerificationCode to nil")
}
var unwrapped string
if err := func() error {
v, err := d.Str()
unwrapped = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = VerificationCode(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s VerificationCode) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *VerificationCode) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes VerificationToken as json.
func (s VerificationToken) Encode(e *jx.Encoder) {
unwrapped := string(s)
@@ -10,6 +10,7 @@ const (
AcknowledgeMyAssessmentSignalNoticeOperation OperationName = "AcknowledgeMyAssessmentSignalNotice"
CancelMyInvitationOperation OperationName = "CancelMyInvitation"
ConfirmEmailOperation OperationName = "ConfirmEmail"
ConfirmEmailByCodeOperation OperationName = "ConfirmEmailByCode"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationOperation OperationName = "CreateOrganization"
@@ -407,6 +407,98 @@ func decodeConfirmEmailParams(args [0]string, argsEscaped bool, r *http.Request)
return params, nil
}
// ConfirmEmailByCodeParams is parameters of ConfirmEmailByCode operation.
type ConfirmEmailByCodeParams 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 unpackConfirmEmailByCodeParams(packed middleware.Parameters) (params ConfirmEmailByCodeParams) {
{
key := middleware.ParameterKey{
Name: "Origin",
In: "header",
}
if v, ok := packed[key]; ok {
params.Origin = v.(OptString)
}
}
return params
}
func decodeConfirmEmailByCodeParams(args [0]string, argsEscaped bool, r *http.Request) (params ConfirmEmailByCodeParams, _ 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
@@ -330,6 +330,85 @@ func (s *Server) decodeConfirmEmailRequest(r *http.Request) (
}
}
func (s *Server) decodeConfirmEmailByCodeRequest(r *http.Request) (
req *EmailVerificationCodeRequest,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request EmailVerificationCodeRequest
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCreateMyAssessmentAttemptRequest(r *http.Request) (
req AssessmentAttemptCreate,
rawBody []byte,
@@ -474,6 +474,81 @@ func encodeConfirmEmailResponse(response ConfirmEmailRes, w http.ResponseWriter,
}
}
func encodeConfirmEmailByCodeResponse(response ConfirmEmailByCodeRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *EmailVerificationResult:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ConfirmEmailByCodeBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ConfirmEmailByCodeForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeCreateMyAssessmentAttemptResponse(response CreateMyAssessmentAttemptRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentAttemptHeaders:
@@ -11,46 +11,49 @@ import (
)
var (
rn83AllowedHeaders = map[string]string{
rn84AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn9AllowedHeaders = map[string]string{
"POST": "Content-Type,Origin",
}
rn79AllowedHeaders = map[string]string{
rn10AllowedHeaders = map[string]string{
"POST": "Content-Type,Origin",
}
rn80AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn69AllowedHeaders = map[string]string{
rn70AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn27AllowedHeaders = map[string]string{
rn28AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn81AllowedHeaders = map[string]string{
rn82AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn11AllowedHeaders = map[string]string{
rn12AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn95AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn23AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn94AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn22AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn93AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn78AllowedHeaders = map[string]string{
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn5AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn85AllowedHeaders = map[string]string{
rn86AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn53AllowedHeaders = map[string]string{
rn54AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
"PUT": "Content-Type,X-Csrf-Token",
}
@@ -60,65 +63,65 @@ var (
rn7AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn19AllowedHeaders = map[string]string{
rn20AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn95AllowedHeaders = map[string]string{
rn96AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn72AllowedHeaders = map[string]string{
rn73AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn56AllowedHeaders = map[string]string{
rn57AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
"PUT": "X-Csrf-Token",
}
rn90AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn91AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn38AllowedHeaders = map[string]string{
rn92AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn39AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn12AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
rn40AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn13AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn15AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
rn14AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn16AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn46AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn77AllowedHeaders = map[string]string{
rn17AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn88AllowedHeaders = map[string]string{
rn47AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn78AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn96AllowedHeaders = map[string]string{
rn89AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn86AllowedHeaders = map[string]string{
rn97AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn87AllowedHeaders = map[string]string{
"POST": "Content-Type,X-Csrf-Token",
}
rn18AllowedHeaders = map[string]string{
rn19AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn49AllowedHeaders = map[string]string{
rn50AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn75AllowedHeaders = map[string]string{
rn76AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
)
@@ -275,7 +278,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn83AllowedHeaders,
allowedHeaders: rn84AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -293,7 +296,6 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleConfirmEmailRequest([0]string{}, elemIsEscaped, w, r)
@@ -308,6 +310,33 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
switch elem[0] {
case '/': // Prefix: "/code"
if l := len("/code"); len(elem) >= l && elem[0:l] == "/code" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleConfirmEmailByCodeRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn10AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
}
}
@@ -352,7 +381,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn79AllowedHeaders,
allowedHeaders: rn80AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -376,7 +405,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn69AllowedHeaders,
allowedHeaders: rn70AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -403,7 +432,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,GET",
allowedHeaders: rn27AllowedHeaders,
allowedHeaders: rn28AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -456,7 +485,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn81AllowedHeaders,
allowedHeaders: rn82AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -504,7 +533,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn11AllowedHeaders,
allowedHeaders: rn12AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -578,7 +607,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn94AllowedHeaders,
allowedHeaders: rn95AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -605,7 +634,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn22AllowedHeaders,
allowedHeaders: rn23AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -671,7 +700,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn93AllowedHeaders,
allowedHeaders: rn94AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -698,7 +727,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn78AllowedHeaders,
allowedHeaders: rn79AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -909,7 +938,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE",
allowedHeaders: rn85AllowedHeaders,
allowedHeaders: rn86AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -943,7 +972,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,PUT",
allowedHeaders: rn53AllowedHeaders,
allowedHeaders: rn54AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1124,7 +1153,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn19AllowedHeaders,
allowedHeaders: rn20AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1151,7 +1180,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn95AllowedHeaders,
allowedHeaders: rn96AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1229,7 +1258,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn72AllowedHeaders,
allowedHeaders: rn73AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1407,7 +1436,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,PUT",
allowedHeaders: rn56AllowedHeaders,
allowedHeaders: rn57AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1498,7 +1527,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn90AllowedHeaders,
allowedHeaders: rn91AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1525,7 +1554,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn91AllowedHeaders,
allowedHeaders: rn92AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1556,7 +1585,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn38AllowedHeaders,
allowedHeaders: rn39AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1585,7 +1614,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn39AllowedHeaders,
allowedHeaders: rn40AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1611,7 +1640,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,POST",
allowedHeaders: rn12AllowedHeaders,
allowedHeaders: rn13AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1675,7 +1704,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn13AllowedHeaders,
allowedHeaders: rn14AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1714,7 +1743,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn15AllowedHeaders,
allowedHeaders: rn16AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -1822,7 +1851,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,POST",
allowedHeaders: rn16AllowedHeaders,
allowedHeaders: rn17AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1863,7 +1892,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn46AllowedHeaders,
allowedHeaders: rn47AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -1943,7 +1972,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn77AllowedHeaders,
allowedHeaders: rn78AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1971,7 +2000,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn88AllowedHeaders,
allowedHeaders: rn89AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2001,7 +2030,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn96AllowedHeaders,
allowedHeaders: rn97AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2034,7 +2063,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn86AllowedHeaders,
allowedHeaders: rn87AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2076,7 +2105,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,POST",
allowedHeaders: rn18AllowedHeaders,
allowedHeaders: rn19AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2118,7 +2147,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn49AllowedHeaders,
allowedHeaders: rn50AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -2195,7 +2224,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn75AllowedHeaders,
allowedHeaders: rn76AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -2458,7 +2487,6 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = ConfirmEmailOperation
@@ -2473,6 +2501,33 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
return
}
}
switch elem[0] {
case '/': // Prefix: "/code"
if l := len("/code"); len(elem) >= l && elem[0:l] == "/code" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = ConfirmEmailByCodeOperation
r.summary = "Verify an email with the six-digit code from the verification message."
r.operationID = "ConfirmEmailByCode"
r.operationGroup = ""
r.pathPattern = "/api/v1/identity/email-verifications/code"
r.args = args
r.count = 0
return r, true
default:
return
}
}
}
}
@@ -7857,6 +7857,14 @@ type ConfirmEmailBadRequest Problem
func (*ConfirmEmailBadRequest) confirmEmailRes() {}
type ConfirmEmailByCodeBadRequest Problem
func (*ConfirmEmailByCodeBadRequest) confirmEmailByCodeRes() {}
type ConfirmEmailByCodeForbidden Problem
func (*ConfirmEmailByCodeForbidden) confirmEmailByCodeRes() {}
type ConfirmEmailForbidden Problem
func (*ConfirmEmailForbidden) confirmEmailRes() {}
@@ -9612,6 +9620,48 @@ func (s *DirectionCode) UnmarshalText(data []byte) error {
type EmailAddress string
// Address, the six-digit code from its verification message, and the password chosen for the
// registration that issued the code. The password is checked the same way as in
// EmailVerificationRequest.
// Ref: #/components/schemas/EmailVerificationCodeRequest
type EmailVerificationCodeRequest struct {
Email EmailAddress `json:"email"`
Code VerificationCode `json:"code"`
// Password chosen for the registration that issued the code. The server applies NFKC normalization and
// the login length bounds, without reapplying the current new-registration blocklist.
Password string `json:"password"`
}
// GetEmail returns the value of Email.
func (s *EmailVerificationCodeRequest) GetEmail() EmailAddress {
return s.Email
}
// GetCode returns the value of Code.
func (s *EmailVerificationCodeRequest) GetCode() VerificationCode {
return s.Code
}
// GetPassword returns the value of Password.
func (s *EmailVerificationCodeRequest) GetPassword() string {
return s.Password
}
// SetEmail sets the value of Email.
func (s *EmailVerificationCodeRequest) SetEmail(val EmailAddress) {
s.Email = val
}
// SetCode sets the value of Code.
func (s *EmailVerificationCodeRequest) SetCode(val VerificationCode) {
s.Code = val
}
// SetPassword sets the value of Password.
func (s *EmailVerificationCodeRequest) SetPassword(val string) {
s.Password = val
}
// 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
@@ -9699,7 +9749,8 @@ func (s *EmailVerificationResult) SetOnboardingStep(val OnboardingStep) {
s.OnboardingStep = val
}
func (*EmailVerificationResult) confirmEmailRes() {}
func (*EmailVerificationResult) confirmEmailByCodeRes() {}
func (*EmailVerificationResult) confirmEmailRes() {}
// Always true in a successful response.
type EmailVerificationResultEmailVerified bool
@@ -31017,6 +31068,7 @@ func (s *TooManyRequestsHeaders) SetResponse(val Problem) {
func (*TooManyRequestsHeaders) acceptMyInvitationRes() {}
func (*TooManyRequestsHeaders) cancelMyInvitationRes() {}
func (*TooManyRequestsHeaders) confirmEmailByCodeRes() {}
func (*TooManyRequestsHeaders) confirmEmailRes() {}
func (*TooManyRequestsHeaders) createMyAssessmentAttemptRes() {}
func (*TooManyRequestsHeaders) createMySupportCaseRes() {}
@@ -31136,6 +31188,8 @@ type UpdateOrganizationUnauthorized Problem
func (*UpdateOrganizationUnauthorized) updateOrganizationRes() {}
type VerificationCode string
type VerificationToken string
type ViewMyInvitationBadRequest Problem
@@ -153,6 +153,38 @@ type Handler interface {
//
// POST /api/v1/identity/email-verifications
ConfirmEmail(ctx context.Context, req *EmailVerificationRequest, params ConfirmEmailParams) (ConfirmEmailRes, error)
// ConfirmEmailByCode implements ConfirmEmailByCode operation.
//
// Public operation without a session. The verification message carries a six-digit code next to the
// link. The client sends the address, the code, and the password chosen for the registration that
// issued the code, so the user types only the code after registration. A reloaded page has no password
// in memory, so it asks for the address, the password, and the code together.
//
// The server finds the newest open verification token of the unverified account with this normalized
// address, whose registration is current and which carries a code. It compares the keyed digest of the
// code with the stored digest, checks the password against the token's pending password hash, and
// checks that the code has not expired. The code lives 30 minutes, or until the token ends if the
// token ends sooner. When all three checks pass, the server consumes the token, verifies the email,
// and applies the pending credentials in one transaction, exactly as the link confirmation does, and
// answers 200 with the same body. Success does not start a session.
//
// Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an
// unknown address, an address without an open code, a wrong code, an expired code, a wrong password,
// or a code that was burned. This keeps the answer from showing which addresses have a pending
// registration. Every failed attempt of an open code counts against that token. The fifth failed
// attempt burns the token: the code and the link stop working, and the user must request a new
// message. A refused attempt changes nothing else.
//
// The same refusal is returned after the rate limits are checked. The operation is limited per client
// address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email
// (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with
// Retry-After. A body that does not match the contract, such as a code that is not six digits, answers
// 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires
// an Origin equal to the configured public application origin and answers 403 `csrf_check_failed`
// otherwise.
//
// POST /api/v1/identity/email-verifications/code
ConfirmEmailByCode(ctx context.Context, req *EmailVerificationCodeRequest, params ConfirmEmailByCodeParams) (ConfirmEmailByCodeRes, error)
// CreateMyAssessmentAttempt implements CreateMyAssessmentAttempt operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -170,6 +170,41 @@ func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerifica
return r, ht.ErrNotImplemented
}
// ConfirmEmailByCode implements ConfirmEmailByCode operation.
//
// Public operation without a session. The verification message carries a six-digit code next to the
// link. The client sends the address, the code, and the password chosen for the registration that
// issued the code, so the user types only the code after registration. A reloaded page has no password
// in memory, so it asks for the address, the password, and the code together.
//
// The server finds the newest open verification token of the unverified account with this normalized
// address, whose registration is current and which carries a code. It compares the keyed digest of the
// code with the stored digest, checks the password against the token's pending password hash, and
// checks that the code has not expired. The code lives 30 minutes, or until the token ends if the
// token ends sooner. When all three checks pass, the server consumes the token, verifies the email,
// and applies the pending credentials in one transaction, exactly as the link confirmation does, and
// answers 200 with the same body. Success does not start a session.
//
// Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an
// unknown address, an address without an open code, a wrong code, an expired code, a wrong password,
// or a code that was burned. This keeps the answer from showing which addresses have a pending
// registration. Every failed attempt of an open code counts against that token. The fifth failed
// attempt burns the token: the code and the link stop working, and the user must request a new
// message. A refused attempt changes nothing else.
//
// The same refusal is returned after the rate limits are checked. The operation is limited per client
// address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email
// (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with
// Retry-After. A body that does not match the contract, such as a code that is not six digits, answers
// 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires
// an Origin equal to the configured public application origin and answers 403 `csrf_check_failed`
// otherwise.
//
// POST /api/v1/identity/email-verifications/code
func (UnimplementedHandler) ConfirmEmailByCode(ctx context.Context, req *EmailVerificationCodeRequest, params ConfirmEmailByCodeParams) (r ConfirmEmailByCodeRes, _ error) {
return r, ht.ErrNotImplemented
}
// CreateMyAssessmentAttempt implements CreateMyAssessmentAttempt operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -7204,6 +7204,22 @@ func (s *ConfirmEmailBadRequest) Validate() error {
return nil
}
func (s *ConfirmEmailByCodeBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ConfirmEmailByCodeForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ConfirmEmailForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -8757,6 +8773,63 @@ func (s EmailAddress) Validate() error {
return nil
}
func (s *EmailVerificationCodeRequest) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Email.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "email",
Error: err,
})
}
if err := func() error {
if err := s.Code.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "code",
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}
}
return nil
}
func (s *EmailVerificationRequest) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -24718,6 +24791,26 @@ func (s *UpdateOrganizationUnauthorized) Validate() error {
return nil
}
func (s VerificationCode) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 6,
MinLengthSet: true,
MaxLength: 6,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[0-9]{6}$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
func (s VerificationToken) Validate() error {
alias := (string)(s)
if err := (validate.String{
@@ -0,0 +1,154 @@
package httpadapter
import (
"encoding/json"
"errors"
"net/http"
"strings"
"testing"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/identity"
)
const confirmationCodePath = "/api/v1/identity/email-verifications/code"
const confirmationCodeBody = `{"email":"candidate@example.com","code":"482915","password":"correct horse battery staple"}`
func TestConfirmEmailByCodeRequiresConfiguredOriginBeforeUsecase(t *testing.T) {
confirmation := &scriptedConfirmation{}
router := newConfirmationRouter(t, confirmation)
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) {
headers := map[string]string{}
if test.set {
headers["Origin"] = test.origin
}
response := serveIdentityRequest(t, router, identityRequest{
method: http.MethodPost, path: confirmationCodePath, body: confirmationCodeBody, headers: headers,
})
requireProblem(t, response, http.StatusForbidden, api.ProblemCodeCsrfCheckFailed)
if confirmation.codeCalls != 0 {
t.Fatal("code confirmation usecase ran before the origin check")
}
})
}
}
func TestConfirmEmailByCodePassesRequestAndReturnsSavedDestination(t *testing.T) {
confirmation := &scriptedConfirmation{codeResult: identity.ConfirmationResult{
Scenario: domain.ScenarioEmployer,
OnboardingStep: domain.OnboardingStepEmployerCompany,
}}
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
method: http.MethodPost,
path: confirmationCodePath,
body: confirmationCodeBody,
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"] != "employer" || result["onboarding_step"] != "employer_company" {
t.Fatalf("response body = %v", result)
}
command := confirmation.codeCommand
if confirmation.codeCalls != 1 || command.Email != "candidate@example.com" || command.Code != "482915" ||
command.Password != "correct horse battery staple" || command.ClientKey == "" {
t.Fatalf("code confirmation call = %d, command %+v", confirmation.codeCalls, command)
}
if confirmation.calls != 0 {
t.Fatal("code confirmation called the link usecase")
}
}
func TestConfirmEmailByCodeRejectsMalformedBodyBeforeUsecase(t *testing.T) {
for _, test := range []struct {
name string
body string
}{
{name: "five digits", body: `{"email":"candidate@example.com","code":"48291","password":"correct horse battery staple"}`},
{name: "seven digits", body: `{"email":"candidate@example.com","code":"4829150","password":"correct horse battery staple"}`},
{name: "letters", body: `{"email":"candidate@example.com","code":"48291A","password":"correct horse battery staple"}`},
{name: "separator", body: `{"email":"candidate@example.com","code":"482 915","password":"correct horse battery staple"}`},
{name: "missing password", body: `{"email":"candidate@example.com","code":"482915"}`},
{name: "token instead of code", body: `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`},
} {
t.Run(test.name, func(t *testing.T) {
confirmation := &scriptedConfirmation{}
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
method: http.MethodPost,
path: confirmationCodePath,
body: test.body,
headers: map[string]string{"Origin": "https://app.example"},
})
requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
if confirmation.codeCalls != 0 {
t.Fatal("code confirmation usecase ran for a malformed body")
}
})
}
}
func TestConfirmEmailByCodeMapsExpectedUsecaseFailures(t *testing.T) {
for _, test := range []struct {
name string
err error
statusCode int
code api.ProblemCode
retryAfter string
}{
{name: "invalid code", err: identity.ErrVerificationTokenInvalid, statusCode: http.StatusBadRequest, code: api.ProblemCodeVerificationTokenInvalid},
{name: "invalid field from usecase", err: &identity.InvalidFieldError{Pointer: "/code", Err: domain.ErrInvalidVerificationCode}, statusCode: http.StatusBadRequest, code: api.ProblemCodeValidationFailed},
{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{codeErr: test.err}
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
method: http.MethodPost,
path: confirmationCodePath,
body: confirmationCodeBody,
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.codeCalls != 1 {
t.Fatalf("code confirmation calls = %d, want 1", confirmation.codeCalls)
}
})
}
}
// An expired code never reaches the client as its own refusal: the usecase
// maps it to verification_token_invalid, and an unexpected storage error stays
// internal.
func TestConfirmEmailByCodeDoesNotConvertUnexpectedUsecaseErrors(t *testing.T) {
confirmation := &scriptedConfirmation{codeErr: errors.New("storage unavailable")}
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
method: http.MethodPost,
path: confirmationCodePath,
body: confirmationCodeBody,
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")
}
}
@@ -24,6 +24,11 @@ type scriptedConfirmation struct {
command identity.ConfirmCommand
result identity.ConfirmationResult
calls int
codeErr error
codeCommand identity.ConfirmCodeCommand
codeResult identity.ConfirmationResult
codeCalls int
}
func (confirmation *scriptedConfirmation) Confirm(_ context.Context, command identity.ConfirmCommand) (identity.ConfirmationResult, error) {
@@ -32,6 +37,12 @@ func (confirmation *scriptedConfirmation) Confirm(_ context.Context, command ide
return confirmation.result, confirmation.err
}
func (confirmation *scriptedConfirmation) ConfirmByCode(_ context.Context, command identity.ConfirmCodeCommand) (identity.ConfirmationResult, error) {
confirmation.codeCalls++
confirmation.codeCommand = command
return confirmation.codeResult, confirmation.codeErr
}
func newConfirmationRouter(t *testing.T, confirmation v1.EmailConfirmation) http.Handler {
t.Helper()
logger := slog.New(slog.DiscardHandler)
@@ -185,6 +185,15 @@ func TestIdentityOperationsBeforeImplementation(t *testing.T) {
statusCode: http.StatusNotImplemented,
code: api.ProblemCodeNotImplemented,
},
{
name: "public email confirmation by code",
request: identityRequest{
method: http.MethodPost, path: "/api/v1/identity/email-verifications/code",
body: `{"email":"candidate@example.com","code":"482915","password":"correct horse battery staple"}`,
},
statusCode: http.StatusNotImplemented,
code: api.ProblemCodeNotImplemented,
},
{
name: "public login",
request: identityRequest{
@@ -46,6 +46,17 @@ func (handler *Handler) ConfirmEmail(
return handler.identity.ConfirmEmail(ctx, request, params)
}
func (handler *Handler) ConfirmEmailByCode(
ctx context.Context,
request *api.EmailVerificationCodeRequest,
params api.ConfirmEmailByCodeParams,
) (api.ConfirmEmailByCodeRes, error) {
if handler.identity == nil || handler.identity.confirmation == nil {
return handler.UnimplementedHandler.ConfirmEmailByCode(ctx, request, params)
}
return handler.identity.ConfirmEmailByCode(ctx, request, params)
}
func (handler *Handler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) {
if handler.identity == nil || handler.identity.sessions == nil {
return handler.UnimplementedHandler.Login(ctx, request)
@@ -158,6 +169,46 @@ func (handler *IdentityHandler) ConfirmEmail(
return nil, err
}
// ConfirmEmailByCode verifies the address with the six-digit code. Its success
// body and its refusal shape match ConfirmEmail: every refusal is
// verification_token_invalid, so the answer never shows which addresses have a
// pending registration.
func (handler *IdentityHandler) ConfirmEmailByCode(
ctx context.Context,
request *api.EmailVerificationCodeRequest,
_ api.ConfirmEmailByCodeParams,
) (api.ConfirmEmailByCodeRes, error) {
if handler.confirmation == nil {
return nil, errors.New("IdentityHandler.ConfirmEmailByCode - confirmation is not configured")
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.ConfirmEmailByCodeForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
result, err := handler.confirmation.ConfirmByCode(ctx, identity.ConfirmCodeCommand{
Email: string(request.Email),
Code: string(request.Code),
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.ErrInvalidField):
return (*api.ConfirmEmailByCodeBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
case errors.Is(err, identity.ErrVerificationTokenInvalid):
return (*api.ConfirmEmailByCodeBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenInvalid).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func (handler *IdentityHandler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) {
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.LoginForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
@@ -16,6 +16,7 @@ type AccountRegistration interface {
// EmailConfirmation is what IdentityHandler needs from the confirmation usecase.
type EmailConfirmation interface {
Confirm(ctx context.Context, command identity.ConfirmCommand) (identity.ConfirmationResult, error)
ConfirmByCode(ctx context.Context, command identity.ConfirmCodeCommand) (identity.ConfirmationResult, error)
}
// IdentityHandlerOption configures an optional identity operation.
@@ -395,7 +395,7 @@ func (repository emailTokenRepository) FindByHash(
if owner.RegistrationVersion != row.RegistrationVersion {
return domain.EmailToken{}, fmt.Errorf("%s - token belongs to an earlier registration: %w", location, outbound.ErrEmailTokenInvalidated)
}
return emailTokenFromRow(row)
return emailTokenFromRow(emailTokenModelFromHashRow(row))
}
func (repository emailTokenRepository) Insert(ctx context.Context, token domain.EmailToken) error {
@@ -411,6 +411,10 @@ func (repository emailTokenRepository) Insert(ctx context.Context, token domain.
CreatedAt: pgTime(token.CreatedAt),
ExpiresAt: pgTime(token.ExpiresAt),
}
if code := token.Code; code != nil {
params.CodeHash = code.Hash[:]
params.CodeExpiresAt = pgTime(code.ExpiresAt)
}
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}
@@ -501,7 +505,7 @@ func (repository emailTokenRepository) Consume(
ConsumedAt: pgTime(at),
})
if err == nil {
return emailTokenFromRow(sqlc.EmailToken(row))
return emailTokenFromRow(consumedEmailTokenRow(row))
}
if !errors.Is(err, pgx.ErrNoRows) {
return domain.EmailToken{}, fmt.Errorf("emailTokenRepository.Consume - update email token: %w", mapIdentityError(err))
@@ -512,6 +516,84 @@ func (repository emailTokenRepository) Consume(
return domain.EmailToken{}, errors.New("emailTokenRepository.Consume - token became consumable after a failed attempt")
}
// emailTokenModelFromHashRow maps the row of GetEmailTokenByHash, which selects
// the token by its hash, to the table model.
func emailTokenModelFromHashRow(row sqlc.GetEmailTokenByHashRow) sqlc.EmailToken {
return sqlc.EmailToken{
ID: row.ID,
UserID: row.UserID,
Purpose: row.Purpose,
TokenHash: row.TokenHash,
RegistrationVersion: row.RegistrationVersion,
CreatedAt: row.CreatedAt,
ExpiresAt: row.ExpiresAt,
ConsumedAt: row.ConsumedAt,
InvalidatedAt: row.InvalidatedAt,
CodeHash: row.CodeHash,
CodeExpiresAt: row.CodeExpiresAt,
CodeFailedAttempts: row.CodeFailedAttempts,
PendingPasswordHash: row.PendingPasswordHash,
PendingScenario: row.PendingScenario,
PendingOnboardingStep: row.PendingOnboardingStep,
}
}
// emailTokenModelFromOpenCodeRow maps the row of GetOpenEmailCodeByAddress to
// the table model. The columns are the same as in GetEmailTokenByHash.
func emailTokenModelFromOpenCodeRow(row sqlc.GetOpenEmailCodeByAddressRow) sqlc.EmailToken {
return sqlc.EmailToken{
ID: row.ID,
UserID: row.UserID,
Purpose: row.Purpose,
TokenHash: row.TokenHash,
RegistrationVersion: row.RegistrationVersion,
CreatedAt: row.CreatedAt,
ExpiresAt: row.ExpiresAt,
ConsumedAt: row.ConsumedAt,
InvalidatedAt: row.InvalidatedAt,
CodeHash: row.CodeHash,
CodeExpiresAt: row.CodeExpiresAt,
CodeFailedAttempts: row.CodeFailedAttempts,
PendingPasswordHash: row.PendingPasswordHash,
PendingScenario: row.PendingScenario,
PendingOnboardingStep: row.PendingOnboardingStep,
}
}
// consumedEmailTokenRow maps the row of ConsumeEmailToken, which holds the token
// as it was before the update, to the table model. The update clears the code,
// so the returned row has none to map.
func consumedEmailTokenRow(row sqlc.ConsumeEmailTokenRow) sqlc.EmailToken {
return sqlc.EmailToken{
ID: row.ID,
UserID: row.UserID,
Purpose: row.Purpose,
TokenHash: row.TokenHash,
RegistrationVersion: row.RegistrationVersion,
CreatedAt: row.CreatedAt,
ExpiresAt: row.ExpiresAt,
ConsumedAt: row.ConsumedAt,
InvalidatedAt: row.InvalidatedAt,
PendingPasswordHash: row.PendingPasswordHash,
PendingScenario: row.PendingScenario,
PendingOnboardingStep: row.PendingOnboardingStep,
}
}
// emailCodeFromColumns decodes the code state of a token row. A NULL digest
// means the token carries no code.
func emailCodeFromColumns(digest []byte, expiresAt pgtype.Timestamptz) (*domain.EmailCode, error) {
if len(digest) == 0 {
return nil, nil
}
var hash domain.VerificationCodeHash
if len(digest) != len(hash) || !expiresAt.Valid {
return nil, errors.New("postgres.emailCodeFromColumns - stored code state is incomplete")
}
copy(hash[:], digest)
return &domain.EmailCode{Hash: hash, ExpiresAt: expiresAt.Time}, nil
}
// explainUnconsumable classifies a token that the atomic consume did not
// match. A nil result means the token is consumable again, which only a
// concurrent transaction that changed and then rolled back the row can cause.
@@ -540,6 +622,43 @@ func (repository emailTokenRepository) explainUnconsumable(
}
}
// FindOpenCodeByAddress reads the newest open token with a code of the
// unverified account at the address. The account is found by the normalized
// address; the code itself is compared by the usecase.
func (repository emailTokenRepository) FindOpenCodeByAddress(ctx context.Context, email domain.EmailAddress) (domain.EmailToken, error) {
const location = "emailTokenRepository.FindOpenCodeByAddress"
row, err := repository.queries.GetOpenEmailCodeByAddress(ctx, sqlc.GetOpenEmailCodeByAddressParams{
EmailNormalized: email.Normalized(),
Purpose: string(domain.EmailTokenPurposeEmailVerification),
})
if err != nil {
return domain.EmailToken{}, fmt.Errorf("%s - select open code: %w", location, mapNoRows(err, outbound.ErrEmailTokenNotFound))
}
return emailTokenFromRow(emailTokenModelFromOpenCodeRow(row))
}
// RecordFailedCodeAttempt counts a failed attempt in one statement. A token
// that is no longer open matches no row, which is not an error: the attempt
// then counts nothing, and the caller refuses the request either way.
func (repository emailTokenRepository) RecordFailedCodeAttempt(ctx context.Context, id uuid.UUID, at time.Time) (bool, error) {
const location = "emailTokenRepository.RecordFailedCodeAttempt"
if err := requireTime(location, at, domain.ErrInvalidEmailToken); err != nil {
return false, err
}
burned, err := repository.queries.RecordFailedEmailCodeAttempt(ctx, sqlc.RecordFailedEmailCodeAttemptParams{
MaxAttempts: domain.VerificationCodeMaxFailedAttempts,
AttemptedAt: pgTime(at),
ID: pgUUID(id),
})
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("%s - count failed attempt: %w", location, mapIdentityError(err))
}
return burned, nil
}
func emailTokenFromRow(row sqlc.EmailToken) (domain.EmailToken, error) {
purpose, err := domain.ParseEmailTokenPurpose(row.Purpose)
if err != nil {
@@ -553,8 +672,13 @@ func emailTokenFromRow(row sqlc.EmailToken) (domain.EmailToken, error) {
if err != nil {
return domain.EmailToken{}, err
}
code, err := emailCodeFromColumns(row.CodeHash, row.CodeExpiresAt)
if err != nil {
return domain.EmailToken{}, err
}
return domain.EmailToken{
Pending: pending,
Code: code,
ID: uuid.UUID(row.ID.Bytes),
UserID: uuid.UUID(row.UserID.Bytes),
Purpose: purpose,
@@ -207,7 +207,9 @@ consumed AS (
consumed_at = $3,
pending_password_hash = NULL,
pending_scenario = NULL,
pending_onboarding_step = NULL
pending_onboarding_step = NULL,
code_hash = NULL,
code_expires_at = NULL
FROM candidate
WHERE token.id = candidate.id
RETURNING token.id, token.consumed_at, token.invalidated_at
@@ -459,6 +461,9 @@ SELECT
expires_at,
consumed_at,
invalidated_at,
code_hash,
code_expires_at,
code_failed_attempts,
pending_password_hash,
pending_scenario,
pending_onboarding_step
@@ -472,11 +477,29 @@ type GetEmailTokenByHashParams struct {
Purpose string
}
type GetEmailTokenByHashRow 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
CodeHash []byte
CodeExpiresAt pgtype.Timestamptz
CodeFailedAttempts int16
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
// 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) {
func (q *Queries) GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (GetEmailTokenByHashRow, error) {
row := q.db.QueryRow(ctx, getEmailTokenByHash, arg.TokenHash, arg.Purpose)
var i EmailToken
var i GetEmailTokenByHashRow
err := row.Scan(
&i.ID,
&i.UserID,
@@ -487,6 +510,9 @@ func (q *Queries) GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHa
&i.ExpiresAt,
&i.ConsumedAt,
&i.InvalidatedAt,
&i.CodeHash,
&i.CodeExpiresAt,
&i.CodeFailedAttempts,
&i.PendingPasswordHash,
&i.PendingScenario,
&i.PendingOnboardingStep,
@@ -597,6 +623,88 @@ func (q *Queries) GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdemp
return i, err
}
const getOpenEmailCodeByAddress = `-- name: GetOpenEmailCodeByAddress :one
SELECT
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.code_hash,
token.code_expires_at,
token.code_failed_attempts,
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
owner.email_normalized = $1
AND owner.email_verified_at IS NULL
AND owner.registration_version = token.registration_version
AND token.purpose = $2
AND token.consumed_at IS NULL
AND token.invalidated_at IS NULL
AND token.code_hash IS NOT NULL
AND token.pending_password_hash IS NOT NULL
ORDER BY token.created_at DESC, token.id DESC
LIMIT 1
`
type GetOpenEmailCodeByAddressParams struct {
EmailNormalized string
Purpose string
}
type GetOpenEmailCodeByAddressRow 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
CodeHash []byte
CodeExpiresAt pgtype.Timestamptz
CodeFailedAttempts int16
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
// Reads the newest open verification token that carries a code for the
// unverified account with this normalized address. The registration version
// must be current, so a code of an earlier registration never matches. The
// row is read before the code is compared; the consumption rechecks it.
func (q *Queries) GetOpenEmailCodeByAddress(ctx context.Context, arg GetOpenEmailCodeByAddressParams) (GetOpenEmailCodeByAddressRow, error) {
row := q.db.QueryRow(ctx, getOpenEmailCodeByAddress, arg.EmailNormalized, arg.Purpose)
var i GetOpenEmailCodeByAddressRow
err := row.Scan(
&i.ID,
&i.UserID,
&i.Purpose,
&i.TokenHash,
&i.RegistrationVersion,
&i.CreatedAt,
&i.ExpiresAt,
&i.ConsumedAt,
&i.InvalidatedAt,
&i.CodeHash,
&i.CodeExpiresAt,
&i.CodeFailedAttempts,
&i.PendingPasswordHash,
&i.PendingScenario,
&i.PendingOnboardingStep,
)
return i, err
}
const getUserByEmailNormalized = `-- name: GetUserByEmailNormalized :one
SELECT
id,
@@ -682,6 +790,8 @@ INSERT INTO email_tokens (
registration_version,
created_at,
expires_at,
code_hash,
code_expires_at,
pending_password_hash,
pending_scenario,
pending_onboarding_step
@@ -695,7 +805,9 @@ INSERT INTO email_tokens (
$7,
$8,
$9,
$10
$10,
$11,
$12
)
`
@@ -707,6 +819,8 @@ type InsertEmailTokenParams struct {
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
CodeHash []byte
CodeExpiresAt pgtype.Timestamptz
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
@@ -721,6 +835,8 @@ func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenPara
arg.RegistrationVersion,
arg.CreatedAt,
arg.ExpiresAt,
arg.CodeHash,
arg.CodeExpiresAt,
arg.PendingPasswordHash,
arg.PendingScenario,
arg.PendingOnboardingStep,
@@ -834,10 +950,12 @@ const invalidateActiveEmailTokens = `-- name: InvalidateActiveEmailTokens :execr
UPDATE email_tokens
SET
invalidated_at = $1,
-- An invalidated token keeps no password hash: it can never be confirmed.
-- An invalidated token keeps no password hash or code: it can never be confirmed.
pending_password_hash = NULL,
pending_scenario = NULL,
pending_onboarding_step = NULL
pending_onboarding_step = NULL,
code_hash = NULL,
code_expires_at = NULL
WHERE
user_id = $2
AND purpose = $3
@@ -939,6 +1057,62 @@ func (q *Queries) PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeE
return result.RowsAffected(), nil
}
const recordFailedEmailCodeAttempt = `-- name: RecordFailedEmailCodeAttempt :one
UPDATE email_tokens
SET
code_failed_attempts = code_failed_attempts + 1,
invalidated_at = CASE
WHEN code_failed_attempts + 1 >= $1 THEN $2
ELSE invalidated_at
END,
code_hash = CASE
WHEN code_failed_attempts + 1 >= $1 THEN NULL
ELSE code_hash
END,
code_expires_at = CASE
WHEN code_failed_attempts + 1 >= $1 THEN NULL
ELSE code_expires_at
END,
pending_password_hash = CASE
WHEN code_failed_attempts + 1 >= $1 THEN NULL
ELSE pending_password_hash
END,
pending_scenario = CASE
WHEN code_failed_attempts + 1 >= $1 THEN NULL
ELSE pending_scenario
END,
pending_onboarding_step = CASE
WHEN code_failed_attempts + 1 >= $1 THEN NULL
ELSE pending_onboarding_step
END
WHERE
id = $3
AND consumed_at IS NULL
AND invalidated_at IS NULL
AND code_hash IS NOT NULL
AND code_failed_attempts < $1
RETURNING code_failed_attempts >= $1 AS burned
`
type RecordFailedEmailCodeAttemptParams struct {
MaxAttempts int16
AttemptedAt pgtype.Timestamptz
ID pgtype.UUID
}
// Counts one failed code or password attempt against an open code. The
// single UPDATE reads and writes the counter under the row lock, so concurrent
// failures serialize and none is lost. The attempt that reaches the limit
// invalidates the token and drops its code and pending credentials, so the
// code and the link both stop working. A token that is no longer open matches
// no row and is left unchanged.
func (q *Queries) RecordFailedEmailCodeAttempt(ctx context.Context, arg RecordFailedEmailCodeAttemptParams) (bool, error) {
row := q.db.QueryRow(ctx, recordFailedEmailCodeAttempt, arg.MaxAttempts, arg.AttemptedAt, arg.ID)
var burned bool
err := row.Scan(&burned)
return burned, err
}
const reserveIdempotencyRecord = `-- name: ReserveIdempotencyRecord :one
INSERT INTO idempotency_records (
scope_hash,
@@ -581,6 +581,12 @@ type EmailToken struct {
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
// HMAC-SHA-256 of the six-digit verification code under a server-side key; NULL when the token carries no code or the code has ended. The code itself is never stored.
CodeHash []byte
// End of the code validity: the earlier of the token expiry and the code lifetime. NULL together with code_hash.
CodeExpiresAt pgtype.Timestamptz
// Wrong code or password attempts counted against the open code; the token is invalidated when the count reaches the limit of five.
CodeFailedAttempts int16
}
type Holding struct {
@@ -345,7 +345,7 @@ type Querier interface {
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)
GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (GetEmailTokenByHashRow, error)
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
GetHoldingIDByFounder(ctx context.Context, founderAccountID pgtype.UUID) (pgtype.UUID, error)
@@ -390,6 +390,11 @@ type Querier interface {
// employer sees it only while they are an active member. No row means the
// content is no longer visible to this recipient.
GetNotificationOrganizationNameForRecipient(ctx context.Context, arg GetNotificationOrganizationNameForRecipientParams) (string, error)
// Reads the newest open verification token that carries a code for the
// unverified account with this normalized address. The registration version
// must be current, so a code of an earlier registration never matches. The
// row is read before the code is compared; the consumption rechecks it.
GetOpenEmailCodeByAddress(ctx context.Context, arg GetOpenEmailCodeByAddressParams) (GetOpenEmailCodeByAddressRow, error)
// Reads only the historical result. It intentionally does not join the live
// organization or membership, whose profile and state may have since changed.
GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error)
@@ -1043,6 +1048,13 @@ type Querier interface {
// the delivery is no longer pending or waiting, or another worker holds it.
// now is the application clock.
RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error)
// Counts one failed code or password attempt against an open code. The
// single UPDATE reads and writes the counter under the row lock, so concurrent
// failures serialize and none is lost. The attempt that reaches the limit
// invalidates the token and drops its code and pending credentials, so the
// code and the link both stop working. A token that is no longer open matches
// no row and is left unchanged.
RecordFailedEmailCodeAttempt(ctx context.Context, arg RecordFailedEmailCodeAttemptParams) (bool, error)
// The compare-and-swap of the first view: it applies only to a delivered
// invitation at the version the caller read and before its deadline, and it
// keeps the deadline.