feat(identity): confirm registration email atomically

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 09:12:15 +03:00
1 parent 8e7ce8d71c
commit fade4e76e4
75 files changed
+4188 -403

No files matched your search

@@ -0,0 +1,168 @@
package httpadapter
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"strings"
"testing"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/identity"
)
const confirmationPath = "/api/v1/identity/email-verifications"
type scriptedConfirmation struct {
err error
command identity.ConfirmCommand
result identity.ConfirmationResult
calls int
}
func (confirmation *scriptedConfirmation) Confirm(_ context.Context, command identity.ConfirmCommand) (identity.ConfirmationResult, error) {
confirmation.calls++
confirmation.command = command
return confirmation.result, confirmation.err
}
func newConfirmationRouter(t *testing.T, confirmation v1.EmailConfirmation) http.Handler {
t.Helper()
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
identityHandler := v1.NewIdentityHandler(nil, v1.WithEmailConfirmation(confirmation, "https://app.example"))
handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(identityHandler))
return newTestRouterWithAPI(t, healthHandler, handler, logger)
}
func TestConfirmEmailRequiresConfiguredOriginBeforeUsecase(t *testing.T) {
confirmation := &scriptedConfirmation{}
router := newConfirmationRouter(t, confirmation)
body := `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`
for _, test := range []struct {
name string
origin string
set bool
}{
{name: "missing"},
{name: "null", origin: "null", set: true},
{name: "foreign", origin: "https://foreign.example", set: true},
{name: "same host with different port", origin: "https://app.example:443", set: true},
} {
t.Run(test.name, func(t *testing.T) {
before := confirmation.calls
headers := map[string]string{}
if test.set {
headers["Origin"] = test.origin
}
response := serveIdentityRequest(t, router, identityRequest{
method: http.MethodPost, path: confirmationPath, body: body, headers: headers,
})
requireProblem(t, response, http.StatusForbidden, api.ProblemCodeCsrfCheckFailed)
if confirmation.calls != before {
t.Fatal("confirmation usecase ran before the origin check")
}
})
}
}
func TestConfirmEmailPassesRequestAndReturnsSavedDestination(t *testing.T) {
confirmation := &scriptedConfirmation{result: identity.ConfirmationResult{
Scenario: domain.ScenarioCandidate,
OnboardingStep: domain.OnboardingStepCandidateProfile,
}}
router := newConfirmationRouter(t, confirmation)
token := strings.Repeat("A", 64)
password := `correct "quoted" horse battery staple`
requestBody, err := json.Marshal(struct {
Token string `json:"token"`
Password string `json:"password"`
}{Token: token, Password: password})
if err != nil {
t.Fatal(err)
}
response := serveIdentityRequest(t, router, identityRequest{
method: http.MethodPost,
path: confirmationPath,
body: string(requestBody),
headers: map[string]string{"Origin": "https://app.example"},
})
if response.Code != http.StatusOK || response.Header().Get("Set-Cookie") != "" {
t.Fatalf("response = %d, Set-Cookie %q, body %s", response.Code, response.Header().Get("Set-Cookie"), response.Body.String())
}
var result map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
t.Fatalf("decode response: %v", err)
}
if result["email_verified"] != true || result["scenario"] != "candidate" || result["onboarding_step"] != "candidate_profile" {
t.Fatalf("response body = %v", result)
}
if confirmation.calls != 1 || confirmation.command.Token != token || confirmation.command.Password != password || confirmation.command.ClientKey == "" {
t.Fatalf("confirmation call = %d, command %+v", confirmation.calls, confirmation.command)
}
}
func TestConfirmEmailRequiresPassword(t *testing.T) {
confirmation := &scriptedConfirmation{}
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
method: http.MethodPost,
path: confirmationPath,
body: `{"token":"` + strings.Repeat("A", 64) + `"}`,
headers: map[string]string{"Origin": "https://app.example"},
})
requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
if confirmation.calls != 0 {
t.Fatal("confirmation usecase ran without the required registration password")
}
}
func TestConfirmEmailMapsExpectedUsecaseFailures(t *testing.T) {
for _, test := range []struct {
name string
err error
statusCode int
code api.ProblemCode
retryAfter string
}{
{name: "invalid token", err: identity.ErrVerificationTokenInvalid, statusCode: http.StatusBadRequest, code: api.ProblemCodeVerificationTokenInvalid},
{name: "expired token", err: identity.ErrVerificationTokenExpired, statusCode: http.StatusBadRequest, code: api.ProblemCodeVerificationTokenExpired},
{name: "limited", err: &identity.RateLimitedError{RetryAfter: 1500 * time.Millisecond}, statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "2"},
} {
t.Run(test.name, func(t *testing.T) {
confirmation := &scriptedConfirmation{err: test.err}
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
method: http.MethodPost,
path: confirmationPath,
body: `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`,
headers: map[string]string{"Origin": "https://app.example"},
})
requireProblem(t, response, test.statusCode, test.code)
if got := response.Header().Get("Retry-After"); got != test.retryAfter {
t.Fatalf("Retry-After = %q, want %q", got, test.retryAfter)
}
if confirmation.calls != 1 {
t.Fatalf("confirmation calls = %d, want 1", confirmation.calls)
}
})
}
}
func TestConfirmEmailDoesNotConvertUnexpectedUsecaseErrors(t *testing.T) {
confirmation := &scriptedConfirmation{err: errors.New("storage unavailable")}
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
method: http.MethodPost,
path: confirmationPath,
body: `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`,
headers: map[string]string{"Origin": "https://app.example"},
})
requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
if strings.Contains(response.Body.String(), "storage unavailable") {
t.Fatal("internal error text leaked into the response")
}
}