Files

364 lines
16 KiB
Go

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