Files
lincodex/backend/internal/adapter/primary/http/identity_code_confirmation_test.go

155 lines
6.4 KiB
Go

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")
}
}