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

+1 -1
View File
@@ -18,7 +18,7 @@ Registration, email confirmation, login, `GET /api/v1/identity/me`, `GET /api/v1
Sessions are stored in PostgreSQL. The browser receives a `__Host-lincodex_session` cookie with `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/`, and no `Domain`; the database stores only the token hash. The default idle timeout is 24 hours and the absolute lifetime is 168 hours. Configure them with `IDENTITY_SESSION_IDLE_TIMEOUT` and `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; the idle timeout cannot exceed the absolute lifetime.
Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`) requires exactly one `Origin` header matching `APP_PUBLIC_URL`. Unsafe session operations also require the session-bound HMAC token in `X-CSRF-Token`; all API instances must use the same `IDENTITY_KEY_SECRET`. Origin checks do not trust `Host` or forwarded headers. A wrong Origin or CSRF token returns `403` and leaves a valid session intact; successful logout revokes it on the server and clears the cookie. Login limits apply separately by client address and normalized email: `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to 30 attempts per hour and `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to 10 attempts per hour.
Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, and `Login`) requires exactly one `Origin` header matching `APP_PUBLIC_URL`. Unsafe session operations also require the session-bound HMAC token in `X-CSRF-Token`; all API instances must use the same `IDENTITY_KEY_SECRET`. Origin checks do not trust `Host` or forwarded headers. A wrong Origin or CSRF token returns `403` and leaves a valid session intact; successful logout revokes it on the server and clears the cookie. Login limits apply separately by client address and normalized email: `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to 30 attempts per hour and `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to 10 attempts per hour.
HTTP-flow tests with PostgreSQL and Redis are part of `make -C backend test-int`; compile the integration suite without starting containers with `make -C backend test-int-compile`.
+1 -1
View File
@@ -18,7 +18,7 @@
Сессия хранится в PostgreSQL. Браузер получает cookie `__Host-lincodex_session` с атрибутами `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/` и без `Domain`; в базе хранится только хеш токена. Время бездействия по умолчанию - 24 часа, абсолютный срок - 168 часов. Эти значения задаются через `IDENTITY_SESSION_IDLE_TIMEOUT` и `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; время бездействия не может превышать абсолютный срок.
Каждая небезопасная публичная identity-операция (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`) требует ровно один заголовок `Origin`, в точности совпадающий с `APP_PUBLIC_URL`. Небезопасные операции сессии также требуют `X-CSRF-Token`, HMAC-токен, связанный с текущей сессией; все API-инстансы должны использовать один `IDENTITY_KEY_SECRET`. Проверка Origin не доверяет `Host` или forwarded-заголовкам. Неверный Origin или CSRF отвечает `403` и сохраняет действующую сессию; успешный выход отзывает ее на сервере и очищает cookie. Лимит входа действует отдельно по адресу клиента и нормализованному email: `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию 30 попыток в час и `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` - 10 попыток в час.
Каждая небезопасная публичная identity-операция (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`) требует ровно один заголовок `Origin`, в точности совпадающий с `APP_PUBLIC_URL`. Небезопасные операции сессии также требуют `X-CSRF-Token`, HMAC-токен, связанный с текущей сессией; все API-инстансы должны использовать один `IDENTITY_KEY_SECRET`. Проверка Origin не доверяет `Host` или forwarded-заголовкам. Неверный Origin или CSRF отвечает `403` и сохраняет действующую сессию; успешный выход отзывает ее на сервере и очищает cookie. Лимит входа действует отдельно по адресу клиента и нормализованному email: `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию 30 попыток в час и `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` - 10 попыток в час.
Проверки HTTP-сценариев с PostgreSQL и Redis входят в `make -C backend test-int`; компиляция integration suite без запуска контейнеров выполняется через `make -C backend test-int-compile`.
@@ -0,0 +1,70 @@
-- +goose Up
-- Email verification codes: a six-digit code that travels with each
-- verification message next to the link. The table keeps only a keyed digest
-- of the code, its expiry, and the count of failed attempts. The count is
-- advanced by a single conditional UPDATE, so concurrent wrong attempts cannot
-- exceed the limit and none is lost. Tokens issued before this migration carry
-- no code and keep working by link only.
--
-- The three columns are set together for a token that carries a code. The
-- application sets the code expiry to the earlier of the token expiry and the
-- code lifetime, and checks both at every use.
ALTER TABLE email_tokens
ADD COLUMN code_hash bytea,
ADD COLUMN code_expires_at timestamptz,
ADD COLUMN code_failed_attempts smallint NOT NULL DEFAULT 0,
ADD CONSTRAINT email_tokens_code_pair CHECK (
(code_hash IS NULL) = (code_expires_at IS NULL)
),
ADD CONSTRAINT email_tokens_code_hash_length CHECK (
code_hash IS NULL OR octet_length(code_hash) = 32
),
ADD CONSTRAINT email_tokens_code_expiry CHECK (
code_expires_at IS NULL OR code_expires_at > created_at
),
ADD CONSTRAINT email_tokens_code_purpose CHECK (
code_hash IS NULL OR purpose = 'email_verification'
),
ADD CONSTRAINT email_tokens_code_attempts_range CHECK (
code_failed_attempts BETWEEN 0 AND 5
);
COMMENT ON COLUMN email_tokens.code_hash IS
'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.';
COMMENT ON COLUMN email_tokens.code_expires_at IS
'End of the code validity: the earlier of the token expiry and the code lifetime. NULL together with code_hash.';
COMMENT ON COLUMN email_tokens.code_failed_attempts IS
'Wrong code or password attempts counted against the open code; the token is invalidated when the count reaches the limit of five.';
-- +goose Down
-- A rollback removes the codes, so it refuses while a code is still usable.
-- A code expires within its 30-minute lifetime, so waiting for expiry is enough.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM email_tokens
WHERE code_hash IS NOT NULL
AND consumed_at IS NULL
AND invalidated_at IS NULL
AND code_expires_at > now()
) THEN
RAISE EXCEPTION USING
ERRCODE = 'object_not_in_prerequisite_state',
MESSAGE = 'email verification codes are still usable',
HINT = 'Wait until the open codes expire, then roll back again.';
END IF;
END
$$;
-- +goose StatementEnd
ALTER TABLE email_tokens
DROP CONSTRAINT email_tokens_code_attempts_range,
DROP CONSTRAINT email_tokens_code_purpose,
DROP CONSTRAINT email_tokens_code_expiry,
DROP CONSTRAINT email_tokens_code_hash_length,
DROP CONSTRAINT email_tokens_code_pair,
DROP COLUMN code_failed_attempts,
DROP COLUMN code_expires_at,
DROP COLUMN code_hash;
+91 -3
View File
@@ -304,6 +304,8 @@ INSERT INTO email_tokens (
registration_version,
created_at,
expires_at,
code_hash,
code_expires_at,
pending_password_hash,
pending_scenario,
pending_onboarding_step
@@ -315,6 +317,8 @@ INSERT INTO email_tokens (
sqlc.arg(registration_version),
sqlc.arg(created_at),
sqlc.arg(expires_at),
sqlc.narg(code_hash),
sqlc.narg(code_expires_at),
sqlc.narg(pending_password_hash),
sqlc.narg(pending_scenario),
sqlc.narg(pending_onboarding_step)
@@ -349,6 +353,9 @@ SELECT
expires_at,
consumed_at,
invalidated_at,
code_hash,
code_expires_at,
code_failed_attempts,
pending_password_hash,
pending_scenario,
pending_onboarding_step
@@ -356,6 +363,83 @@ FROM email_tokens
WHERE token_hash = sqlc.arg(token_hash)
AND purpose = sqlc.arg(purpose);
-- 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.
-- 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 = sqlc.arg(email_normalized)
AND owner.email_verified_at IS NULL
AND owner.registration_version = token.registration_version
AND token.purpose = sqlc.arg(purpose)
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;
-- 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.
-- name: RecordFailedEmailCodeAttempt :one
UPDATE email_tokens
SET
code_failed_attempts = code_failed_attempts + 1,
invalidated_at = CASE
WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN sqlc.arg(attempted_at)
ELSE invalidated_at
END,
code_hash = CASE
WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL
ELSE code_hash
END,
code_expires_at = CASE
WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL
ELSE code_expires_at
END,
pending_password_hash = CASE
WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL
ELSE pending_password_hash
END,
pending_scenario = CASE
WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL
ELSE pending_scenario
END,
pending_onboarding_step = CASE
WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL
ELSE pending_onboarding_step
END
WHERE
id = sqlc.arg(id)
AND consumed_at IS NULL
AND invalidated_at IS NULL
AND code_hash IS NOT NULL
AND code_failed_attempts < sqlc.arg(max_attempts)
RETURNING code_failed_attempts >= sqlc.arg(max_attempts) AS burned;
-- Starts a new registration of an unverified account without touching its
-- credentials, scenario, or onboarding step: the new registration carries
-- them on its verification token. Advances the registration version, which
@@ -416,10 +500,12 @@ FROM updated;
UPDATE email_tokens
SET
invalidated_at = sqlc.arg(invalidated_at),
-- 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 = sqlc.arg(user_id)
AND purpose = sqlc.arg(purpose)
@@ -466,7 +552,9 @@ consumed AS (
consumed_at = sqlc.arg(consumed_at),
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
+363
View File
@@ -0,0 +1,363 @@
//go:build integration
package integration_test
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"net/http"
"regexp"
"sync"
"testing"
"time"
)
const (
emailVerificationCodePath = "/api/v1/identity/email-verifications/code"
codeTestTimeout = 5 * time.Minute
// codeWaitAfterMessage waits out the verification message interval of the
// test stand. Its counters use the real clock, as the Redis limiter does.
codeWaitAfterMessage = registrationMinInterval + 100*time.Millisecond
)
// verificationCodeText finds the code in the text part of the message.
var verificationCodeText = regexp.MustCompile(`Код подтверждения: ([0-9]{6})\b`)
// codeTokenState is the stored state of one verification token that the code
// path reads and writes.
type codeTokenState struct {
codeStored bool
codeFailedAttempts int
consumed bool
invalidated bool
pendingStored bool
codeLifetimeMinute int64
}
func messageCode(t *testing.T, text string) string {
t.Helper()
match := verificationCodeText.FindStringSubmatch(text)
if match == nil {
t.Fatal("the verification message has no six-digit code")
}
return match[1]
}
func messageToken(t *testing.T, text string) string {
t.Helper()
match := verificationLinkToken.FindStringSubmatch(text)
if match == nil {
t.Fatal("the verification message has no token in its link")
}
return match[1]
}
// registerAndSendCode registers the address and returns the token of its link
// and the code of its message.
func (harness *registrationHarness) registerAndSendCode(ctx context.Context, t *testing.T, email, scenario, password string) (string, string) {
t.Helper()
text := harness.registerAndReceiveVerification(ctx, t, email, scenario, password)
return messageToken(t, text), messageCode(t, text)
}
func (harness *registrationHarness) confirmByCode(t *testing.T, email, code, password string) registrationResponse {
t.Helper()
body, err := json.Marshal(struct {
Email string `json:"email"`
Code string `json:"code"`
Password string `json:"password"`
}{Email: email, Code: code, Password: password})
if err != nil {
t.Fatalf("encode code confirmation request: %v", err)
}
return harness.post(t, emailVerificationCodePath, string(body), nil)
}
func readCodeTokenState(ctx context.Context, t *testing.T, harness *registrationHarness, rawToken string) codeTokenState {
t.Helper()
hash := sha256.Sum256([]byte(rawToken))
var state codeTokenState
err := harness.pool.QueryRow(ctx, `
SELECT
code_hash IS NOT NULL,
code_failed_attempts,
consumed_at IS NOT NULL,
invalidated_at IS NOT NULL,
pending_password_hash IS NOT NULL,
coalesce(extract(epoch FROM (code_expires_at - created_at)) / 60, 0)::bigint
FROM email_tokens
WHERE token_hash = $1`, hash[:]).Scan(
&state.codeStored, &state.codeFailedAttempts, &state.consumed, &state.invalidated,
&state.pendingStored, &state.codeLifetimeMinute,
)
if err != nil {
t.Fatalf("read code token state: %v", err)
}
return state
}
// requireCodeRefusal checks the one refusal of the code operation: the same
// status, content type, and problem code whatever the cause, and no session or
// rate-limit header.
func requireCodeRefusal(t *testing.T, response registrationResponse) {
t.Helper()
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.setCookie != "" || response.retryAfter != "" {
t.Fatalf("refusal set a cookie %q or Retry-After %q", response.setCookie, response.retryAfter)
}
}
// problemShape returns the body of a refusal without its per-request trace_id,
// so refusals of different causes can be compared.
func problemShape(t *testing.T, response registrationResponse) string {
t.Helper()
var problem map[string]any
if err := json.Unmarshal([]byte(response.body), &problem); err != nil {
t.Fatalf("decode refusal %q: %v", response.body, err)
}
delete(problem, "trace_id")
shape, err := json.Marshal(problem)
if err != nil {
t.Fatalf("encode refusal shape: %v", err)
}
return fmt.Sprintf("%d %s %s", response.status, response.contentType, shape)
}
func TestEmailVerificationCodeOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), codeTestTimeout)
defer cancel()
harness := newRegistrationHarness(ctx, t, env, 1000)
publicOrigin := env.Config.AppPublicURL
reset := func(t *testing.T) {
t.Helper()
harness.truncate(ctx, t)
harness.clock.Set(harness.start)
}
t.Run("the code from the message confirms the registration like the link", func(t *testing.T) {
reset(t)
const email = "code.confirm@example.com"
token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
if before.pendingPasswordHash == nil {
t.Fatal("registration did not store the pending password on the token")
}
state := readCodeTokenState(ctx, t, harness, token)
if !state.codeStored || state.codeLifetimeMinute != 30 || !state.pendingStored {
t.Fatalf("token code state = %+v, want a stored code of 30 minutes", state)
}
response := harness.confirmByCode(t, email, code, registrationPassword)
requireConfirmationSuccess(t, response, "candidate", "candidate_consents")
after := readConfirmationState(ctx, t, harness, email, token)
assertConfirmationApplied(t, before, after, "candidate", "candidate_consents")
assertSingleConfirmationEvent(ctx, t, harness, email)
if after.sessionCount != 0 {
t.Fatalf("code confirmation created %d sessions, want none", after.sessionCount)
}
afterState := readCodeTokenState(ctx, t, harness, token)
if afterState.codeStored || !afterState.consumed || afterState.pendingStored {
t.Fatalf("consumed token keeps code or pending state: %+v", afterState)
}
harness.assertLogsHoldNoSecrets(t, code, registrationPassword, token)
replay := harness.confirmByCode(t, email, code, registrationPassword)
requireCodeRefusal(t, replay)
if !sameConfirmationState(after, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("replaying a consumed code changed the account")
}
})
t.Run("five wrong codes burn the token, and then even the right code and the link fail", func(t *testing.T) {
reset(t)
const email = "code.burn@example.com"
token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword)
wrong := wrongDigits(code)
for attempt := 1; attempt <= 5; attempt++ {
requireCodeRefusal(t, harness.confirmByCode(t, email, wrong, registrationPassword))
state := readCodeTokenState(ctx, t, harness, token)
if state.codeFailedAttempts != attempt || state.invalidated != (attempt == 5) {
t.Fatalf("after wrong attempt %d the state is %+v", attempt, state)
}
}
requireCodeRefusal(t, harness.confirmByCode(t, email, code, registrationPassword))
requireProblemStatus(t, harness.confirm(t, token, registrationPassword, &publicOrigin), http.StatusBadRequest, "verification_token_invalid")
state := readCodeTokenState(ctx, t, harness, token)
if state.consumed || state.codeStored || state.pendingStored {
t.Fatalf("a burned token keeps state: %+v", state)
}
if verified := harness.count(ctx, t, `SELECT count(*) FROM users WHERE email_normalized = $1 AND email_verified_at IS NOT NULL`, email); verified != 0 {
t.Fatal("a burned code verified the address")
}
harness.assertLogsHoldNoSecrets(t, code, wrong, registrationPassword, token)
})
t.Run("concurrent wrong codes count at most five attempts", func(t *testing.T) {
reset(t)
const email = "code.concurrent@example.com"
token, code := harness.registerAndSendCode(ctx, t, email, "employer", registrationPassword)
wrong := wrongDigits(code)
const parallel = 8
responses := make([]registrationResponse, parallel)
var group sync.WaitGroup
for index := range parallel {
group.Add(1)
go func() {
defer group.Done()
responses[index] = harness.confirmByCode(t, email, wrong, registrationPassword)
}()
}
group.Wait()
for _, response := range responses {
requireCodeRefusal(t, response)
}
state := readCodeTokenState(ctx, t, harness, token)
if state.codeFailedAttempts != 5 || !state.invalidated {
t.Fatalf("concurrent wrong attempts left %+v, want exactly five counted and the token burned", state)
}
})
t.Run("a wrong password with the right code is refused and counted", func(t *testing.T) {
reset(t)
const email = "code.password@example.com"
token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword)
requireCodeRefusal(t, harness.confirmByCode(t, email, code, "this is the wrong password"))
state := readCodeTokenState(ctx, t, harness, token)
if state.codeFailedAttempts != 1 || state.consumed || state.invalidated {
t.Fatalf("after a wrong password the state is %+v", state)
}
requireConfirmationSuccess(t, harness.confirmByCode(t, email, code, registrationPassword), "candidate", "candidate_consents")
})
t.Run("an expired code is refused, while the link stays valid until the token expires", func(t *testing.T) {
reset(t)
const email = "code.expired@example.com"
token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword)
harness.clock.Set(harness.clock.Now().Add(31 * time.Minute))
requireCodeRefusal(t, harness.confirmByCode(t, email, code, registrationPassword))
state := readCodeTokenState(ctx, t, harness, token)
if state.codeFailedAttempts != 1 || state.consumed {
t.Fatalf("expired code state = %+v, want one counted attempt and an open token", state)
}
requireConfirmationSuccess(t, harness.confirm(t, token, registrationPassword, &publicOrigin), "candidate", "candidate_consents")
})
t.Run("the link consumes the code and the code consumes the link", func(t *testing.T) {
reset(t)
const linkFirst = "code.link-first@example.com"
token, code := harness.registerAndSendCode(ctx, t, linkFirst, "candidate", registrationPassword)
requireConfirmationSuccess(t, harness.confirm(t, token, registrationPassword, &publicOrigin), "candidate", "candidate_consents")
requireCodeRefusal(t, harness.confirmByCode(t, linkFirst, code, registrationPassword))
const codeFirst = "code.code-first@example.com"
token, code = harness.registerAndSendCode(ctx, t, codeFirst, "candidate", registrationPassword)
requireConfirmationSuccess(t, harness.confirmByCode(t, codeFirst, code, registrationPassword), "candidate", "candidate_consents")
requireProblemStatus(t, harness.confirm(t, token, registrationPassword, &publicOrigin), http.StatusBadRequest, "verification_token_invalid")
})
t.Run("a resend replaces the code and the earlier code stops working", func(t *testing.T) {
reset(t)
const email = "code.resend@example.com"
_, first := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword)
time.Sleep(codeWaitAfterMessage)
requestCount := len(harness.fixture.Requests())
response := harness.resend(t, email)
requireAccepted(t, response)
second := messageCode(t, harness.receiveVerificationText(ctx, t, email, requestCount))
if first == second {
t.Skip("the two random codes were equal; the replacement cannot be told apart")
}
requireCodeRefusal(t, harness.confirmByCode(t, email, first, registrationPassword))
requireConfirmationSuccess(t, harness.confirmByCode(t, email, second, registrationPassword), "candidate", "candidate_consents")
})
t.Run("a registration replaced by a stranger's address cannot be confirmed with its code", func(t *testing.T) {
reset(t)
const email = "code.hijack@example.com"
const attackerPassword = "attacker registered this address first"
attackerToken, attackerCode := harness.registerAndSendCode(ctx, t, email, "candidate", attackerPassword)
time.Sleep(codeWaitAfterMessage)
harness.clock.Set(harness.clock.Now().Add(time.Minute))
requestCount := len(harness.fixture.Requests())
requireAccepted(t, harness.register(t, email, "candidate", ""))
ownerText := harness.receiveVerificationText(ctx, t, email, requestCount)
ownerCode := messageCode(t, ownerText)
ownerToken := messageToken(t, ownerText)
if state := readCodeTokenState(ctx, t, harness, attackerToken); !state.invalidated {
t.Fatal("the owner's registration did not replace the earlier token")
}
requireCodeRefusal(t, harness.confirmByCode(t, email, attackerCode, attackerPassword))
requireCodeRefusal(t, harness.confirmByCode(t, email, ownerCode, attackerPassword))
requireConfirmationSuccess(t, harness.confirmByCode(t, email, ownerCode, registrationPassword), "candidate", "candidate_consents")
if ownerState := readCodeTokenState(ctx, t, harness, ownerToken); !ownerState.consumed {
t.Fatal("the owner's code did not consume the owner's token")
}
})
t.Run("an unknown address and a wrong code give the same refusal", func(t *testing.T) {
reset(t)
const email = "code.enumeration@example.com"
_, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword)
unknown := harness.confirmByCode(t, "nobody.registered@example.com", code, registrationPassword)
wrong := harness.confirmByCode(t, email, wrongDigits(code), registrationPassword)
expired := harness.confirmByCode(t, "nobody.either@example.com", wrongDigits(code), "a password nobody set")
if problemShape(t, unknown) != problemShape(t, wrong) || problemShape(t, wrong) != problemShape(t, expired) {
t.Fatalf("refusals differ:\nunknown %s\nwrong %s\nother %s", problemShape(t, unknown), problemShape(t, wrong), problemShape(t, expired))
}
})
t.Run("a malformed code is a validation failure before any lookup", func(t *testing.T) {
reset(t)
for _, body := range []string{
`{"email":"candidate@example.com","code":"12345","password":"` + registrationPassword + `"}`,
`{"email":"candidate@example.com","code":"1234567","password":"` + registrationPassword + `"}`,
} {
response := harness.post(t, emailVerificationCodePath, body, nil)
requireProblemStatus(t, response, http.StatusBadRequest, "validation_failed")
}
})
t.Run("the address limit refuses after ten code requests", func(t *testing.T) {
reset(t)
const email = "code.limit@example.com"
_, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword)
wrong := wrongDigits(code)
for range registrationEmailHourlyLimit {
response := harness.confirmByCode(t, email, wrong, registrationPassword)
if response.status != http.StatusBadRequest {
t.Fatalf("request within the limit = %d %s", response.status, response.body)
}
}
limited := harness.confirmByCode(t, email, code, registrationPassword)
requireProblemStatus(t, limited, http.StatusTooManyRequests, "rate_limited")
if limited.retryAfter == "" {
t.Fatal("the refused code request has no Retry-After")
}
})
t.Run("an origin that is not the public one is refused before the usecase", func(t *testing.T) {
reset(t)
const email = "code.origin@example.com"
token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword)
body, err := json.Marshal(map[string]string{"email": email, "code": code, "password": registrationPassword})
if err != nil {
t.Fatal(err)
}
response := harness.postWithOriginDefault(t, emailVerificationCodePath, string(body), map[string]string{"Origin": "https://foreign.example"}, false)
requireProblemStatus(t, response, http.StatusForbidden, "csrf_check_failed")
if state := readCodeTokenState(ctx, t, harness, token); state.codeFailedAttempts != 0 {
t.Fatal("a refused origin counted an attempt")
}
})
}
// wrongDigits returns a six-digit code that differs from code.
func wrongDigits(code string) string {
if code == "000000" {
return "000001"
}
return "000000"
}
@@ -1841,6 +1841,10 @@ func (harness *senderHarness) enqueueToken(
if err != nil {
t.Fatalf("NewEmailToken() error = %v", err)
}
code, err := domain.NewVerificationCode()
if err != nil {
t.Fatalf("NewVerificationCode() error = %v", err)
}
var deliveryID uuid.UUID
err = harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.EmailTokens().Insert(ctx, token); err != nil {
@@ -1848,6 +1852,7 @@ func (harness *senderHarness) enqueueToken(
}
deliveryID, err = enqueue(ctx, unit, notification.TokenMailRequest{
Recipient: user.Email, Token: token, RawToken: raw, Lifetime: domain.Hours(lifetime / time.Hour),
Code: code, CodeLifetime: domain.VerificationCodeLifetime,
})
return err
})
@@ -33,6 +33,11 @@ func TestNotificationSubjectMigrations(t *testing.T) {
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
// Migration 00046 (verification codes) is newer than the subject migration
// under test. Roll it back first, so the rollback checks below act on 00045.
if result, err := migrator.DownOne(ctx); err != nil || result.Version != 46 {
t.Fatalf("roll back the newest migration: result %+v, error = %v; want migration 46", result, err)
}
now := time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC)
userID, deliveryID, invitationID, organizationID := uuid.New(), uuid.New(), uuid.New(), uuid.New()
+30 -8
View File
@@ -50,8 +50,11 @@ const (
// The production default is a minute.
registrationMinInterval = 3 * time.Second
registrationDailyLimit = 3
registrationSecret = "integration-test-identity-key-secret-0123456789"
registrationApplication = "registration_http"
// registrationEmailHourlyLimit is the production default of the login
// limit per address, which code confirmation shares.
registrationEmailHourlyLimit = 10
registrationSecret = "integration-test-identity-key-secret-0123456789"
registrationApplication = "registration_http"
)
var (
@@ -163,6 +166,7 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm
}, identity.ConfirmationSettings{
TokenHourlyLimit: 2,
ClientHourlyLimit: clientHourlyLimit,
EmailHourlyLimit: registrationEmailHourlyLimit,
})
if err != nil {
t.Fatalf("NewEmailConfirmation() error = %v", err)
@@ -301,23 +305,41 @@ func (harness *registrationHarness) registerAndSendVerification(
ctx context.Context,
t *testing.T,
email, scenario, password string,
) string {
t.Helper()
link := verificationLinkToken.FindStringSubmatch(harness.registerAndReceiveVerification(ctx, t, email, scenario, password))
if link == nil {
t.Fatal("the received verification message has no token in its link fragment")
}
return link[1]
}
// registerAndReceiveVerification registers the address, delivers the queued
// message through the fixture, and returns the text of the message.
func (harness *registrationHarness) registerAndReceiveVerification(
ctx context.Context,
t *testing.T,
email, scenario, password string,
) string {
t.Helper()
requestCount := len(harness.fixture.Requests())
response := harness.registerBody(t, registrationBody(email, scenario, password, registrationC1), "")
requireAccepted(t, response)
return harness.receiveVerificationText(ctx, t, email, requestCount)
}
// receiveVerificationText drains the sending worker and returns the text of the
// one message the fixture received after requestCount requests.
func (harness *registrationHarness) receiveVerificationText(ctx context.Context, t *testing.T, email string, requestCount int) string {
t.Helper()
if settled := harness.drain(ctx, t); settled != 1 {
t.Fatalf("settled %d deliveries, want 1", settled)
}
received := harness.fixture.Requests()[requestCount:]
if len(received) != 1 || !slices.Equal(received[0].To, []string{email}) {
t.Fatalf("fixture received %d messages for the registration, want one to the registered address", len(received))
t.Fatalf("fixture received %d messages, want one to the registered address", len(received))
}
link := verificationLinkToken.FindStringSubmatch(received[0].Text)
if link == nil {
t.Fatal("the received verification message has no token in its link fragment")
}
return link[1]
return received[0].Text
}
// truncate empties the tables of the flow. CASCADE also empties tables that
@@ -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.
+1
View File
@@ -136,6 +136,7 @@ func newIdentityHandler(
}, identity.ConfirmationSettings{
TokenHourlyLimit: identity.DefaultTokenHourlyLimit,
ClientHourlyLimit: int64(settings.IdentityClientHourlyLimit),
EmailHourlyLimit: int64(settings.IdentityLoginEmailHourlyLimit),
})
if err != nil {
pool.Close()
+106
View File
@@ -0,0 +1,106 @@
package domain
import (
"crypto/rand"
"errors"
"fmt"
"io"
"log/slog"
"math/big"
"regexp"
"time"
)
const (
// VerificationCodeDigits is the length of the code in a verification
// message. The contract pattern is ^[0-9]{6}$.
VerificationCodeDigits = 6
// VerificationCodeMaxFailedAttempts is the number of failed attempts
// against one open code after which the code and its token are burned.
// The storage check constraint repeats this value.
VerificationCodeMaxFailedAttempts = 5
// VerificationCodeLifetime bounds how long a code works. A token lasts
// longer, so the code ends first; the code expiry is the earlier of the
// two, see NewEmailToken.
VerificationCodeLifetime = 30 * time.Minute
// verificationCodeSpace is the number of distinct codes: 000000 to 999999.
verificationCodeSpace = 1_000_000
)
var (
// ErrInvalidVerificationCode reports a code that is not six ASCII digits.
// Its message never contains the rejected value.
ErrInvalidVerificationCode = errors.New("invalid verification code")
verificationCodeSpaceBig = big.NewInt(verificationCodeSpace)
verificationCodePattern = regexp.MustCompile(`^[0-9]{6}$`)
)
// VerificationCode is the six-digit code of a verification message. Only the
// holder sees the value; String, GoString, Format, and LogValue redact it so
// that it does not reach logs by accident. Reveal returns it for the one place
// that must send it. The value sits behind a pointer, as in SecretToken.
type VerificationCode struct {
value *string
}
// NewVerificationCode returns a code drawn uniformly from 000000 to 999999
// with crypto/rand.
func NewVerificationCode() (VerificationCode, error) {
return newVerificationCode(rand.Reader)
}
// newVerificationCode draws from random. crypto/rand.Int rejects the draws
// above the bound instead of reducing them modulo it, so every code is equally
// likely.
func newVerificationCode(random io.Reader) (VerificationCode, error) {
number, err := rand.Int(random, verificationCodeSpaceBig)
if err != nil {
return VerificationCode{}, fmt.Errorf("domain.NewVerificationCode - draw code: %w", err)
}
return VerificationCode{value: newRedactedValue(fmt.Sprintf("%0*d", VerificationCodeDigits, number.Int64()))}, nil
}
// ParseVerificationCode accepts exactly six ASCII digits from a request. Spaces
// and separators are rejected rather than stripped, so the contract stays exact.
func ParseVerificationCode(raw string) (VerificationCode, error) {
if !verificationCodePattern.MatchString(raw) {
return VerificationCode{}, fmt.Errorf("domain.ParseVerificationCode - code must have %d digits: %w", VerificationCodeDigits, ErrInvalidVerificationCode)
}
return VerificationCode{value: newRedactedValue(raw)}, nil
}
// Reveal returns the digits for delivery to the holder, or for the keyed
// digest. Never store or log the result.
func (code VerificationCode) Reveal() string { return redactedValue(code.value) }
// IsZero reports a VerificationCode not built by NewVerificationCode or
// ParseVerificationCode.
func (code VerificationCode) IsZero() bool { return code.value == nil }
func (code VerificationCode) String() string { return redactedSecret }
func (code VerificationCode) GoString() string { return redactedSecret }
// Format redacts every verb; without it %d would print the digits.
func (code VerificationCode) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) }
func (code VerificationCode) LogValue() slog.Value { return slog.StringValue(redactedSecret) }
// VerificationCodeHash is the keyed digest of a VerificationCode that storage
// keeps. It is an HMAC under a server secret: the code space has only a
// million values, so an unkeyed digest could be reversed by enumeration.
type VerificationCodeHash [SecretTokenHashSize]byte
// IsZero reports the all-zero value, which marks a missing digest.
func (hash VerificationCodeHash) IsZero() bool { return hash == VerificationCodeHash{} }
// EmailCode is the code state of an email token: its keyed digest and the end
// of its validity.
type EmailCode struct {
Hash VerificationCodeHash
ExpiresAt time.Time
}
+194
View File
@@ -0,0 +1,194 @@
package domain
import (
"errors"
"fmt"
"io"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
// fixedReader yields the given bytes in order and then reports an error, so a
// draw that needs more entropy than the test provides fails loudly.
type fixedReader struct {
data []byte
}
func (reader *fixedReader) Read(buffer []byte) (int, error) {
if len(reader.data) == 0 {
return 0, io.ErrUnexpectedEOF
}
count := copy(buffer, reader.data)
reader.data = reader.data[count:]
return count, nil
}
func TestVerificationCodeRejectsDrawsAboveTheBoundInsteadOfReducingThem(t *testing.T) {
// crypto/rand.Int draws 20 random bits for the 1,000,000 codes and masks the
// top byte to 4 bits. 0x0FFFFF is 1048575, above the bound, so it is drawn
// again; the next draw 0x000007 is code 000007. A modulo reduction would
// have returned 048575 here and biased every code.
code, err := newVerificationCode(&fixedReader{data: []byte{0x0F, 0xFF, 0xFF, 0x00, 0x00, 0x07}})
if err != nil {
t.Fatalf("newVerificationCode() error = %v", err)
}
if code.Reveal() != "000007" {
t.Fatalf("code = %q, want 000007", code.Reveal())
}
}
func TestVerificationCodeCoversTheWholeRange(t *testing.T) {
low, err := newVerificationCode(&fixedReader{data: []byte{0x00, 0x00, 0x00}})
if err != nil {
t.Fatalf("newVerificationCode(0) error = %v", err)
}
high, err := newVerificationCode(&fixedReader{data: []byte{0x0F, 0x42, 0x3F}})
if err != nil {
t.Fatalf("newVerificationCode(999999) error = %v", err)
}
if low.Reveal() != "000000" || high.Reveal() != "999999" {
t.Fatalf("bounds = %q and %q, want 000000 and 999999", low.Reveal(), high.Reveal())
}
}
func TestVerificationCodeDrawFailureIsReported(t *testing.T) {
if _, err := newVerificationCode(&fixedReader{}); err == nil {
t.Fatal("newVerificationCode() accepted a failing entropy source")
}
}
func TestNewVerificationCodeIsRoughlyUniform(t *testing.T) {
const draws = 20_000
var buckets [10]int
for range draws {
code, err := NewVerificationCode()
if err != nil {
t.Fatalf("NewVerificationCode() error = %v", err)
}
if len(code.Reveal()) != VerificationCodeDigits {
t.Fatalf("code %q does not have %d digits", code.Reveal(), VerificationCodeDigits)
}
buckets[code.Reveal()[0]-'0']++
}
// The expected count per leading digit is 2000 with a standard deviation
// near 42. A window of about seven standard deviations keeps the test
// deterministic in practice and still rejects a visibly skewed generator.
for digit, count := range buckets {
if count < 1700 || count > 2300 {
t.Fatalf("leading digit %d appeared %d times in %d draws", digit, count, draws)
}
}
}
func TestParseVerificationCodeAcceptsOnlySixASCIIDigits(t *testing.T) {
for _, valid := range []string{"000000", "482915", "999999"} {
code, err := ParseVerificationCode(valid)
if err != nil || code.Reveal() != valid {
t.Fatalf("ParseVerificationCode(%q) = %q, %v", valid, code.Reveal(), err)
}
}
for _, invalid := range []string{"", "48291", "4829156", "48291a", " 482915", "482915\n", "482 915", "482915", "-82915"} {
if _, err := ParseVerificationCode(invalid); !errors.Is(err, ErrInvalidVerificationCode) {
t.Fatalf("ParseVerificationCode(%q) error = %v, want ErrInvalidVerificationCode", invalid, err)
}
}
}
func TestVerificationCodeNeverPrintsItsDigits(t *testing.T) {
code, err := ParseVerificationCode("482915")
if err != nil {
t.Fatal(err)
}
for _, rendered := range []string{
fmt.Sprint(code),
fmt.Sprintf("%v %+v %#v %s %d", code, code, code, code, code),
code.LogValue().String(),
fmt.Sprint(struct{ Code VerificationCode }{code}),
} {
if strings.Contains(rendered, "482915") {
t.Fatalf("rendering %q contains the code", rendered)
}
}
if code.Reveal() != "482915" || code.IsZero() || !(VerificationCode{}).IsZero() {
t.Fatal("Reveal or IsZero does not report the stored code")
}
}
func TestVerificationCodeHashIsZeroOnlyWhenUnset(t *testing.T) {
if !(VerificationCodeHash{}).IsZero() {
t.Fatal("the zero digest is not reported as zero")
}
if (VerificationCodeHash{1}).IsZero() {
t.Fatal("a set digest is reported as zero")
}
}
func verificationTokenInput(t *testing.T, purpose EmailTokenPurpose) NewEmailTokenInput {
t.Helper()
raw, err := NewSecretToken()
if err != nil {
t.Fatal(err)
}
return NewEmailTokenInput{
UserID: uuid.New(),
Purpose: purpose,
TokenHash: raw.Hash(),
RegistrationVersion: 1,
IssuedAt: time.Date(2026, time.October, 9, 12, 0, 0, 0, time.UTC),
Lifetime: 24 * time.Hour,
CodeHash: VerificationCodeHash{1},
CodeLifetime: VerificationCodeLifetime,
}
}
func TestNewEmailTokenEndsTheCodeAtTheEarlierOfTokenAndCodeLifetime(t *testing.T) {
input := verificationTokenInput(t, EmailTokenPurposeEmailVerification)
token, err := NewEmailToken(input)
if err != nil {
t.Fatalf("NewEmailToken() error = %v", err)
}
if token.Code == nil || token.Code.Hash != input.CodeHash {
t.Fatalf("token code = %+v, want the digest", token.Code)
}
if want := input.IssuedAt.Add(VerificationCodeLifetime); !token.Code.ExpiresAt.Equal(want) {
t.Fatalf("code expiry = %s, want %s", token.Code.ExpiresAt, want)
}
input.Lifetime = 10 * time.Minute
token, err = NewEmailToken(input)
if err != nil {
t.Fatalf("NewEmailToken(short token) error = %v", err)
}
if !token.Code.ExpiresAt.Equal(token.ExpiresAt) {
t.Fatalf("code expiry = %s, want the token expiry %s", token.Code.ExpiresAt, token.ExpiresAt)
}
}
func TestNewEmailTokenRequiresCodeFieldsTogetherAndOnlyForVerification(t *testing.T) {
cases := map[string]func(*NewEmailTokenInput){
"hash without lifetime": func(input *NewEmailTokenInput) { input.CodeLifetime = 0 },
"lifetime without hash": func(input *NewEmailTokenInput) { input.CodeHash = VerificationCodeHash{} },
"negative lifetime": func(input *NewEmailTokenInput) { input.CodeLifetime = -time.Minute },
}
for name, mutate := range cases {
input := verificationTokenInput(t, EmailTokenPurposeEmailVerification)
mutate(&input)
if _, err := NewEmailToken(input); !errors.Is(err, ErrInvalidEmailToken) {
t.Fatalf("NewEmailToken(%s) error = %v, want ErrInvalidEmailToken", name, err)
}
}
reset := verificationTokenInput(t, EmailTokenPurposePasswordReset)
if _, err := NewEmailToken(reset); !errors.Is(err, ErrInvalidEmailToken) {
t.Fatalf("NewEmailToken(reset with code) error = %v, want ErrInvalidEmailToken", err)
}
plain := verificationTokenInput(t, EmailTokenPurposeEmailVerification)
plain.CodeHash = VerificationCodeHash{}
plain.CodeLifetime = 0
token, err := NewEmailToken(plain)
if err != nil || token.Code != nil {
t.Fatalf("NewEmailToken(no code) = %+v, %v; want no code state", token.Code, err)
}
}
+32 -3
View File
@@ -68,6 +68,9 @@ type EmailToken struct {
ExpiresAt time.Time
ConsumedAt *time.Time
InvalidatedAt *time.Time
// Code is set on a verification token that carries a six-digit code and
// nil otherwise. Its digest is never the code itself.
Code *EmailCode
// Pending is set on the verification token of a registration and nil on
// a token that carries no credentials.
Pending *PendingRegistration
@@ -82,6 +85,11 @@ type NewEmailTokenInput struct {
RegistrationVersion int64
IssuedAt time.Time
Lifetime time.Duration
// CodeHash and CodeLifetime describe the optional verification code. Both
// are set together or both are zero. The code expires at the earlier of
// the token expiry and IssuedAt plus CodeLifetime.
CodeHash VerificationCodeHash
CodeLifetime time.Duration
// Pending is optional; see PendingRegistration.
Pending *PendingRegistration
}
@@ -99,24 +107,45 @@ func NewEmailToken(input NewEmailTokenInput) (EmailToken, error) {
return EmailToken{}, invalidEmailToken("issue time must be set")
case input.Lifetime <= 0:
return EmailToken{}, invalidEmailToken("lifetime must be positive")
case input.CodeHash.IsZero() != (input.CodeLifetime == 0):
return EmailToken{}, invalidEmailToken("code hash and code lifetime must be set together")
case input.CodeLifetime < 0:
return EmailToken{}, invalidEmailToken("code lifetime must not be negative")
}
if _, err := ParseEmailTokenPurpose(string(input.Purpose)); err != nil {
return EmailToken{}, fmt.Errorf("domain.NewEmailToken - validate purpose: %w", err)
}
if !input.CodeHash.IsZero() && input.Purpose != EmailTokenPurposeEmailVerification {
return EmailToken{}, invalidEmailToken("only an email verification token carries a code")
}
id, err := uuid.NewV7()
if err != nil {
return EmailToken{}, fmt.Errorf("domain.NewEmailToken - generate token ID: %w", err)
}
return EmailToken{
expiresAt := input.IssuedAt.Add(input.Lifetime)
token := EmailToken{
ID: id,
UserID: input.UserID,
Purpose: input.Purpose,
TokenHash: input.TokenHash,
RegistrationVersion: input.RegistrationVersion,
CreatedAt: input.IssuedAt,
ExpiresAt: input.IssuedAt.Add(input.Lifetime),
ExpiresAt: expiresAt,
Pending: input.Pending,
}, nil
}
if !input.CodeHash.IsZero() {
token.Code = &EmailCode{Hash: input.CodeHash, ExpiresAt: earlierInstant(expiresAt, input.IssuedAt.Add(input.CodeLifetime))}
}
return token, nil
}
// earlierInstant returns the earlier of two instants. The time type is not
// ordered by the built-in min.
func earlierInstant(left, right time.Time) time.Time {
if right.Before(left) {
return right
}
return left
}
func invalidEmailToken(reason string) error {
@@ -176,6 +176,20 @@ type EmailTokenRepository interface {
// ErrUserVersionConflict; the rollback also restores the token. The
// confirmation usecase maps that outcome to verification_token_invalid.
Consume(ctx context.Context, hash domain.SecretTokenHash, purpose domain.EmailTokenPurpose, at time.Time) (domain.EmailToken, error)
// FindOpenCodeByAddress returns the newest open verification token that
// carries a code for the unverified account with the normalized address,
// and whose registration is current. It returns ErrEmailTokenNotFound when
// there is none. The caller compares the code and the password, then
// consumes the token with Consume in its transaction.
FindOpenCodeByAddress(ctx context.Context, email domain.EmailAddress) (domain.EmailToken, error)
// RecordFailedCodeAttempt counts one wrong code or password against the
// open token with the ID at the given time. The attempt that reaches
// domain.VerificationCodeMaxFailedAttempts invalidates the token, drops
// its code and pending credentials, and reports burned true. A token that
// is no longer open is left unchanged and reports false without an error.
RecordFailedCodeAttempt(ctx context.Context, id uuid.UUID, at time.Time) (burned bool, err error)
}
// SessionRepository stores server-side sessions by the hash of their token.
@@ -0,0 +1,191 @@
package identity
import (
"context"
"errors"
"fmt"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
// codePointer is the JSON Pointer of the code field in a request body.
codePointer = "/code"
// addressCodeWindow is the window of the per-address limit. It is the
// window of the login limit, so both draw on one counter.
addressCodeWindow = time.Hour
)
// ConfirmCodeCommand is the content of a confirmation by the six-digit code of
// a verification message, unvalidated.
type ConfirmCodeCommand struct {
Email string
Code string
Password string
// ClientKey is the opaque limiter key of the client network address.
ClientKey string
}
// ConfirmByCode verifies the address with the code of its verification
// message. It checks the same things as the link confirmation: the open token
// of the current registration, the password chosen for that registration, and
// the consumption of the token in one transaction. The code also has its own
// expiry and attempt limit.
//
// Every refusal is ErrVerificationTokenInvalid, whatever its cause: an unknown
// address, no open code, a wrong code or password, an expired code, or a burned
// token. The answer then does not reveal which addresses have a pending
// registration. Each failed attempt against an open code is counted in the
// token row; the attempt that reaches the limit burns the token, so both the
// code and the link stop working.
//
// The password is checked on every branch, with the same hashing work, so the
// time of a refusal does not depend on whether the address has an account.
func (confirmation *EmailConfirmation) ConfirmByCode(ctx context.Context, command ConfirmCodeCommand) (ConfirmationResult, error) {
const location = "EmailConfirmation.ConfirmByCode"
email, err := domain.NewEmailAddress(command.Email)
if err != nil {
return ConfirmationResult{}, fmt.Errorf("%s - validate email: %w", location, invalidField(emailPointer, err))
}
code, err := domain.ParseVerificationCode(command.Code)
if err != nil {
return ConfirmationResult{}, fmt.Errorf("%s - validate code: %w", location, invalidField(codePointer, err))
}
if err := confirmation.takeCodeAttempt(ctx, email, command.ClientKey); err != nil {
return ConfirmationResult{}, fmt.Errorf("%s - limit code confirmation: %w", location, err)
}
open, found, err := confirmation.findOpenCode(ctx, email)
if err != nil {
return ConfirmationResult{}, fmt.Errorf("%s - read open code: %w", location, err)
}
passwordMatches, err := confirmation.codePasswordMatches(ctx, command.Password, open, found)
if err != nil {
return ConfirmationResult{}, fmt.Errorf("%s - verify registration password: %w", location, err)
}
now := confirmation.deps.Clock()
if !found || !passwordMatches || !codeMatches(confirmation.deps.Keyring, code, open, now) {
if found {
if _, err := confirmation.deps.Tokens.RecordFailedCodeAttempt(ctx, open.ID, now); err != nil {
return ConfirmationResult{}, fmt.Errorf("%s - count failed attempt: %w", location, err)
}
}
return ConfirmationResult{}, fmt.Errorf("%s - code does not confirm the registration: %w", location, ErrVerificationTokenInvalid)
}
var result ConfirmationResult
err = confirmation.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return confirmation.confirmInTransaction(ctx, unit, open.TokenHash, open, &result)
})
if err != nil {
return ConfirmationResult{}, fmt.Errorf("%s - confirm registration: %w", location, codeOutcomeError(err))
}
return result, nil
}
// takeCodeAttempt counts the request against the client limit, when the request
// has a client key, and against the normalized address. The address counter
// sees every request, whether or not an account exists.
func (confirmation *EmailConfirmation) takeCodeAttempt(ctx context.Context, email domain.EmailAddress, clientKey string) error {
const location = "EmailConfirmation.takeCodeAttempt"
if clientKey != "" {
err := takeRateLimit(ctx, confirmation.deps.Limiter, confirmation.deps.Metrics, ScopeClient,
confirmation.deps.Keyring.ClientBucket(clientKey),
outbound.RateLimitRule{Window: clientWindow, Limit: confirmation.settings.ClientHourlyLimit})
if err != nil {
return fmt.Errorf("%s - take client limit: %w", location, err)
}
}
err := takeRateLimit(ctx, confirmation.deps.Limiter, confirmation.deps.Metrics, ScopeAddress,
confirmation.deps.Keyring.EmailBucket(email.Normalized()),
outbound.RateLimitRule{Window: addressCodeWindow, Limit: confirmation.settings.EmailHourlyLimit})
if err != nil {
return fmt.Errorf("%s - take address limit: %w", location, err)
}
return nil
}
// takeRateLimit counts one request against one rule and reports a refusal as
// *RateLimitedError, after it notifies the metrics of the scope.
func takeRateLimit(
ctx context.Context,
limiter outbound.RateLimiter,
metrics RateLimitMetrics,
scope, bucket string,
rule outbound.RateLimitRule,
) error {
decision, err := limiter.Take(ctx, bucket, rule)
if err != nil {
return fmt.Errorf("take rate limit: %w", err)
}
if !decision.Allowed {
if metrics != nil {
metrics.ObserveIdentityRateLimited(scope)
}
return &RateLimitedError{RetryAfter: decision.RetryAfter}
}
return nil
}
// findOpenCode returns the open code token of the address and whether one
// exists. The absence of a token is not an error: it is one of the refusals.
func (confirmation *EmailConfirmation) findOpenCode(ctx context.Context, email domain.EmailAddress) (domain.EmailToken, bool, error) {
token, err := confirmation.deps.Tokens.FindOpenCodeByAddress(ctx, email)
switch {
case errors.Is(err, outbound.ErrEmailTokenNotFound):
return domain.EmailToken{}, false, nil
case err != nil:
return domain.EmailToken{}, false, fmt.Errorf("EmailConfirmation.findOpenCode - read token: %w", err)
}
return token, true, nil
}
// codePasswordMatches reports whether password is the one chosen for the
// registration of the open code. With no open code, or a password outside the
// login bounds, it spends the same hashing work on a dummy hash and reports no
// match; the work does not depend on whether the address has an account.
func (confirmation *EmailConfirmation) codePasswordMatches(
ctx context.Context,
password string,
open domain.EmailToken,
found bool,
) (bool, error) {
credentials := confirmation.deps.Credentials
if _, err := domain.ParseLoginPassword(password); err != nil || !found || open.Pending == nil {
err := credentials.VerifyDummyLoginPassword(ctx, password)
if err != nil && !errors.Is(err, outbound.ErrPasswordMismatch) {
return false, fmt.Errorf("EmailConfirmation.codePasswordMatches - verify dummy hash: %w", err)
}
return false, nil
}
err := credentials.VerifyLoginPassword(ctx, password, open.Pending.PasswordHash)
switch {
case err == nil:
return true, nil
case errors.Is(err, outbound.ErrPasswordMismatch), errors.Is(err, domain.ErrInvalidPassword):
return false, nil
default:
return false, fmt.Errorf("EmailConfirmation.codePasswordMatches - verify password: %w", err)
}
}
// codeMatches reports whether code is the open code of the token, and whether
// both the code and the token are still within their validity. It is false when
// there is no open code.
func codeMatches(keyring *Keyring, code domain.VerificationCode, open domain.EmailToken, now time.Time) bool {
if open.Code == nil || !open.Code.ExpiresAt.After(now) || !open.ExpiresAt.After(now) {
return false
}
return keyring.VerifyVerificationCode(code, open.Code.Hash)
}
// codeOutcomeError maps the outcome of the code transaction to the single
// refusal of the code operation, so an expired token is not reported apart.
func codeOutcomeError(err error) error {
if errors.Is(err, ErrVerificationTokenExpired) {
return ErrVerificationTokenInvalid
}
return confirmationOutcomeError(err)
}
@@ -0,0 +1,437 @@
package identity
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
codeTestSecret = "code confirmation test key with enough entropy"
codeTestEmailLimit = 10
codeTestClientLimit = 30
)
// codeTestStore models the verification token row that the confirmation
// reads and writes: the open code, its failed attempts, and the closing
// outcomes of consumption and burning.
type codeTestStore struct {
outbound.EmailTokenRepository
token domain.EmailToken
missing bool
attempts int
recorded int
closed bool
consumed bool
invalidated bool
}
func (store *codeTestStore) FindByHash(_ context.Context, hash domain.SecretTokenHash, _ domain.EmailTokenPurpose) (domain.EmailToken, error) {
if store.missing || hash != store.token.TokenHash {
return domain.EmailToken{}, outbound.ErrEmailTokenNotFound
}
token := store.token
if store.consumed {
consumedAt := token.CreatedAt
token.ConsumedAt = &consumedAt
}
if store.invalidated {
invalidatedAt := token.CreatedAt
token.InvalidatedAt = &invalidatedAt
}
return token, nil
}
func (store *codeTestStore) FindOpenCodeByAddress(context.Context, domain.EmailAddress) (domain.EmailToken, error) {
if store.missing || store.closed || store.token.Code == nil {
return domain.EmailToken{}, outbound.ErrEmailTokenNotFound
}
return store.token, nil
}
func (store *codeTestStore) RecordFailedCodeAttempt(_ context.Context, id uuid.UUID, _ time.Time) (bool, error) {
if store.missing || store.closed || id != store.token.ID {
return false, nil
}
store.recorded++
store.attempts++
if store.attempts >= domain.VerificationCodeMaxFailedAttempts {
store.closed = true
store.invalidated = true
return true, nil
}
return false, nil
}
// Consume closes the token the way the link path does, so the code and the
// link share one consumption.
func (store *codeTestStore) Consume(_ context.Context, hash domain.SecretTokenHash, _ domain.EmailTokenPurpose, at time.Time) (domain.EmailToken, error) {
switch {
case store.missing || hash != store.token.TokenHash:
return domain.EmailToken{}, outbound.ErrEmailTokenNotFound
case store.consumed:
return domain.EmailToken{}, outbound.ErrEmailTokenConsumed
case store.invalidated:
return domain.EmailToken{}, outbound.ErrEmailTokenInvalidated
case !store.token.ExpiresAt.After(at):
return domain.EmailToken{}, outbound.ErrEmailTokenExpired
}
store.closed = true
store.consumed = true
token := store.token
token.ConsumedAt = &at
return token, nil
}
// codeTestUnit gives the confirmation the four repositories a successful
// transaction uses. Any other accessor panics, which keeps the test honest.
type codeTestUnit struct {
outbound.UnitOfWork
store *codeTestStore
}
func (unit codeTestUnit) EmailTokens() outbound.EmailTokenRepository { return unit.store }
func (unit codeTestUnit) Users() outbound.UserRepository { return codeTestUsers{store: unit.store} }
func (unit codeTestUnit) ConsentLedger() outbound.ConsentLedger { return codeTestLedger{} }
func (unit codeTestUnit) Outbox() outbound.OutboxWriter { return codeTestOutbox{} }
type codeTestUsers struct {
outbound.UserRepository
store *codeTestStore
}
func (users codeTestUsers) ConfirmEmail(_ context.Context, id uuid.UUID, _ int64, _ domain.PendingRegistration, at time.Time) (domain.User, error) {
return domain.User{
ID: id,
Scenario: domain.ScenarioCandidate,
OnboardingStep: domain.OnboardingStepCandidateConsents,
EmailVerifiedAt: &at,
Version: 2,
}, nil
}
type codeTestLedger struct {
outbound.ConsentLedger
}
func (codeTestLedger) LockRegistration(context.Context, uuid.UUID, int64) (domain.ConsentRecord, error) {
return domain.ConsentRecord{}, nil
}
type codeTestOutbox struct{}
func (codeTestOutbox) Append(context.Context, ...domain.DomainEvent) error { return nil }
type codeTestTransactor struct {
unit outbound.UnitOfWork
calls int
}
func (transactor *codeTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
transactor.calls++
return work(ctx, transactor.unit)
}
// codeTestLimiter records every key and refuses when deny is set.
type codeTestLimiter struct {
keys []string
rules [][]outbound.RateLimitRule
deny bool
}
func (limiter *codeTestLimiter) Take(_ context.Context, key string, rules ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) {
limiter.keys = append(limiter.keys, key)
limiter.rules = append(limiter.rules, rules)
if limiter.deny {
return outbound.RateLimitDecision{Allowed: false, RetryAfter: time.Minute}, nil
}
return outbound.RateLimitDecision{Allowed: true}, nil
}
type codeFixture struct {
now time.Time
keyring *Keyring
raw domain.SecretToken
code domain.VerificationCode
store *codeTestStore
hasher *countingHasher
limiter *codeTestLimiter
transactor *codeTestTransactor
confirmation *EmailConfirmation
}
func newCodeFixture(t *testing.T) *codeFixture {
t.Helper()
now := time.Date(2026, time.October, 9, 12, 0, 0, 0, time.UTC)
keyring, err := NewKeyring([]byte(codeTestSecret))
if err != nil {
t.Fatal(err)
}
raw, err := domain.NewSecretToken()
if err != nil {
t.Fatal(err)
}
code, err := domain.ParseVerificationCode("482915")
if err != nil {
t.Fatal(err)
}
passwordHash, err := domain.NewPasswordHash(confirmationTestPasswordHash)
if err != nil {
t.Fatal(err)
}
pending, err := domain.NewPendingRegistration(passwordHash, domain.ScenarioCandidate)
if err != nil {
t.Fatal(err)
}
token, err := domain.NewEmailToken(domain.NewEmailTokenInput{
UserID: uuid.New(),
Purpose: domain.EmailTokenPurposeEmailVerification,
TokenHash: raw.Hash(),
RegistrationVersion: 1,
IssuedAt: now,
Lifetime: 24 * time.Hour,
CodeHash: keyring.VerificationCodeDigest(code),
CodeLifetime: domain.VerificationCodeLifetime,
Pending: &pending,
})
if err != nil {
t.Fatal(err)
}
store := &codeTestStore{token: token}
hasher := &countingHasher{}
limiter := &codeTestLimiter{}
transactor := &codeTestTransactor{unit: codeTestUnit{store: store}}
confirmation, err := NewEmailConfirmation(ConfirmationDependencies{
Transactor: transactor,
Tokens: store,
Credentials: NewCredentials(hasher),
Limiter: limiter,
Keyring: keyring,
Clock: func() time.Time { return now },
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: codeTestClientLimit, EmailHourlyLimit: codeTestEmailLimit})
if err != nil {
t.Fatal(err)
}
return &codeFixture{
now: now, keyring: keyring, raw: raw, code: code, store: store, hasher: hasher,
limiter: limiter, transactor: transactor, confirmation: confirmation,
}
}
func (fixture *codeFixture) command(code, password string) ConfirmCodeCommand {
return ConfirmCodeCommand{Email: "Candidate@Example.com", Code: code, Password: password, ClientKey: "client-key"}
}
func wrongCodeFor(code domain.VerificationCode) string {
if code.Reveal() == "000000" {
return "000001"
}
return "000000"
}
func requireInvalidCode(t *testing.T, err error) {
t.Helper()
if !errors.Is(err, ErrVerificationTokenInvalid) {
t.Fatalf("ConfirmByCode() error = %v, want ErrVerificationTokenInvalid", err)
}
}
func TestConfirmByCodeRejectsMalformedFieldsBeforeAnyLookup(t *testing.T) {
for _, test := range []struct {
name string
email string
code string
pointer string
}{
{name: "email", email: "not-an-address", code: "482915", pointer: emailPointer},
{name: "short code", email: "candidate@example.com", code: "48291", pointer: codePointer},
{name: "long code", email: "candidate@example.com", code: "4829156", pointer: codePointer},
{name: "letters", email: "candidate@example.com", code: "48291A", pointer: codePointer},
{name: "spaces", email: "candidate@example.com", code: " 482915", pointer: codePointer},
{name: "empty", email: "candidate@example.com", code: "", pointer: codePointer},
} {
t.Run(test.name, func(t *testing.T) {
fixture := newCodeFixture(t)
_, err := fixture.confirmation.ConfirmByCode(context.Background(), ConfirmCodeCommand{
Email: test.email, Code: test.code, Password: "correct horse battery staple", ClientKey: "client-key",
})
var field *InvalidFieldError
if !errors.As(err, &field) || field.Pointer != test.pointer {
t.Fatalf("ConfirmByCode() error = %v, want invalid field %s", err, test.pointer)
}
if len(fixture.limiter.keys) != 0 || fixture.store.recorded != 0 || fixture.hasher.verifyCalls+fixture.hasher.dummyCalls != 0 {
t.Fatal("a malformed request reached the limiter, the store, or the hasher")
}
})
}
}
func TestConfirmByCodeChecksTheClientAndAddressLimitsBeforeTheLookup(t *testing.T) {
fixture := newCodeFixture(t)
fixture.limiter.deny = true
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command("482915", "correct horse battery staple"))
var limited *RateLimitedError
if !errors.As(err, &limited) || limited.RetryAfter != time.Minute {
t.Fatalf("ConfirmByCode() error = %v, want rate limit", err)
}
if len(fixture.limiter.keys) != 1 || fixture.limiter.keys[0] != fixture.keyring.ClientBucket("client-key") {
t.Fatalf("limiter keys = %v, want the client bucket only", fixture.limiter.keys)
}
fixture.limiter.keys = nil
fixture.limiter.rules = nil
if _, err := fixture.confirmation.ConfirmByCode(context.Background(), ConfirmCodeCommand{
Email: "Candidate@Example.com", Code: "482915", Password: "correct horse battery staple",
}); !errors.As(err, &limited) {
t.Fatalf("ConfirmByCode() without client key error = %v, want the address rate limit", err)
}
if got, want := fixture.limiter.keys[0], fixture.keyring.EmailBucket("candidate@example.com"); got != want {
t.Fatalf("address bucket = %q, want the normalized address bucket", got)
}
rule := fixture.limiter.rules[0]
if len(rule) != 1 || rule[0].Window != time.Hour || rule[0].Limit != codeTestEmailLimit {
t.Fatalf("address rule = %+v, want one hour and the login limit", rule)
}
if fixture.store.recorded != 0 || fixture.hasher.dummyCalls+fixture.hasher.verifyCalls != 0 {
t.Fatal("a refused request reached the store or the hasher")
}
}
func TestConfirmByCodeRefusesAnUnknownAddressWithTheSameWork(t *testing.T) {
fixture := newCodeFixture(t)
fixture.store.missing = true
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
requireInvalidCode(t, err)
if fixture.hasher.dummyCalls != 1 || fixture.hasher.verifyCalls != 0 {
t.Fatalf("hasher calls = dummy %d, verify %d; want one dummy comparison", fixture.hasher.dummyCalls, fixture.hasher.verifyCalls)
}
if fixture.store.recorded != 0 || fixture.transactor.calls != 0 {
t.Fatal("an unknown address counted an attempt or opened a transaction")
}
}
func TestConfirmByCodeWrongCodeBurnsTheTokenOnTheFifthAttempt(t *testing.T) {
fixture := newCodeFixture(t)
wrong := wrongCodeFor(fixture.code)
for attempt := 1; attempt <= domain.VerificationCodeMaxFailedAttempts; attempt++ {
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(wrong, "correct horse battery staple"))
requireInvalidCode(t, err)
if closed := fixture.store.closed; closed != (attempt == domain.VerificationCodeMaxFailedAttempts) {
t.Fatalf("after attempt %d the token closed = %v", attempt, closed)
}
}
if fixture.store.recorded != domain.VerificationCodeMaxFailedAttempts {
t.Fatalf("counted attempts = %d, want %d", fixture.store.recorded, domain.VerificationCodeMaxFailedAttempts)
}
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
requireInvalidCode(t, err)
if fixture.transactor.calls != 0 {
t.Fatal("the right code confirmed after the token was burned")
}
}
func TestConfirmByCodeWrongPasswordWithTheRightCodeIsRefusedAndCounted(t *testing.T) {
fixture := newCodeFixture(t)
fixture.hasher.verifyErr = outbound.ErrPasswordMismatch
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "a wrong password for this registration"))
requireInvalidCode(t, err)
if fixture.hasher.verifyCalls != 1 || fixture.store.recorded != 1 || fixture.transactor.calls != 0 {
t.Fatalf("verify %d, counted %d, transactions %d", fixture.hasher.verifyCalls, fixture.store.recorded, fixture.transactor.calls)
}
if fixture.store.closed {
t.Fatal("one wrong password closed the token")
}
}
// An attacker who registered someone else's address knows the password of the
// registration but not the code, which goes only to the address owner.
func TestConfirmByCodeAttackerRegistrationNeedsTheOwnersCode(t *testing.T) {
fixture := newCodeFixture(t)
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(wrongCodeFor(fixture.code), "correct horse battery staple"))
requireInvalidCode(t, err)
if fixture.store.recorded != 1 || fixture.store.closed {
t.Fatalf("counted %d, closed %v; want one counted attempt and an open token", fixture.store.recorded, fixture.store.closed)
}
}
func TestConfirmByCodeRefusesAnExpiredCode(t *testing.T) {
fixture := newCodeFixture(t)
fixture.confirmation.deps.Clock = func() time.Time { return fixture.now.Add(domain.VerificationCodeLifetime + time.Second) }
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
requireInvalidCode(t, err)
if errors.Is(err, ErrVerificationTokenExpired) {
t.Fatal("an expired code reported its own refusal")
}
if fixture.store.recorded != 1 || fixture.transactor.calls != 0 {
t.Fatalf("counted %d, transactions %d", fixture.store.recorded, fixture.transactor.calls)
}
}
func TestConfirmByCodeMalformedPasswordDoesNotSkipTheHashingWork(t *testing.T) {
fixture := newCodeFixture(t)
for _, password := range []string{"", strings.Repeat("p", 129)} {
fixture.hasher.dummyCalls = 0
fixture.hasher.verifyCalls = 0
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), password))
requireInvalidCode(t, err)
if fixture.hasher.dummyCalls != 1 || fixture.hasher.verifyCalls != 0 {
t.Fatalf("password length %d: hasher calls dummy %d, verify %d", len(password), fixture.hasher.dummyCalls, fixture.hasher.verifyCalls)
}
}
}
func TestConfirmByCodeConsumesTheTokenAndBlocksLaterUse(t *testing.T) {
fixture := newCodeFixture(t)
result, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
if err != nil {
t.Fatalf("ConfirmByCode() error = %v", err)
}
if result.Scenario != domain.ScenarioCandidate || result.OnboardingStep != domain.OnboardingStepCandidateConsents {
t.Fatalf("result = %+v", result)
}
if !fixture.store.consumed || fixture.transactor.calls != 1 {
t.Fatalf("consumed %v, transactions %d", fixture.store.consumed, fixture.transactor.calls)
}
_, err = fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
requireInvalidCode(t, err)
_, err = fixture.confirmation.Confirm(context.Background(), ConfirmCommand{Token: fixture.raw.Reveal(), Password: "correct horse battery staple"})
requireInvalidCode(t, err)
}
// The link consumes the same token, so a code confirmation after it is refused.
func TestLinkConfirmationBurnsTheCode(t *testing.T) {
fixture := newCodeFixture(t)
if _, err := fixture.confirmation.Confirm(context.Background(), ConfirmCommand{
Token: fixture.raw.Reveal(), Password: "correct horse battery staple", ClientKey: "client-key",
}); err != nil {
t.Fatalf("Confirm() error = %v", err)
}
_, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple"))
requireInvalidCode(t, err)
if fixture.transactor.calls != 1 {
t.Fatalf("transactions = %d, want only the link confirmation", fixture.transactor.calls)
}
}
func TestVerificationCodeSettingsMustBePositive(t *testing.T) {
fixture := newCodeFixture(t)
_, err := NewEmailConfirmation(ConfirmationDependencies{
Transactor: fixture.transactor, Tokens: fixture.store, Credentials: NewCredentials(fixture.hasher),
Limiter: fixture.limiter, Keyring: fixture.keyring, Clock: time.Now,
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 30})
if err == nil {
t.Fatal("NewEmailConfirmation() accepted a missing address limit")
}
}
@@ -31,11 +31,14 @@ type ConfirmationDependencies struct {
Metrics RateLimitMetrics
}
// ConfirmationSettings contains the attempt limits for one token and one
// client. The client limit matches registration and resend.
// ConfirmationSettings contains the attempt limits for one token, one client,
// and one normalized address. The client limit matches registration and
// resend. The address limit is the login limit: code confirmation draws on the
// same hourly budget as login for the address.
type ConfirmationSettings struct {
TokenHourlyLimit int64
ClientHourlyLimit int64
EmailHourlyLimit int64
}
// EmailConfirmation confirms the address and applies the credentials of the
@@ -52,7 +55,7 @@ func NewEmailConfirmation(deps ConfirmationDependencies, settings ConfirmationSe
case deps.Transactor == nil, deps.Tokens == nil, deps.Credentials == nil,
deps.Limiter == nil, deps.Keyring == nil, deps.Clock == nil:
return nil, errors.New("identity.NewEmailConfirmation - every dependency must be set")
case settings.TokenHourlyLimit < 1, settings.ClientHourlyLimit < 1:
case settings.TokenHourlyLimit < 1, settings.ClientHourlyLimit < 1, settings.EmailHourlyLimit < 1:
return nil, errors.New("identity.NewEmailConfirmation - confirmation limits must be positive")
}
return &EmailConfirmation{deps: deps, settings: settings}, nil
@@ -114,6 +117,8 @@ func (confirmation *EmailConfirmation) Confirm(ctx context.Context, command Conf
return result, nil
}
// confirmationOutcomeError maps the storage outcome of a link confirmation to
// the public refusals. Expiry is reported as its own refusal.
func confirmationOutcomeError(err error) error {
switch {
case errors.Is(err, outbound.ErrEmailTokenExpired):
@@ -108,7 +108,7 @@ func TestEmailConfirmationKeepsInvalidTokenPrecedenceOverExpiry(t *testing.T) {
confirmation, err := NewEmailConfirmation(ConfirmationDependencies{
Transactor: transactor, Tokens: tokens, Credentials: NewCredentials(nil),
Limiter: limiter, Keyring: keyring, Clock: func() time.Time { return now },
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20})
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20, EmailHourlyLimit: 10})
if err != nil {
t.Fatal(err)
}
@@ -138,7 +138,7 @@ func TestEmailConfirmationClientLimitRunsBeforeTokenLookup(t *testing.T) {
confirmation, err := NewEmailConfirmation(ConfirmationDependencies{
Transactor: transactor, Tokens: tokens, Credentials: NewCredentials(nil),
Limiter: limiter, Keyring: keyring, Clock: time.Now,
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20})
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20, EmailHourlyLimit: 10})
if err != nil {
t.Fatal(err)
}
@@ -25,6 +25,7 @@ const (
labelEmailBucket = "lincodex/identity/email-bucket/v1"
labelClientBucket = "lincodex/identity/client-bucket/v1"
labelTokenBucket = "lincodex/identity/verification-token-bucket/v1"
labelVerificationCode = "lincodex/identity/verification-code/v1"
labelSessionCSRF = "lincodex/identity/session-csrf/v1"
labelCandidateView = "lincodex/identity/candidate-view/v1"
@@ -45,6 +46,7 @@ type Keyring struct {
bucketKey []byte
clientKey []byte
tokenKey []byte
codeKey []byte
sessionCSRFKey []byte
candidateViewKey []byte
answerKey []byte
@@ -64,6 +66,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
bucketKey: derive(secret, labelEmailBucket),
clientKey: derive(secret, labelClientBucket),
tokenKey: derive(secret, labelTokenBucket),
codeKey: derive(secret, labelVerificationCode),
sessionCSRFKey: derive(secret, labelSessionCSRF),
candidateViewKey: derive(secret, labelCandidateView),
answerKey: derive(secret, labelAnswerFingerprint),
@@ -148,6 +151,26 @@ func (keyring *Keyring) VerificationTokenBucket(rawToken string) string {
return "identity:verification-token:" + hex.EncodeToString(mac.Sum(nil))
}
// VerificationCodeDigest keys a six-digit verification code under the code
// purpose key. The code space holds only a million values, so an unkeyed digest
// could be reversed by enumeration; the keyed digest cannot be checked offline
// without the server secret.
func (keyring *Keyring) VerificationCodeDigest(code domain.VerificationCode) domain.VerificationCodeHash {
mac := hmac.New(sha256.New, keyring.codeKey)
mac.Write([]byte(code.Reveal()))
return domain.VerificationCodeHash(mac.Sum(nil))
}
// VerifyVerificationCode compares a supplied code with a stored digest in
// constant time.
func (keyring *Keyring) VerifyVerificationCode(code domain.VerificationCode, stored domain.VerificationCodeHash) bool {
if code.IsZero() || stored.IsZero() {
return false
}
computed := keyring.VerificationCodeDigest(code)
return hmac.Equal(computed[:], stored[:])
}
// SessionCSRF derives a synchronizer token for exactly one session. The
// purpose key and message are both domain-separated from every other keyring
// use, and only the encoded result is returned to the HTTP adapter.
@@ -143,3 +143,41 @@ func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t
t.Fatal("the cursor signature shares a key with the idempotency scope")
}
}
func TestVerificationCodeDigestIsKeyedAndPurposeSeparated(t *testing.T) {
keyring, err := NewKeyring([]byte("keyring test secret with enough entropy"))
if err != nil {
t.Fatal(err)
}
other, err := NewKeyring([]byte("another keyring secret with enough entropy"))
if err != nil {
t.Fatal(err)
}
code, err := domain.ParseVerificationCode("482915")
if err != nil {
t.Fatal(err)
}
digest := keyring.VerificationCodeDigest(code)
if digest != keyring.VerificationCodeDigest(code) {
t.Fatal("the same code gives different digests under one key")
}
if digest == other.VerificationCodeDigest(code) {
t.Fatal("two server secrets give the same digest for one code")
}
if digest == domain.VerificationCodeHash(sha256.Sum256([]byte("482915"))) {
t.Fatal("the stored digest is an unkeyed SHA-256 of the code")
}
if !keyring.VerifyVerificationCode(code, digest) {
t.Fatal("VerifyVerificationCode() rejected the matching code")
}
wrong, err := domain.ParseVerificationCode("482916")
if err != nil {
t.Fatal(err)
}
if keyring.VerifyVerificationCode(wrong, digest) {
t.Fatal("VerifyVerificationCode() accepted a wrong code")
}
if keyring.VerifyVerificationCode(domain.VerificationCode{}, digest) || keyring.VerifyVerificationCode(code, domain.VerificationCodeHash{}) {
t.Fatal("VerifyVerificationCode() accepted a missing code or digest")
}
}
+15 -5
View File
@@ -365,7 +365,9 @@ func (registration *Registration) reRegister(
}
// issueVerification stores a new token bound to the current registration
// version and queues its message, in the caller's transaction.
// version and queues its message, in the caller's transaction. The message
// carries a six-digit code next to the link; storage keeps only the keyed digest
// of the code, which ends with the token or after the code lifetime.
func (registration *Registration) issueVerification(
ctx context.Context,
unit outbound.UnitOfWork,
@@ -383,6 +385,10 @@ func (registration *Registration) issueVerification(
if err != nil {
return fmt.Errorf("%s - generate token: %w", location, err)
}
code, err := domain.NewVerificationCode()
if err != nil {
return fmt.Errorf("%s - generate code: %w", location, err)
}
token, err := domain.NewEmailToken(domain.NewEmailTokenInput{
UserID: user.ID,
Purpose: domain.EmailTokenPurposeEmailVerification,
@@ -390,6 +396,8 @@ func (registration *Registration) issueVerification(
RegistrationVersion: user.RegistrationVersion,
IssuedAt: now,
Lifetime: lifetime.Duration(),
CodeHash: registration.deps.Keyring.VerificationCodeDigest(code),
CodeLifetime: domain.VerificationCodeLifetime,
Pending: pending,
})
if err != nil {
@@ -399,10 +407,12 @@ func (registration *Registration) issueVerification(
return fmt.Errorf("%s - store token: %w", location, err)
}
_, err = registration.deps.Mailer.EnqueueVerification(ctx, unit, notification.TokenMailRequest{
Recipient: user.Email,
Token: token,
RawToken: raw,
Lifetime: lifetime,
Recipient: user.Email,
Token: token,
RawToken: raw,
Lifetime: lifetime,
Code: code,
CodeLifetime: domain.VerificationCodeLifetime,
})
if err != nil {
return fmt.Errorf("%s - queue message: %w", location, err)
@@ -4,6 +4,7 @@ import (
"fmt"
"log/slog"
"strings"
"time"
"unicode"
"unicode/utf8"
@@ -36,6 +37,12 @@ type VerificationData struct {
// TokenLifetime is the policy value stated in the copy, from 1 hour to
// 7 days.
TokenLifetime domain.Hours
// Code is the six-digit code the message shows. VerificationCode redacts
// itself in fmt and slog output.
Code domain.VerificationCode
// CodeLifetime is the validity of the code stated in the copy: whole
// minutes, from 1 to 60.
CodeLifetime time.Duration
}
// PasswordResetData is the input of the password reset message.
@@ -77,6 +84,15 @@ type tokenLinkView struct {
LifetimeHours int
}
// verificationCodeView is what the verification templates receive: the link
// view plus the code and its validity in whole minutes.
type verificationCodeView struct {
tokenLinkView
Code string
CodeLifetimeMinutes int
}
// notificationView is what the notification templates receive. TextBody is
// the sanitized body for the plain-text part; Paragraphs holds the same lines
// for the HTML part, where html/template escapes each line.
@@ -97,6 +113,26 @@ func (renderer *Renderer) tokenLinkView(linkPath string, token domain.SecretToke
return tokenLinkView{Link: renderer.tokenLink(linkPath, token), LifetimeHours: int(lifetime)}, nil
}
// maxCodeLifetimeMinutes bounds the code copy; the code lifetime is a fixed
// product value of 30 minutes, so a longer value in the copy would be a bug.
const maxCodeLifetimeMinutes = 60
func (renderer *Renderer) verificationCodeView(data VerificationData) (verificationCodeView, error) {
const location = "Renderer.verificationCodeView"
link, err := renderer.tokenLinkView(verifyEmailPath, data.Token, data.TokenLifetime)
if err != nil {
return verificationCodeView{}, err
}
if data.Code.IsZero() {
return verificationCodeView{}, invalidData(location, "verification code must be set")
}
minutes := data.CodeLifetime / time.Minute
if data.CodeLifetime%time.Minute != 0 || minutes < 1 || minutes > maxCodeLifetimeMinutes {
return verificationCodeView{}, invalidData(location, fmt.Sprintf("code lifetime must be whole minutes from 1 to %d", maxCodeLifetimeMinutes))
}
return verificationCodeView{tokenLinkView: link, Code: data.Code.Reveal(), CodeLifetimeMinutes: int(minutes)}, nil
}
func (renderer *Renderer) notificationView(data NotificationData) (notificationView, error) {
if !utf8.ValidString(data.Subject) || !utf8.ValidString(data.Body) {
return notificationView{}, invalidData("Renderer.notificationView", "subject and body must be valid UTF-8")
@@ -42,7 +42,7 @@ type TemplateVersion string
// The versions that new renderings use. Changing copy means adding new
// template files with the next version and pointing the constant at them.
const (
currentVerificationVersion TemplateVersion = "verification.v1"
currentVerificationVersion TemplateVersion = "verification.v2"
currentPasswordResetVersion TemplateVersion = "password_reset.v1"
currentNotificationVersion TemplateVersion = "notification.v1"
)
@@ -110,10 +110,10 @@ func NewRenderer(publicOrigin string) (*Renderer, error) {
return &Renderer{origin: origin, templates: templates}, nil
}
// RenderVerification renders the email confirmation message. The link is
// <origin>/verify-email#token=<token>.
// RenderVerification renders the email confirmation message with its six-digit
// code and the link. The link is <origin>/verify-email#token=<token>.
func (renderer *Renderer) RenderVerification(data VerificationData) (RenderedMail, error) {
view, err := renderer.tokenLinkView(verifyEmailPath, data.Token, data.TokenLifetime)
view, err := renderer.verificationCodeView(data)
if err != nil {
return RenderedMail{}, fmt.Errorf("Renderer.RenderVerification - validate data: %w", err)
}
@@ -12,6 +12,7 @@ import (
"strings"
"testing"
"testing/fstest"
"time"
"lincodex/backend/internal/domain"
)
@@ -50,6 +51,21 @@ func testToken(t *testing.T) domain.SecretToken {
return token
}
// testCode is a fixed synthetic code. It is not a credential.
const (
syntheticCode = "482915"
testCodeLifetime = 30 * time.Minute
)
func testCode(t *testing.T) domain.VerificationCode {
t.Helper()
code, err := domain.ParseVerificationCode(syntheticCode)
if err != nil {
t.Fatalf("ParseVerificationCode() error = %v", err)
}
return code
}
func hostileNotification() NotificationData {
return NotificationData{Subject: hostileSubject, Body: hostileBody, LinkPath: "/candidate/invitations"}
}
@@ -58,7 +74,7 @@ func hostileNotification() NotificationData {
func renderAll(t *testing.T, renderer *Renderer) map[Kind]RenderedMail {
t.Helper()
token := testToken(t)
verification, err := renderer.RenderVerification(VerificationData{Token: token, TokenLifetime: 24})
verification, err := renderer.RenderVerification(VerificationData{Token: token, TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime})
if err != nil {
t.Fatalf("RenderVerification() error = %v", err)
}
@@ -102,7 +118,7 @@ func assertGolden(t *testing.T, path, got string) {
func TestRenderingCarriesKindAndVersion(t *testing.T) {
want := map[Kind]TemplateVersion{
KindVerification: "verification.v1",
KindVerification: "verification.v2",
KindPasswordReset: "password_reset.v1",
KindNotification: "notification.v1",
}
@@ -146,7 +162,7 @@ func TestLoopbackOriginKeepsPort(t *testing.T) {
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 24})
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime})
if err != nil {
t.Fatalf("RenderVerification() error = %v", err)
}
@@ -251,18 +267,29 @@ func TestNotificationRejectsLinksOutsideTheApp(t *testing.T) {
func TestRejectsInvalidData(t *testing.T) {
renderer := newTestRenderer(t)
token := testToken(t)
code := testCode(t)
tokenCases := map[string]VerificationData{
"missing token": {TokenLifetime: 24},
"zero lifetime": {Token: token},
"negative": {Token: token, TokenLifetime: -1},
"lifetime too big": {Token: token, TokenLifetime: maxTokenLifetime + 1},
"missing token": {TokenLifetime: 24, Code: code, CodeLifetime: testCodeLifetime},
"zero lifetime": {Token: token, Code: code, CodeLifetime: testCodeLifetime},
"negative": {Token: token, TokenLifetime: -1, Code: code, CodeLifetime: testCodeLifetime},
"lifetime too big": {Token: token, TokenLifetime: maxTokenLifetime + 1, Code: code, CodeLifetime: testCodeLifetime},
"missing code": {Token: token, TokenLifetime: 24, CodeLifetime: testCodeLifetime},
"zero code lifetime": {Token: token, TokenLifetime: 24, Code: code},
"code lifetime seconds": {Token: token, TokenLifetime: 24, Code: code, CodeLifetime: testCodeLifetime + time.Second},
"code lifetime too long": {Token: token, TokenLifetime: 24, Code: code, CodeLifetime: 61 * time.Minute},
}
for name, data := range tokenCases {
if _, err := renderer.RenderVerification(data); !errors.Is(err, ErrInvalidTemplateData) {
t.Fatalf("RenderVerification(%s) error = %v", name, err)
}
reset := PasswordResetData(data)
if _, err := renderer.RenderPasswordReset(reset); !errors.Is(err, ErrInvalidTemplateData) {
}
resetCases := map[string]PasswordResetData{
"missing token": {TokenLifetime: 24},
"zero lifetime": {Token: token},
"negative": {Token: token, TokenLifetime: -1},
}
for name, data := range resetCases {
if _, err := renderer.RenderPasswordReset(data); !errors.Is(err, ErrInvalidTemplateData) {
t.Fatalf("RenderPasswordReset(%s) error = %v", name, err)
}
}
@@ -287,7 +314,7 @@ func TestRejectsInvalidData(t *testing.T) {
func TestLifetimeCopyUsesRussianPlural(t *testing.T) {
renderer := newTestRenderer(t)
for hours, want := range map[domain.Hours]string{1: "1 час.", 3: "3 часа.", 11: "11 часов.", 21: "21 час.", 24: "24 часа.", 48: "48 часов.", 168: "168 часов."} {
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: hours})
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: hours, Code: testCode(t), CodeLifetime: testCodeLifetime})
if err != nil {
t.Fatalf("RenderVerification(%d) error = %v", hours, err)
}
@@ -336,10 +363,10 @@ func TestContentHashPinsTheBody(t *testing.T) {
base Kind
}{
{"token", func() (RenderedMail, error) {
return renderer.RenderVerification(VerificationData{Token: otherToken, TokenLifetime: 24})
return renderer.RenderVerification(VerificationData{Token: otherToken, TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime})
}, KindVerification},
{"lifetime", func() (RenderedMail, error) {
return renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 25})
return renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 25, Code: testCode(t), CodeLifetime: testCodeLifetime})
}, KindVerification},
{"body", func() (RenderedMail, error) {
data := hostileNotification()
@@ -376,7 +403,7 @@ func TestRenderingNeverReachesLogs(t *testing.T) {
slog.New(slog.NewTextHandler(&output, nil)),
slog.New(slog.NewJSONHandler(&output, nil)),
}
verification := VerificationData{Token: token, TokenLifetime: 24}
verification := VerificationData{Token: token, TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime}
notification := hostileNotification()
// RenderedMail hides its content even in an unexported field.
// NotificationData redacts itself only where fmt can call its methods.
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>{{.Subject}}</title>
</head>
<body style="margin:0;padding:0;background-color:#ededed;color:#1b1c21;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:1.5;">
<div style="max-width:560px;margin:0 auto;padding:24px 12px;">
<div style="background-color:#ffffff;border-top:4px solid #402fff;border-radius:8px;padding:28px 24px;">
<p style="margin:0 0 24px;font-size:18px;font-weight:bold;letter-spacing:0.02em;color:#1b1c21;">Lincodex</p>
<h1 style="margin:0 0 16px;font-size:22px;line-height:1.3;color:#1b1c21;">Подтвердите адрес почты</h1>
<p style="margin:0 0 16px;">Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации.</p>
<p style="margin:0 0 8px;font-size:14px;">Код подтверждения:</p>
<p style="margin:0 0 8px;padding:16px;border-radius:6px;background-color:#f3f2ff;color:#1b1c21;font-family:'Courier New',Courier,monospace;font-size:32px;font-weight:bold;letter-spacing:0.3em;text-align:center;">{{.View.Code}}</p>
<p style="margin:0 0 24px;font-size:14px;">Код действует {{.View.CodeLifetimeMinutes}} {{plural .View.CodeLifetimeMinutes "минуту" "минуты" "минут"}}.</p>
<p style="margin:0 0 8px;font-size:14px;">Или откройте ссылку и подтвердите адрес на открывшейся странице:</p>
<p style="margin:0 0 24px;"><a href="{{.View.Link}}" style="display:inline-block;padding:12px 24px;border-radius:6px;background-color:#402fff;color:#ffffff;font-weight:bold;text-decoration:none;">Подтвердить почту</a></p>
<p style="margin:0 0 8px;font-size:14px;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0 0 24px;font-size:14px;word-break:break-all;"><a href="{{.View.Link}}" style="color:#402fff;">{{.View.Link}}</a></p>
<p style="margin:0 0 16px;">Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.</p>
<p style="margin:0;">Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.</p>
</div>
<p style="margin:16px 12px 0;font-size:13px;color:#2d2e37;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</div>
</body>
</html>
@@ -0,0 +1 @@
Подтвердите почту в Lincodex
@@ -0,0 +1,18 @@
Подтвердите адрес почты
Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации:
Код подтверждения: {{.View.Code}}
Код действует {{.View.CodeLifetimeMinutes}} {{plural .View.CodeLifetimeMinutes "минуту" "минуты" "минут"}}.
Или откройте ссылку и подтвердите адрес на открывшейся странице:
{{.View.Link}}
Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.
Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.
--
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -1,14 +0,0 @@
Subject: Подтвердите почту в Lincodex
Подтвердите адрес почты
Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице:
https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv
Ссылка действует 24 часа.
Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.
--
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -11,12 +11,16 @@
<div style="background-color:#ffffff;border-top:4px solid #402fff;border-radius:8px;padding:28px 24px;">
<p style="margin:0 0 24px;font-size:18px;font-weight:bold;letter-spacing:0.02em;color:#1b1c21;">Lincodex</p>
<h1 style="margin:0 0 16px;font-size:22px;line-height:1.3;color:#1b1c21;">Подтвердите адрес почты</h1>
<p style="margin:0 0 24px;">Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице.</p>
<p style="margin:0 0 16px;">Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации.</p>
<p style="margin:0 0 8px;font-size:14px;">Код подтверждения:</p>
<p style="margin:0 0 8px;padding:16px;border-radius:6px;background-color:#f3f2ff;color:#1b1c21;font-family:'Courier New',Courier,monospace;font-size:32px;font-weight:bold;letter-spacing:0.3em;text-align:center;">482915</p>
<p style="margin:0 0 24px;font-size:14px;">Код действует 30 минут.</p>
<p style="margin:0 0 8px;font-size:14px;">Или откройте ссылку и подтвердите адрес на открывшейся странице:</p>
<p style="margin:0 0 24px;"><a href="https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="display:inline-block;padding:12px 24px;border-radius:6px;background-color:#402fff;color:#ffffff;font-weight:bold;text-decoration:none;">Подтвердить почту</a></p>
<p style="margin:0 0 8px;font-size:14px;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0 0 24px;font-size:14px;word-break:break-all;"><a href="https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="color:#402fff;">https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv</a></p>
<p style="margin:0 0 16px;">Ссылка действует 24 часа.</p>
<p style="margin:0;">Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.</p>
<p style="margin:0;">Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.</p>
</div>
<p style="margin:16px 12px 0;font-size:13px;color:#2d2e37;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</div>
@@ -0,0 +1,20 @@
Subject: Подтвердите почту в Lincodex
Подтвердите адрес почты
Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации:
Код подтверждения: 482915
Код действует 30 минут.
Или откройте ссылку и подтвердите адрес на открывшейся странице:
https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv
Ссылка действует 24 часа.
Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.
--
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -29,6 +29,11 @@ type TokenMailRequest struct {
// Lifetime is the validity of the token that the message states, in
// whole hours.
Lifetime domain.Hours
// Code is the six-digit code of an email verification message, and
// CodeLifetime its validity as the message states it. Both are required
// for email verification and unused by the other kinds.
Code domain.VerificationCode
CodeLifetime time.Duration
}
// ServiceMailer stores service mail of the account flows (email verification
@@ -65,7 +70,15 @@ func (mailer *ServiceMailer) EnqueueVerification(ctx context.Context, unit outbo
if err := checkTokenMailRequest(location, request, domain.EmailTokenPurposeEmailVerification); err != nil {
return uuid.Nil, err
}
content, err := mailer.renderer.RenderVerification(mailtemplate.VerificationData{Token: request.RawToken, TokenLifetime: request.Lifetime})
if request.Code.IsZero() {
return uuid.Nil, fmt.Errorf("%s - verification code must be set: %w", location, domain.ErrInvalidEmailToken)
}
content, err := mailer.renderer.RenderVerification(mailtemplate.VerificationData{
Token: request.RawToken,
TokenLifetime: request.Lifetime,
Code: request.Code,
CodeLifetime: request.CodeLifetime,
})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - render message: %w", location, err)
}
@@ -47,7 +47,14 @@ func (h *serviceMailHarness) request(t *testing.T, purpose domain.EmailTokenPurp
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
return TokenMailRequest{Recipient: recipient, Token: token, RawToken: raw, Lifetime: 24}
code, err := domain.NewVerificationCode()
if err != nil {
t.Fatalf("NewVerificationCode() error = %v", err)
}
return TokenMailRequest{
Recipient: recipient, Token: token, RawToken: raw, Lifetime: 24,
Code: code, CodeLifetime: domain.VerificationCodeLifetime,
}
}
func TestServiceMailerStoresATokenBoundDeliveryUnderTheTokenID(t *testing.T) {
@@ -125,6 +132,8 @@ func TestServiceMailerRefusesAWrongTokenBeforeRendering(t *testing.T) {
"no recipient": func(request *TokenMailRequest) { request.Recipient = domain.EmailAddress{} },
"zero lifetime": func(request *TokenMailRequest) { request.Lifetime = 0 },
"lifetime >7d": func(request *TokenMailRequest) { request.Lifetime = 24 * 8 },
"no code": func(request *TokenMailRequest) { request.Code = domain.VerificationCode{} },
"code lifetime": func(request *TokenMailRequest) { request.CodeLifetime = 90 * time.Second },
} {
request := h.request(t, domain.EmailTokenPurposeEmailVerification)
change(&request)