Files
lincodex/backend/integration_test/email_verification_test.go
T

681 lines
33 KiB
Go

//go:build integration
package integration_test
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"mime"
"net/http"
"strconv"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
)
const (
confirmationTestTimeout = 5 * time.Minute
confirmationRetryWindow = time.Hour
confirmationSecondPassword = "another correct horse battery staple"
confirmationWrongPassword = "this is the wrong password"
confirmationUnknownToken = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
confirmationFailureFunction = "integration_reject_email_confirmation"
confirmationFailureTrigger = "integration_reject_email_confirmation_event"
)
type confirmationState struct {
scenario string
onboardingStep string
passwordHash string
emailVerifiedAt *time.Time
registrationVersion int64
userVersion int64
tokenRegistrationVersion int64
tokenConsumedAt *time.Time
tokenInvalidatedAt *time.Time
pendingPasswordHash *string
pendingScenario *string
pendingOnboardingStep *string
c1RegistrationVersion *int64
tokenCount int
sessionCount int
confirmationEventCount int
}
func TestEmailVerificationOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), confirmationTestTimeout)
defer cancel()
harness := newRegistrationHarness(ctx, t, env, 1000)
reset := func(t *testing.T) {
t.Helper()
harness.truncate(ctx, t)
harness.clock.Set(harness.start)
}
publicOrigin := env.Config.AppPublicURL
t.Run("a candidate and employer confirm the registration received by mail", func(t *testing.T) {
for _, test := range []struct {
name string
email string
scenario string
step string
}{
{name: "candidate", email: "confirm.candidate@example.com", scenario: "candidate", step: "candidate_consents"},
{name: "employer", email: "confirm.employer@example.com", scenario: "employer", step: "employer_company"},
} {
t.Run(test.name, func(t *testing.T) {
reset(t)
token := harness.registerAndSendVerification(ctx, t, test.email, test.scenario, registrationPassword)
before := readConfirmationState(ctx, t, harness, test.email, token)
if before.pendingPasswordHash == nil || before.c1RegistrationVersion == nil ||
*before.c1RegistrationVersion != before.tokenRegistrationVersion {
t.Fatal("registration did not bind its C1 record and pending password to the emailed token")
}
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireConfirmationSuccess(t, response, test.scenario, test.step)
after := readConfirmationState(ctx, t, harness, test.email, token)
assertConfirmationApplied(t, before, after, test.scenario, test.step)
assertSingleConfirmationEvent(ctx, t, harness, test.email)
if after.sessionCount != 0 {
t.Fatalf("confirmation created %d sessions, want none", after.sessionCount)
}
harness.assertLogsHoldNoSecrets(t, test.email, registrationPassword, token)
// A consumed link cannot be replayed and leaves the committed account alone.
replay := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, replay, http.StatusBadRequest, "verification_token_invalid")
if replay.setCookie != "" || !sameConfirmationState(after, readConfirmationState(ctx, t, harness, test.email, token)) {
t.Fatal("replaying a consumed token changed the account or set a cookie")
}
})
}
})
t.Run("an unknown token is refused without creating identity state", func(t *testing.T) {
reset(t)
response := harness.confirm(t, confirmationUnknownToken, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.retryAfter != "" || response.setCookie != "" ||
harness.count(ctx, t, `SELECT count(*) FROM users`) != 0 ||
harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) != 0 ||
harness.count(ctx, t, `SELECT count(*) FROM sessions`) != 0 ||
harness.count(ctx, t, `SELECT count(*) FROM outbox_events WHERE event_type = 'identity.email_verified'`) != 0 {
t.Fatal("an unknown token changed identity state or returned rate-limit/session headers")
}
harness.assertLogsHoldNoSecrets(t, confirmationUnknownToken, registrationPassword)
})
t.Run("an expired token remains unconsumed", func(t *testing.T) {
reset(t)
const email = "confirm.expired@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
expiresAt := tokenExpiresAt(ctx, t, harness, token)
harness.clock.Set(expiresAt.Add(time.Second))
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_expired")
if response.retryAfter != "" || response.setCookie != "" ||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("an expired token changed the account or returned rate-limit/session headers")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("an expired active token from an earlier registration version is invalid", func(t *testing.T) {
reset(t)
const email = "confirm.stale-active-version@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
hash := sha256.Sum256([]byte(token))
deadline := harness.clock.Now().Add(time.Second)
harness.exec(ctx, t, `UPDATE email_tokens SET expires_at = $1 WHERE token_hash = $2`, deadline, hash[:])
harness.clock.Set(deadline.Add(time.Second))
harness.exec(ctx, t, `UPDATE users SET registration_version = registration_version + 1, version = version + 1, updated_at = $1 WHERE email_normalized = $2`,
harness.clock.Now(), strings.ToLower(email))
before := readConfirmationState(ctx, t, harness, email, token)
if before.tokenInvalidatedAt != nil || before.pendingPasswordHash == nil ||
before.registrationVersion == before.tokenRegistrationVersion || !deadline.Before(harness.clock.Now()) {
t.Fatal("fixture does not contain an expired, active token for an earlier account version")
}
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.retryAfter != "" || response.setCookie != "" ||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("an expired active token from an earlier account version changed identity state")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("expiry is checked after confirmation waits for token, consent, or user locks", func(t *testing.T) {
for _, target := range []struct {
name string
query string
}{
{name: "token", query: `SELECT 1 FROM email_tokens WHERE token_hash = $1 FOR UPDATE`},
{name: "registration consent", query: `
SELECT 1 FROM consent_records AS consent
JOIN users AS account ON account.id = consent.subject_id
WHERE account.email_normalized = $1 AND consent.purpose = 'c1'
AND consent.source = 'registration' AND consent.revoked_at IS NULL
FOR UPDATE OF consent`},
{name: "user", query: `SELECT 1 FROM users WHERE email_normalized = $1 FOR UPDATE`},
} {
t.Run(target.name, func(t *testing.T) {
reset(t)
email := "confirm.lock-expiry-" + strings.ReplaceAll(target.name, " ", "-") + "@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
expiresAt := tokenExpiresAt(ctx, t, harness, token)
monitorPool := env.newPool(ctx, t)
holder, err := harness.pool.Begin(ctx)
if err != nil {
t.Fatalf("begin %s lock: %v", target.name, err)
}
defer func() {
if err := holder.Rollback(context.WithoutCancel(ctx)); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
t.Errorf("release %s lock: %v", target.name, err)
}
}()
var lockKey any = strings.ToLower(email)
if target.name == "token" {
hash := sha256.Sum256([]byte(token))
lockKey = hash[:]
}
var locked int
if err := holder.QueryRow(ctx, target.query, lockKey).Scan(&locked); err != nil {
t.Fatalf("lock the emailed %s row: %v", target.name, err)
}
type confirmationReply struct{ response registrationResponse }
reply := make(chan confirmationReply, 1)
go func() {
reply <- confirmationReply{response: harness.confirm(t, token, registrationPassword, &publicOrigin)}
}()
waitEvent, observed := waitForLockWait(ctx, monitorPool, registrationApplication)
if !observed {
_ = holder.Rollback(context.WithoutCancel(ctx))
<-reply
t.Fatalf("confirmation did not wait on the %s row lock (last wait event %q)", target.name, waitEvent)
}
harness.clock.Set(expiresAt.Add(time.Second))
if err := holder.Commit(ctx); err != nil {
t.Fatalf("release the %s lock: %v", target.name, err)
}
response := (<-reply).response
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_expired")
if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatalf("a request queued on the %s lock consumed the token after its deadline", target.name)
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
}
})
t.Run("missing, null, and foreign Origin values are rejected without consuming the token", func(t *testing.T) {
reset(t)
const email = "confirm.origin@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
for _, test := range []struct {
name string
origin *string
}{
{name: "missing"},
{name: "null", origin: stringPointer("null")},
{name: "foreign", origin: stringPointer("https://foreign.example")},
} {
t.Run(test.name, func(t *testing.T) {
response := harness.confirm(t, token, registrationPassword, test.origin)
requireProblemStatus(t, response, http.StatusForbidden, "csrf_check_failed")
if response.retryAfter != "" || response.setCookie != "" ||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("an invalid Origin changed the account or returned rate-limit/session headers")
}
})
}
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireConfirmationSuccess(t, response, "candidate", "candidate_consents")
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("the second registrant confirms only with its own password and token", func(t *testing.T) {
reset(t)
const email = "confirm.replaced@example.com"
firstToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
firstHash := sha256.Sum256([]byte(firstToken))
firstDeadline := harness.clock.Now().Add(time.Second)
harness.exec(ctx, t, `UPDATE email_tokens SET expires_at = $1 WHERE token_hash = $2`, firstDeadline, firstHash[:])
harness.clock.Set(firstDeadline.Add(time.Second))
time.Sleep(registrationMinInterval + 100*time.Millisecond)
secondToken := harness.registerAndSendVerification(ctx, t, email, "employer", confirmationSecondPassword)
oldBefore := readConfirmationState(ctx, t, harness, email, firstToken)
if oldBefore.tokenInvalidatedAt == nil || oldBefore.pendingPasswordHash != nil {
t.Fatal("re-registration did not invalidate the old token and clear its pending credentials")
}
old := harness.confirm(t, firstToken, registrationPassword, &publicOrigin)
requireProblemStatus(t, old, http.StatusBadRequest, "verification_token_invalid")
if !sameConfirmationState(oldBefore, readConfirmationState(ctx, t, harness, email, firstToken)) {
t.Fatal("an expired token from a replaced registration changed account or token rows")
}
currentBefore := readConfirmationState(ctx, t, harness, email, secondToken)
wrong := harness.confirm(t, secondToken, registrationPassword, &publicOrigin)
requireProblemStatus(t, wrong, http.StatusBadRequest, "verification_token_invalid")
if !sameConfirmationState(currentBefore, readConfirmationState(ctx, t, harness, email, secondToken)) {
t.Fatal("a wrong password consumed the current token or changed the account")
}
accepted := harness.confirm(t, secondToken, confirmationSecondPassword, &publicOrigin)
requireConfirmationSuccess(t, accepted, "employer", "employer_company")
after := readConfirmationState(ctx, t, harness, email, secondToken)
assertConfirmationApplied(t, currentBefore, after, "employer", "employer_company")
assertSingleConfirmationEvent(ctx, t, harness, email)
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationSecondPassword, firstToken, secondToken)
})
t.Run("the original registrant can replace a second registrant before confirmation", func(t *testing.T) {
reset(t)
const email = "confirm.owner-first@example.com"
firstToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
time.Sleep(registrationMinInterval + 100*time.Millisecond)
secondToken := harness.registerAndSendVerification(ctx, t, email, "employer", confirmationSecondPassword)
firstAfterReplacement := readConfirmationState(ctx, t, harness, email, firstToken)
if firstAfterReplacement.tokenInvalidatedAt == nil || firstAfterReplacement.pendingPasswordHash != nil {
t.Fatal("the second registration did not invalidate the original token and clear its pending credentials")
}
old := harness.confirm(t, firstToken, registrationPassword, &publicOrigin)
requireProblemStatus(t, old, http.StatusBadRequest, "verification_token_invalid")
if !sameConfirmationState(firstAfterReplacement, readConfirmationState(ctx, t, harness, email, firstToken)) {
t.Fatal("the original registrant's replaced token changed account or token rows")
}
secondBefore := readConfirmationState(ctx, t, harness, email, secondToken)
wrong := harness.confirm(t, secondToken, registrationPassword, &publicOrigin)
requireProblemStatus(t, wrong, http.StatusBadRequest, "verification_token_invalid")
if !sameConfirmationState(secondBefore, readConfirmationState(ctx, t, harness, email, secondToken)) {
t.Fatal("the original password consumed the second registrant's token or changed the account")
}
time.Sleep(registrationMinInterval + 100*time.Millisecond)
harness.clock.Advance(registrationMinInterval + time.Second)
thirdToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
secondAfterReplacement := readConfirmationState(ctx, t, harness, email, secondToken)
if secondAfterReplacement.tokenInvalidatedAt == nil || secondAfterReplacement.pendingPasswordHash != nil {
t.Fatal("the original registrant's new registration did not invalidate the second token")
}
superseded := harness.confirm(t, secondToken, confirmationSecondPassword, &publicOrigin)
requireProblemStatus(t, superseded, http.StatusBadRequest, "verification_token_invalid")
if !sameConfirmationState(secondAfterReplacement, readConfirmationState(ctx, t, harness, email, secondToken)) {
t.Fatal("confirming the superseded second registration changed account or token rows")
}
thirdBefore := readConfirmationState(ctx, t, harness, email, thirdToken)
accepted := harness.confirm(t, thirdToken, registrationPassword, &publicOrigin)
requireConfirmationSuccess(t, accepted, "candidate", "candidate_consents")
after := readConfirmationState(ctx, t, harness, email, thirdToken)
assertConfirmationApplied(t, thirdBefore, after, "candidate", "candidate_consents")
assertSingleConfirmationEvent(ctx, t, harness, email)
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationSecondPassword, firstToken, secondToken, thirdToken)
})
t.Run("a confirmed registration stays current if another registration follows", func(t *testing.T) {
reset(t)
const email = "confirm.before-reregistration@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireConfirmationSuccess(t, response, "candidate", "candidate_consents")
confirmed := readConfirmationState(ctx, t, harness, email, token)
assertConfirmationApplied(t, before, confirmed, "candidate", "candidate_consents")
time.Sleep(registrationMinInterval + 100*time.Millisecond)
registrationResponse := harness.registerBody(t, registrationBody(email, "employer", confirmationSecondPassword, registrationC1), "")
requireAccepted(t, registrationResponse)
if registrationResponse.setCookie != "" || !sameConfirmationState(confirmed, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a registration after confirmation changed the verified account")
}
assertSingleConfirmationEvent(ctx, t, harness, email)
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token, confirmationSecondPassword)
})
t.Run("a token cannot use the C1 record of another registration version", func(t *testing.T) {
reset(t)
const email = "confirm.c1-version@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
if before.c1RegistrationVersion == nil || *before.c1RegistrationVersion != before.tokenRegistrationVersion {
t.Fatal("initial C1 record is not bound to the token registration version")
}
hash := sha256.Sum256([]byte(token))
harness.exec(ctx, t, `UPDATE users SET registration_version = registration_version + 1, version = version + 1, updated_at = $1 WHERE email_normalized = $2`,
harness.clock.Now().Add(time.Second), strings.ToLower(email))
harness.exec(ctx, t, `UPDATE email_tokens SET registration_version = registration_version + 1 WHERE token_hash = $1`, hash[:])
stale := readConfirmationState(ctx, t, harness, email, token)
if stale.registrationVersion != stale.tokenRegistrationVersion || stale.c1RegistrationVersion == nil ||
*stale.c1RegistrationVersion == stale.tokenRegistrationVersion {
t.Fatal("fixture did not create a token and account version newer than its C1 record")
}
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.setCookie != "" || !sameConfirmationState(stale, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a token without current-version C1 changed the account or token")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("a token without pending registration credentials cannot be confirmed", func(t *testing.T) {
reset(t)
const email = "confirm.no-pending@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
hash := sha256.Sum256([]byte(token))
harness.exec(ctx, t, `UPDATE email_tokens SET pending_password_hash = NULL, pending_scenario = NULL, pending_onboarding_step = NULL WHERE token_hash = $1`, hash[:])
before := readConfirmationState(ctx, t, harness, email, token)
if before.pendingPasswordHash != nil || before.pendingScenario != nil || before.pendingOnboardingStep != nil {
t.Fatal("test token still has pending registration data")
}
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a token without pending registration data changed the account or token")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("confirmation rate limits refusals and reports Retry-After", func(t *testing.T) {
reset(t)
const email = "confirm.rate-limit@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
for range 2 {
response := harness.confirm(t, token, confirmationWrongPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.retryAfter != "" || response.setCookie != "" ||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a refused password attempt changed identity state or returned rate-limit/session headers")
}
}
limited := harness.confirm(t, token, confirmationWrongPassword, &publicOrigin)
requireProblemStatus(t, limited, http.StatusTooManyRequests, "rate_limited")
requirePositiveRetryAfter(t, limited)
if limited.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a rate-limited confirmation changed identity state or set a cookie")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationWrongPassword, token)
})
t.Run("an outbox failure rolls back token consumption and account confirmation", func(t *testing.T) {
reset(t)
const email = "confirm.rollback@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
installConfirmationOutboxFailure(ctx, t, harness)
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusInternalServerError, "internal")
if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a failed confirmation outbox insert did not roll back all account and token changes")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("two concurrent HTTP confirmations produce one success and one event", func(t *testing.T) {
reset(t)
const email = "confirm.concurrent@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
responses := make([]registrationResponse, 2)
start := make(chan struct{})
finished := make(chan int, len(responses))
for index := range responses {
go func(index int) {
<-start
responses[index] = harness.confirm(t, token, registrationPassword, &publicOrigin)
finished <- index
}(index)
}
close(start)
<-finished
<-finished
successes := 0
refusals := 0
for _, response := range responses {
switch response.status {
case http.StatusOK:
successes++
requireConfirmationSuccess(t, response, "candidate", "candidate_consents")
case http.StatusBadRequest:
refusals++
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
default:
t.Fatalf("concurrent confirmation returned status %d, want one success and one invalid-token refusal", response.status)
}
if response.setCookie != "" {
t.Fatal("confirmation set a cookie")
}
}
if successes != 1 || refusals != 1 {
t.Fatalf("concurrent confirmations had %d successes and %d refusals, want one each", successes, refusals)
}
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("concurrent confirmation created %d sessions, want none", after.sessionCount)
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
}
func (harness *registrationHarness) confirm(t *testing.T, token, password string, origin *string) registrationResponse {
t.Helper()
headers := make(map[string]string)
if origin != nil {
headers["Origin"] = *origin
}
body, err := json.Marshal(struct {
Token string `json:"token"`
Password string `json:"password"`
}{Token: token, Password: password})
if err != nil {
t.Fatalf("encode confirmation request: %v", err)
}
if origin == nil {
return harness.postWithoutDefaultOrigin(t, emailVerificationPath, string(body), headers)
}
return harness.post(t, emailVerificationPath, string(body), headers)
}
func readConfirmationState(ctx context.Context, t *testing.T, harness *registrationHarness, email, rawToken string) confirmationState {
t.Helper()
hash := sha256.Sum256([]byte(rawToken))
var state confirmationState
err := harness.pool.QueryRow(ctx, `
SELECT account.scenario, account.onboarding_step, account.password_hash,
account.email_verified_at, account.registration_version, account.version,
token.registration_version, token.consumed_at, token.invalidated_at,
token.pending_password_hash, token.pending_scenario, token.pending_onboarding_step,
consent.registration_version,
(SELECT count(*)::integer FROM email_tokens WHERE user_id = account.id),
(SELECT count(*)::integer FROM sessions WHERE user_id = account.id),
(SELECT count(*)::integer FROM outbox_events
WHERE aggregate_id = account.id AND event_type = 'identity.email_verified')
FROM users AS account
JOIN email_tokens AS token ON token.user_id = account.id AND token.token_hash = $1
LEFT JOIN LATERAL (
SELECT registration_version FROM consent_records
WHERE subject_id = account.id AND purpose = 'c1' AND source = 'registration' AND revoked_at IS NULL
ORDER BY granted_at DESC, id DESC LIMIT 1
) AS consent ON TRUE
WHERE account.email_normalized = $2`, hash[:], strings.ToLower(email)).Scan(
&state.scenario, &state.onboardingStep, &state.passwordHash,
&state.emailVerifiedAt, &state.registrationVersion, &state.userVersion,
&state.tokenRegistrationVersion, &state.tokenConsumedAt, &state.tokenInvalidatedAt,
&state.pendingPasswordHash, &state.pendingScenario, &state.pendingOnboardingStep,
&state.c1RegistrationVersion, &state.tokenCount, &state.sessionCount, &state.confirmationEventCount,
)
if err != nil {
t.Fatalf("read confirmation state: %v", err)
}
return state
}
func tokenExpiresAt(ctx context.Context, t *testing.T, harness *registrationHarness, rawToken string) time.Time {
t.Helper()
hash := sha256.Sum256([]byte(rawToken))
var expiresAt time.Time
if err := harness.pool.QueryRow(ctx, `SELECT expires_at FROM email_tokens WHERE token_hash = $1`, hash[:]).Scan(&expiresAt); err != nil {
t.Fatalf("read emailed token deadline: %v", err)
}
return expiresAt
}
func sameConfirmationState(left, right confirmationState) bool {
return left.scenario == right.scenario && left.onboardingStep == right.onboardingStep &&
left.passwordHash == right.passwordHash && sameOptionalTime(left.emailVerifiedAt, right.emailVerifiedAt) &&
left.registrationVersion == right.registrationVersion && left.userVersion == right.userVersion &&
left.tokenRegistrationVersion == right.tokenRegistrationVersion &&
sameOptionalTime(left.tokenConsumedAt, right.tokenConsumedAt) &&
sameOptionalTime(left.tokenInvalidatedAt, right.tokenInvalidatedAt) &&
sameOptionalString(left.pendingPasswordHash, right.pendingPasswordHash) &&
sameOptionalString(left.pendingScenario, right.pendingScenario) &&
sameOptionalString(left.pendingOnboardingStep, right.pendingOnboardingStep) &&
sameOptionalInt64(left.c1RegistrationVersion, right.c1RegistrationVersion) &&
left.tokenCount == right.tokenCount && left.sessionCount == right.sessionCount &&
left.confirmationEventCount == right.confirmationEventCount
}
func assertConfirmationApplied(t *testing.T, before, after confirmationState, scenario, step string) {
t.Helper()
if after.scenario != scenario || after.onboardingStep != step || after.emailVerifiedAt == nil ||
after.registrationVersion != before.tokenRegistrationVersion ||
after.userVersion != before.userVersion+1 || after.tokenConsumedAt == nil ||
after.tokenInvalidatedAt != nil || after.pendingPasswordHash != nil ||
after.pendingScenario != nil || after.pendingOnboardingStep != nil ||
after.c1RegistrationVersion == nil || *after.c1RegistrationVersion != after.tokenRegistrationVersion ||
before.pendingPasswordHash == nil || after.passwordHash != *before.pendingPasswordHash ||
after.tokenCount != before.tokenCount || after.sessionCount != 0 || after.confirmationEventCount != 1 {
t.Fatal("confirmation did not atomically apply the emailed registration and consume its token")
}
}
func assertSingleConfirmationEvent(ctx context.Context, t *testing.T, harness *registrationHarness, email string) {
t.Helper()
var userID string
if err := harness.pool.QueryRow(ctx, `SELECT id::text FROM users WHERE email_normalized = $1`, strings.ToLower(email)).Scan(&userID); err != nil {
t.Fatalf("read confirmed account ID: %v", err)
}
var count int
var eventType, aggregateType, aggregateID, payload string
var aggregateVersion int64
rows, err := harness.pool.Query(ctx, `SELECT event_type, aggregate_type, aggregate_id::text, aggregate_version, payload::text
FROM outbox_events WHERE event_type = 'identity.email_verified' AND aggregate_id = $1`, userID)
if err != nil {
t.Fatalf("read confirmation outbox event: %v", err)
}
for rows.Next() {
count++
if err := rows.Scan(&eventType, &aggregateType, &aggregateID, &aggregateVersion, &payload); err != nil {
rows.Close()
t.Fatalf("scan confirmation outbox event: %v", err)
}
}
if err := rows.Err(); err != nil {
rows.Close()
t.Fatalf("read confirmation outbox events: %v", err)
}
rows.Close()
var userVersion int64
if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1::uuid`, userID).Scan(&userVersion); err != nil {
t.Fatalf("read confirmed account version: %v", err)
}
if count != 1 || eventType != "identity.email_verified" || aggregateType != "user" ||
aggregateID != userID || aggregateVersion != userVersion || payload != "{}" {
t.Fatal("confirmation outbox event count or contents do not match the confirmed account")
}
}
func requireConfirmationSuccess(t *testing.T, response registrationResponse, scenario, step string) {
t.Helper()
want := fmt.Sprintf(`{"email_verified":true,"scenario":%q,"onboarding_step":%q}`, scenario, step)
mediaType, _, contentTypeErr := mime.ParseMediaType(response.contentType)
if response.status != http.StatusOK || response.body != want || contentTypeErr != nil || mediaType != "application/json" ||
response.setCookie != "" || response.retryAfter != "" {
t.Fatalf("confirmation response = %d %q (content type %q, Set-Cookie present %t, Retry-After %q), want 200 %q with JSON media type and no session or rate-limit headers",
response.status, response.body, response.contentType, response.setCookie != "", response.retryAfter, want)
}
}
func requirePositiveRetryAfter(t *testing.T, response registrationResponse) {
t.Helper()
seconds, err := strconv.Atoi(response.retryAfter)
if err != nil || seconds < 1 || seconds > int(confirmationRetryWindow/time.Second) {
t.Fatalf("Retry-After = %q, want 1 to %d seconds", response.retryAfter, int(confirmationRetryWindow/time.Second))
}
}
func installConfirmationOutboxFailure(ctx context.Context, t *testing.T, harness *registrationHarness) {
t.Helper()
harness.exec(ctx, t, fmt.Sprintf(`CREATE FUNCTION %s() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.event_type = 'identity.email_verified' THEN
RAISE EXCEPTION USING ERRCODE = 'P0001', MESSAGE = 'test confirmation outbox failure';
END IF;
RETURN NEW;
END;
$$`, pgx.Identifier{confirmationFailureFunction}.Sanitize()))
harness.exec(ctx, t, fmt.Sprintf(`CREATE TRIGGER %s BEFORE INSERT ON outbox_events
FOR EACH ROW EXECUTE FUNCTION %s()`,
pgx.Identifier{confirmationFailureTrigger}.Sanitize(),
pgx.Identifier{confirmationFailureFunction}.Sanitize()))
t.Cleanup(func() {
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
defer cancel()
if _, err := harness.pool.Exec(cleanupCtx, fmt.Sprintf(`DROP TRIGGER IF EXISTS %s ON outbox_events`,
pgx.Identifier{confirmationFailureTrigger}.Sanitize())); err != nil {
t.Errorf("drop confirmation outbox trigger: %v", err)
}
if _, err := harness.pool.Exec(cleanupCtx, fmt.Sprintf(`DROP FUNCTION IF EXISTS %s()`,
pgx.Identifier{confirmationFailureFunction}.Sanitize())); err != nil {
t.Errorf("drop confirmation outbox trigger function: %v", err)
}
})
}
func stringPointer(value string) *string { return &value }
func sameOptionalString(left, right *string) bool {
if left == nil || right == nil {
return left == nil && right == nil
}
return *left == *right
}
func sameOptionalTime(left, right *time.Time) bool {
if left == nil || right == nil {
return left == nil && right == nil
}
return left.Equal(*right)
}
func sameOptionalInt64(left, right *int64) bool {
if left == nil || right == nil {
return left == nil && right == nil
}
return *left == *right
}