207 lines
7.6 KiB
Go
207 lines
7.6 KiB
Go
package httpadapter
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"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/usecase/identity"
|
|
)
|
|
|
|
const resendPath = "/api/v1/identity/email-verification-requests"
|
|
|
|
// scriptedRegistration answers every call with its fixed error and records
|
|
// the last commands.
|
|
type scriptedRegistration struct {
|
|
err error
|
|
register identity.RegisterCommand
|
|
resend identity.ResendCommand
|
|
calls int
|
|
}
|
|
|
|
func (registration *scriptedRegistration) Register(_ context.Context, command identity.RegisterCommand) error {
|
|
registration.calls++
|
|
registration.register = command
|
|
return registration.err
|
|
}
|
|
|
|
func (registration *scriptedRegistration) ResendVerification(_ context.Context, command identity.ResendCommand) error {
|
|
registration.calls++
|
|
registration.resend = command
|
|
return registration.err
|
|
}
|
|
|
|
const identityTestOrigin = "https://app.example"
|
|
|
|
func newIdentityRouter(t *testing.T, registration v1.AccountRegistration) http.Handler {
|
|
t.Helper()
|
|
logger := slog.New(slog.DiscardHandler)
|
|
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
|
identityHandler := v1.NewIdentityHandler(registration, v1.WithPublicOrigin(identityTestOrigin))
|
|
handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(identityHandler))
|
|
return newTestRouterWithAPI(t, healthHandler, handler, logger)
|
|
}
|
|
|
|
func TestRegistrationOperationsMapUsecaseOutcomes(t *testing.T) {
|
|
registerRequest := identityRequest{
|
|
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
|
|
headers: map[string]string{"Idempotency-Key": testIdempotencyKey, "Origin": identityTestOrigin},
|
|
}
|
|
resendRequest := identityRequest{
|
|
method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`,
|
|
headers: map[string]string{"Origin": identityTestOrigin},
|
|
}
|
|
staleConsent := &identity.InvalidFieldError{Pointer: "/consent_c1/text_version", Err: errors.New("stale")}
|
|
for _, test := range []struct {
|
|
name string
|
|
request identityRequest
|
|
err error
|
|
statusCode int
|
|
code api.ProblemCode
|
|
pointer string
|
|
retryAfter string
|
|
}{
|
|
{name: "register accepted", request: registerRequest, statusCode: http.StatusAccepted},
|
|
{name: "resend accepted", request: resendRequest, statusCode: http.StatusAccepted},
|
|
{
|
|
name: "register stale consent version", request: registerRequest, err: staleConsent,
|
|
statusCode: http.StatusBadRequest, code: api.ProblemCodeValidationFailed, pointer: "/consent_c1/text_version",
|
|
},
|
|
{
|
|
name: "register reused key", request: registerRequest, err: identity.ErrIdempotencyKeyReused,
|
|
statusCode: http.StatusUnprocessableEntity, code: api.ProblemCodeIdempotencyKeyReused,
|
|
},
|
|
{
|
|
name: "register limited", request: registerRequest, err: &identity.RateLimitedError{RetryAfter: 1500 * time.Millisecond},
|
|
statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "2",
|
|
},
|
|
{
|
|
name: "resend limited", request: resendRequest, err: &identity.RateLimitedError{RetryAfter: 59 * time.Second},
|
|
statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "59",
|
|
},
|
|
{
|
|
name: "resend internal failure", request: resendRequest, err: errors.New("database unavailable"),
|
|
statusCode: http.StatusInternalServerError, code: api.ProblemCodeInternal,
|
|
},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
response := serveIdentityRequest(t, newIdentityRouter(t, &scriptedRegistration{err: test.err}), test.request)
|
|
if test.statusCode == http.StatusAccepted {
|
|
if response.Code != http.StatusAccepted || response.Body.String() != `{"status":"accepted"}` {
|
|
t.Fatalf("response = %d %s, want the neutral 202", response.Code, response.Body.String())
|
|
}
|
|
return
|
|
}
|
|
body := requireProblem(t, response, test.statusCode, test.code)
|
|
if test.pointer != "" && (len(body.Errors) != 1 || body.Errors[0].Pointer != test.pointer) {
|
|
t.Fatalf("errors = %v, want one error at %s", body.Errors, test.pointer)
|
|
}
|
|
if got := response.Header().Get("Retry-After"); got != test.retryAfter {
|
|
t.Fatalf("Retry-After = %q, want %q", got, test.retryAfter)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRegistrationPassesTheRequestToTheUsecase(t *testing.T) {
|
|
registration := &scriptedRegistration{}
|
|
router := newIdentityRouter(t, registration)
|
|
response := serveIdentityRequest(t, router, identityRequest{
|
|
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
|
|
headers: map[string]string{"Idempotency-Key": testIdempotencyKey, "Origin": identityTestOrigin},
|
|
})
|
|
if response.Code != http.StatusAccepted {
|
|
t.Fatalf("status = %d: %s", response.Code, response.Body.String())
|
|
}
|
|
want := identity.RegisterCommand{
|
|
IdempotencyKey: testIdempotencyKey, Email: "candidate@example.com", Password: validPassword,
|
|
Scenario: "candidate", ConsentTextVersion: "c1-2026-10-01", ClientKey: "192.0.2.1",
|
|
}
|
|
if registration.register != want {
|
|
t.Fatalf("command = %+v, want %+v", registration.register, want)
|
|
}
|
|
}
|
|
|
|
func TestRegistrationAndResendRejectOriginBeforeUsecase(t *testing.T) {
|
|
for _, operation := range []struct {
|
|
name string
|
|
request identityRequest
|
|
}{
|
|
{
|
|
name: "register",
|
|
request: identityRequest{
|
|
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
|
|
headers: map[string]string{"Idempotency-Key": testIdempotencyKey},
|
|
},
|
|
},
|
|
{
|
|
name: "resend",
|
|
request: identityRequest{method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`},
|
|
},
|
|
} {
|
|
for _, originCase := range []struct {
|
|
name string
|
|
origins []string
|
|
headers map[string]string
|
|
}{
|
|
{name: "missing"},
|
|
{name: "null origin", origins: []string{"null"}},
|
|
{name: "foreign origin", origins: []string{"https://attacker.example"}},
|
|
{name: "duplicate origin", origins: []string{identityTestOrigin, "https://attacker.example"}},
|
|
{name: "forwarded host only", headers: map[string]string{"X-Forwarded-Host": "app.example"}},
|
|
} {
|
|
t.Run(operation.name+"/"+originCase.name, func(t *testing.T) {
|
|
registration := &scriptedRegistration{}
|
|
request := operation.request
|
|
request.headers = cloneHeaders(request.headers)
|
|
for name, value := range originCase.headers {
|
|
request.headers[name] = value
|
|
}
|
|
response := serveIdentityRequestWithOrigins(t, newIdentityRouter(t, registration), request, originCase.origins)
|
|
requireProblem(t, response, http.StatusForbidden, api.ProblemCodeCsrfCheckFailed)
|
|
if registration.calls != 0 {
|
|
t.Fatalf("identity usecase calls = %d, want zero before origin check", registration.calls)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func serveIdentityRequestWithOrigins(
|
|
t *testing.T,
|
|
router http.Handler,
|
|
identityRequest identityRequest,
|
|
origins []string,
|
|
) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
request := httptest.NewRequest(identityRequest.method, identityRequest.path, strings.NewReader(identityRequest.body))
|
|
if identityRequest.body != "" {
|
|
request.Header.Set("Content-Type", "application/json")
|
|
}
|
|
for name, value := range identityRequest.headers {
|
|
request.Header.Set(name, value)
|
|
}
|
|
for _, origin := range origins {
|
|
request.Header.Add("Origin", origin)
|
|
}
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, request)
|
|
return response
|
|
}
|
|
|
|
func cloneHeaders(headers map[string]string) map[string]string {
|
|
cloned := make(map[string]string, len(headers))
|
|
for name, value := range headers {
|
|
cloned[name] = value
|
|
}
|
|
return cloned
|
|
}
|