feat(identity): add server sessions and audited mail recovery
This commit is contained in:
1 parent
20c03288d6
commit
4ee53d9a74
58 files changed
+5359
-567
No files matched your search
@@ -0,0 +1,72 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const mailRetryMigrationVersion = 17
|
||||
|
||||
func TestMailRetryMigrationKeepsAnAppendOnlyAudit(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
migrator := newMigrator(t, databaseURL)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("Up() error = %v", err)
|
||||
}
|
||||
|
||||
deliveryID := uuid.New()
|
||||
decidedAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO delivery_retry_decisions (
|
||||
delivery_id, attempt_count, actor, duplicate_risk_acknowledged, previous_lease_expired, decided_at
|
||||
) VALUES ($1, 2, 'operator:mail-ops', true, false, $2)`, deliveryID, decidedAt); err != nil {
|
||||
t.Fatalf("insert retry decision: %v", err)
|
||||
}
|
||||
|
||||
for _, statement := range []string{
|
||||
"UPDATE delivery_retry_decisions SET actor = 'operator:other' WHERE delivery_id = '" + deliveryID.String() + "'",
|
||||
"DELETE FROM delivery_retry_decisions WHERE delivery_id = '" + deliveryID.String() + "'",
|
||||
"TRUNCATE delivery_retry_decisions",
|
||||
} {
|
||||
_, err := pool.Exec(ctx, statement)
|
||||
assertSQLRefusal(t, err, "delivery_retry_decisions_immutable")
|
||||
}
|
||||
var decisions int
|
||||
if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 {
|
||||
t.Fatalf("audit decisions = %d, %v; want one retained record", decisions, err)
|
||||
}
|
||||
var predicate string
|
||||
if err := pool.QueryRow(ctx, `SELECT pg_get_expr(indpred, indrelid) FROM pg_index WHERE indexrelid = 'deliveries_due_idx'::regclass`).Scan(&predicate); err != nil {
|
||||
t.Fatalf("read deliveries_due_idx predicate: %v", err)
|
||||
}
|
||||
if predicate == "" || !containsAll(predicate, "unknown", "next_attempt_at") {
|
||||
t.Fatalf("deliveries_due_idx predicate = %q; want scheduled unknown rows", predicate)
|
||||
}
|
||||
|
||||
result, err := migrator.DownOne(ctx)
|
||||
if err != nil || result.Version != mailRetryMigrationVersion {
|
||||
t.Fatalf("DownOne() = %+v, %v; want rollback of migration %d", result, err, mailRetryMigrationVersion)
|
||||
}
|
||||
var auditTable bool
|
||||
if err := pool.QueryRow(ctx, "SELECT to_regclass('public.delivery_retry_decisions') IS NOT NULL").Scan(&auditTable); err != nil || auditTable {
|
||||
t.Fatalf("audit table after rollback = %t, %v; want removed", auditTable, err)
|
||||
}
|
||||
}
|
||||
|
||||
func containsAll(value string, fragments ...string) bool {
|
||||
for _, fragment := range fragments {
|
||||
if !strings.Contains(value, fragment) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/cli/mailretry"
|
||||
"lincodex/backend/internal/adapter/secondary/mail/disabled"
|
||||
"lincodex/backend/internal/adapter/secondary/mail/resend"
|
||||
"lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture"
|
||||
@@ -145,6 +147,7 @@ func TestServiceMailSending(t *testing.T) {
|
||||
fixture := resendfixture.New()
|
||||
t.Cleanup(fixture.Close)
|
||||
clock := &testClock{now: mailSenderStart}
|
||||
fixture.SetClock(clock.Now)
|
||||
transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, fixture.URL(), clock.Now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLoopbackSender() error = %v", err)
|
||||
@@ -173,6 +176,7 @@ func TestServiceMailSending(t *testing.T) {
|
||||
// their start instead.
|
||||
truncateTables(ctx, t, pool, slices.Concat(mailSenderTables, usersDependentTables)...)
|
||||
clock.Set(mailSenderStart)
|
||||
fixture.SetClock(clock.Now)
|
||||
fixture.SetDelay(0)
|
||||
}
|
||||
|
||||
@@ -246,6 +250,45 @@ func TestServiceMailSending(t *testing.T) {
|
||||
harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), "verify-email")
|
||||
})
|
||||
|
||||
t.Run("an accepted request with a lost response retries under the same key within 24 hours", func(t *testing.T) {
|
||||
reset(t)
|
||||
calls := len(fixture.Requests())
|
||||
messages := fixture.Messages()
|
||||
user := harness.createUser(ctx, t, false)
|
||||
_, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime)
|
||||
sender := harness.newSender(t, harness.transactor, 100, 3000)
|
||||
fixture.Script(resendfixture.Reply{DropAfterAccept: true})
|
||||
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("pass after the fixture accepted and dropped the response = %+v, want unknown", result)
|
||||
}
|
||||
uncertain := harness.delivery(ctx, t, deliveryID)
|
||||
if uncertain.Status() != domain.DeliveryStatusUnknown || !uncertain.NextAttemptAt().Equal(mailSenderStart.Add(time.Minute)) {
|
||||
t.Fatalf("delivery is %s due %s, want unknown with a bounded retry", uncertain.Status(), uncertain.NextAttemptAt())
|
||||
}
|
||||
if fixture.Messages()-messages != 1 {
|
||||
t.Fatalf("fixture accepted %d messages, want exactly one before the retry", fixture.Messages()-messages)
|
||||
}
|
||||
|
||||
harness.clock.Advance(time.Minute)
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted {
|
||||
t.Fatalf("pass within the provider window = %+v, want the original acceptance", result)
|
||||
}
|
||||
requests := fixture.Requests()[calls:]
|
||||
if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey ||
|
||||
requests[0].IdempotencyKey != "delivery/"+deliveryID.String() || !requests[1].Replayed ||
|
||||
!slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject ||
|
||||
requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML {
|
||||
t.Fatalf("provider calls = %+v, want the same pinned key and stored body, replayed once", requests)
|
||||
}
|
||||
stored := harness.delivery(ctx, t, deliveryID)
|
||||
if stored.ProviderAccount() != harness.account || stored.Status() != domain.DeliveryStatusAccepted ||
|
||||
stored.AttemptCount() != 2 || fixture.Messages()-messages != 1 {
|
||||
t.Fatalf("delivery is %s on %s after %d attempts, fixture has %d new message(s); want pinned account, accepted, two calls, one message",
|
||||
stored.Status(), stored.ProviderAccount().Account(), stored.AttemptCount(), fixture.Messages()-messages)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a worker that holds a delivery keeps every other worker off it", func(t *testing.T) {
|
||||
reset(t)
|
||||
calls := len(fixture.Requests())
|
||||
@@ -917,21 +960,27 @@ func TestServiceMailSending(t *testing.T) {
|
||||
t.Fatalf("attempts = %+v, want a temporary refusal and then acceptance", attempts)
|
||||
}
|
||||
|
||||
// An uncertain answer is never retried by the worker and never read
|
||||
// as not sent.
|
||||
// An uncertain answer remains unknown, but gets a bounded retry while
|
||||
// the provider still holds the idempotency key.
|
||||
other := harness.createUser(ctx, t, false)
|
||||
_, _, uncertainID := harness.enqueueVerification(ctx, t, other, mailSenderTokenLifetime)
|
||||
fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"})
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("pass after a 500 = %+v, want unknown", result)
|
||||
}
|
||||
if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().IsZero() {
|
||||
t.Fatalf("delivery is %s with next attempt %s, want unknown without one", got.Status(), got.NextAttemptAt())
|
||||
if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().Equal(harness.clock.Now().Add(time.Minute)) {
|
||||
t.Fatalf("delivery is %s with next attempt %s, want unknown with bounded retry", got.Status(), got.NextAttemptAt())
|
||||
}
|
||||
harness.clock.Advance(24 * time.Hour)
|
||||
// PostgreSQL owns the cutoff clock; move its start time to exercise
|
||||
// the same DB-clock age calculation without sleeping for a day.
|
||||
harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '24 hours' WHERE id = $1", uncertainID)
|
||||
callsBefore := len(fixture.Requests())
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()) != callsBefore {
|
||||
t.Fatalf("pass after an unknown outcome = %+v, want idle without a call", result)
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown || len(fixture.Requests()) != callsBefore {
|
||||
t.Fatalf("pass after the deduplication cutoff = %+v, want unknown without a call", result)
|
||||
}
|
||||
if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().IsZero() {
|
||||
t.Fatalf("delivery after cutoff is %s due %s, want terminal unknown without automatic retry", got.Status(), got.NextAttemptAt())
|
||||
}
|
||||
|
||||
// A permanent refusal ends the delivery.
|
||||
@@ -947,6 +996,344 @@ func TestServiceMailSending(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an earlier unknown answer remains uncertain after a confirmed 429", func(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
age time.Duration
|
||||
wantOutcome inbound.MailPassOutcome
|
||||
wantStatus domain.DeliveryStatus
|
||||
wantCalls int
|
||||
}{
|
||||
{name: "retry remains allowed before cutoff", age: 22 * time.Hour, wantOutcome: inbound.MailPassAccepted, wantStatus: domain.DeliveryStatusAccepted, wantCalls: 3},
|
||||
{name: "cutoff stops without a phantom attempt", age: 24 * time.Hour, wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantCalls: 2},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
reset(t)
|
||||
calls := len(fixture.Requests())
|
||||
messages := fixture.Messages()
|
||||
user := harness.createUser(ctx, t, false)
|
||||
_, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime)
|
||||
sender := harness.newSender(t, harness.transactor, 100, 3000)
|
||||
|
||||
fixture.Script(resendfixture.Reply{DropAfterAccept: true})
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("accepted request with dropped response = %+v, want unknown", result)
|
||||
}
|
||||
harness.clock.Advance(time.Minute)
|
||||
fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "rate_limit_exceeded", RetryAfter: "60"})
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry {
|
||||
t.Fatalf("confirmed 429 = %+v, want retry", result)
|
||||
}
|
||||
pending := harness.delivery(ctx, t, deliveryID)
|
||||
if pending.Status() != domain.DeliveryStatusPending || pending.AttemptCount() != 2 {
|
||||
t.Fatalf("delivery after 429 is %s after %d attempts, want pending after two", pending.Status(), pending.AttemptCount())
|
||||
}
|
||||
attempts := harness.attempts(ctx, t, deliveryID)
|
||||
if len(attempts) != 2 || attempts[0].Outcome != domain.DeliveryOutcomeUnknown || attempts[1].Rejection != domain.DeliveryRejectionRateLimited {
|
||||
t.Fatalf("attempts = %+v, want unknown then confirmed rate limit", attempts)
|
||||
}
|
||||
|
||||
harness.clock.Set(mailSenderStart.Add(test.age))
|
||||
harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - make_interval(secs => $2::float8) WHERE id = $1", deliveryID, test.age.Seconds())
|
||||
result := harness.pass(ctx, t, sender)
|
||||
stored := harness.delivery(ctx, t, deliveryID)
|
||||
if result.Outcome != test.wantOutcome || stored.Status() != test.wantStatus || len(fixture.Requests())-calls != test.wantCalls {
|
||||
t.Fatalf("pass = %+v, delivery %s, provider requests %d; want %s and %d calls", result, stored.Status(), len(fixture.Requests())-calls, test.wantOutcome, test.wantCalls)
|
||||
}
|
||||
requests := fixture.Requests()[calls:]
|
||||
if requests[0].IdempotencyKey != requests[1].IdempotencyKey ||
|
||||
!slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject ||
|
||||
requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML {
|
||||
t.Fatal("unknown and confirmed-refusal requests did not keep the same pinned key and body")
|
||||
}
|
||||
if test.wantStatus == domain.DeliveryStatusUnknown &&
|
||||
(stored.AttemptCount() != 2 || !stored.NextAttemptAt().IsZero() || len(attempts) != 2 || fixture.Messages()-messages != 1) {
|
||||
t.Fatalf("cutoff state = %s due %s after %d attempts, fixture accepted %d messages; want no new call or attempt", stored.Status(), stored.NextAttemptAt(), stored.AttemptCount(), fixture.Messages()-messages)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("manual retry audits the decision, honors 429 Retry-After, and stops after another unknown", func(t *testing.T) {
|
||||
reset(t)
|
||||
calls := len(fixture.Requests())
|
||||
messages := fixture.Messages()
|
||||
user := harness.createUser(ctx, t, false)
|
||||
_, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime)
|
||||
sender := harness.newSender(t, harness.transactor, 100, 3000)
|
||||
fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"})
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("initial 500 pass = %+v, want unknown", result)
|
||||
}
|
||||
|
||||
operator, err := notification.NewDeliveryRetryOperator(
|
||||
harness.transactor, harness.deliveries, harness.account, resend.IdempotencyWindow, harness.clock.Now,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDeliveryRetryOperator() error = %v", err)
|
||||
}
|
||||
if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) {
|
||||
t.Fatalf("RetryUnknown() before cutoff error = %v, want not allowed", err)
|
||||
}
|
||||
if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", false); !errors.Is(err, notification.ErrDuplicateRiskAcknowledgementRequired) {
|
||||
t.Fatalf("RetryUnknown() without acknowledgement error = %v, want acknowledgement required", err)
|
||||
}
|
||||
|
||||
// Claim while the original result is still inside the safe window,
|
||||
// then age the DB-clock timestamp before MarkSendStarted. The last
|
||||
// storage check must refuse the call even though the claim succeeded.
|
||||
harness.clock.Advance(time.Minute)
|
||||
owner := uuid.New()
|
||||
var claimed outbound.ClaimedDelivery
|
||||
if err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
claimed, err = unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{
|
||||
Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: time.Minute,
|
||||
})
|
||||
return err
|
||||
}); err != nil || claimed.Delivery.ID() != deliveryID {
|
||||
t.Fatalf("claim for the cutoff check = %s, %v; want the uncertain delivery", claimed.Delivery.ID(), err)
|
||||
}
|
||||
harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '24 hours' WHERE id = $1", deliveryID)
|
||||
started, err := harness.deliveries.MarkSendStarted(ctx, deliveryID, owner, true, 23*time.Hour)
|
||||
if err != nil || started {
|
||||
t.Fatalf("MarkSendStarted() at the DB-clock cutoff = %t, %v; want no send", started, err)
|
||||
}
|
||||
if released, err := harness.deliveries.ReleaseClaim(ctx, deliveryID, owner); err != nil || !released {
|
||||
t.Fatalf("ReleaseClaim() after cutoff refusal = %t, %v; want released", released, err)
|
||||
}
|
||||
|
||||
harness.clock.Set(mailSenderStart.Add(23 * time.Hour))
|
||||
harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '23 hours' WHERE id = $1", deliveryID)
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("pass at the automatic cutoff = %+v, want automatic retry stopped", result)
|
||||
}
|
||||
stopped := harness.delivery(ctx, t, deliveryID)
|
||||
if stopped.Status() != domain.DeliveryStatusUnknown || !stopped.NextAttemptAt().IsZero() {
|
||||
t.Fatalf("delivery after automatic cutoff is %s due %s, want unknown without automatic retry", stopped.Status(), stopped.NextAttemptAt())
|
||||
}
|
||||
lookup := func(key string) (string, bool) {
|
||||
switch key {
|
||||
case "DATABASE_URL":
|
||||
return env.Config.DatabaseURL, true
|
||||
case "EMAIL_PROVIDER":
|
||||
return "resend", true
|
||||
case "EMAIL_ACCOUNT":
|
||||
return mailSenderAccount, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
var cliOutput bytes.Buffer
|
||||
if err := mailretry.Run(ctx, []string{"inspect", "--delivery", deliveryID.String()}, lookup, &cliOutput); err != nil {
|
||||
t.Fatalf("mail-retry inspect error = %v", err)
|
||||
}
|
||||
if !strings.Contains(cliOutput.String(), notification.DuplicateRiskWarning) ||
|
||||
strings.Contains(cliOutput.String(), user.Email.Address()) {
|
||||
t.Fatalf("mail-retry inspect output = %q; want duplicate warning without recipient data", cliOutput.String())
|
||||
}
|
||||
cliOutput.Reset()
|
||||
if err := mailretry.Run(ctx, []string{
|
||||
"retry", "--delivery", deliveryID.String(), "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk",
|
||||
}, lookup, &cliOutput); err != nil {
|
||||
t.Fatalf("mail-retry retry error = %v", err)
|
||||
}
|
||||
if !strings.Contains(cliOutput.String(), notification.DuplicateRiskWarning) ||
|
||||
!strings.Contains(cliOutput.String(), "retry scheduled; audit decision recorded") {
|
||||
t.Fatalf("mail-retry retry output = %q; want warning and audited scheduling", cliOutput.String())
|
||||
}
|
||||
if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) {
|
||||
t.Fatalf("duplicate RetryUnknown() error = %v, want not allowed", err)
|
||||
}
|
||||
var decisions int
|
||||
if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 {
|
||||
t.Fatalf("audited decisions = %d, %v; want exactly one", decisions, err)
|
||||
}
|
||||
|
||||
fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "rate_limit_exceeded", RetryAfter: "300"})
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry {
|
||||
t.Fatalf("manual 429 pass = %+v, want scheduled retry", result)
|
||||
}
|
||||
rateLimited := harness.delivery(ctx, t, deliveryID)
|
||||
wantRetryAt := harness.clock.Now().Add(5 * time.Minute)
|
||||
if rateLimited.Status() != domain.DeliveryStatusPending || !rateLimited.NextAttemptAt().Equal(wantRetryAt) {
|
||||
t.Fatalf("429 state is %s due %s, want pending due at Retry-After %s", rateLimited.Status(), rateLimited.NextAttemptAt(), wantRetryAt)
|
||||
}
|
||||
|
||||
harness.clock.Set(wantRetryAt)
|
||||
fixture.Script(resendfixture.Reply{DropAfterAccept: true})
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("manual send with accepted connection drop = %+v, want unknown", result)
|
||||
}
|
||||
unknown := harness.delivery(ctx, t, deliveryID)
|
||||
if unknown.Status() != domain.DeliveryStatusUnknown || !unknown.NextAttemptAt().IsZero() || unknown.AttemptCount() != 3 {
|
||||
t.Fatalf("manual drop state is %s due %s after %d attempts, want terminal unknown after 3", unknown.Status(), unknown.NextAttemptAt(), unknown.AttemptCount())
|
||||
}
|
||||
callsAfterUnknown := len(fixture.Requests())
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()) != callsAfterUnknown {
|
||||
t.Fatalf("pass after manual unknown = %+v with %d requests, want idle", result, len(fixture.Requests())-calls)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 {
|
||||
t.Fatalf("audited decisions without another operator command = %d, %v; want still one", decisions, err)
|
||||
}
|
||||
requests := fixture.Requests()[calls:]
|
||||
if len(requests) != 3 || fixture.Messages()-messages != 1 {
|
||||
t.Fatalf("provider saw %d requests and accepted %d messages; want 3 requests and one accepted message", len(requests), fixture.Messages()-messages)
|
||||
}
|
||||
for _, request := range requests[1:] {
|
||||
if request.IdempotencyKey != requests[0].IdempotencyKey || !slices.Equal(request.To, requests[0].To) ||
|
||||
request.Subject != requests[0].Subject || request.Text != requests[0].Text || request.HTML != requests[0].HTML {
|
||||
t.Fatal("the manual retries changed the pinned key or stored body")
|
||||
}
|
||||
}
|
||||
if requests[2].Replayed {
|
||||
t.Fatal("the final request was unexpectedly replayed before the fixture accepted its first manual request")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an expired manual send-start is recorded before another authorized send", func(t *testing.T) {
|
||||
reset(t)
|
||||
calls := len(fixture.Requests())
|
||||
user := harness.createUser(ctx, t, false)
|
||||
_, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime)
|
||||
sender := harness.newSender(t, harness.transactor, 100, 3000)
|
||||
fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"})
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("initial 500 pass = %+v, want unknown", result)
|
||||
}
|
||||
harness.clock.Set(mailSenderStart.Add(23 * time.Hour))
|
||||
harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '23 hours' WHERE id = $1", deliveryID)
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("pass at automatic cutoff = %+v, want terminal unknown", result)
|
||||
}
|
||||
|
||||
lookup := func(key string) (string, bool) {
|
||||
switch key {
|
||||
case "DATABASE_URL":
|
||||
return env.Config.DatabaseURL, true
|
||||
case "EMAIL_PROVIDER":
|
||||
return "resend", true
|
||||
case "EMAIL_ACCOUNT":
|
||||
return mailSenderAccount, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
retryCommand := func() {
|
||||
t.Helper()
|
||||
var output bytes.Buffer
|
||||
if err := mailretry.Run(ctx, []string{
|
||||
"retry", "--delivery", deliveryID.String(), "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk",
|
||||
}, lookup, &output); err != nil {
|
||||
t.Fatalf("mail-retry command error = %v", err)
|
||||
}
|
||||
if !strings.Contains(output.String(), notification.DuplicateRiskWarning) ||
|
||||
!strings.Contains(output.String(), "retry scheduled; audit decision recorded") ||
|
||||
strings.Contains(output.String(), user.Email.Address()) {
|
||||
t.Fatalf("mail-retry output = %q; want warning and safe scheduling result", output.String())
|
||||
}
|
||||
}
|
||||
dbClock := func() time.Time {
|
||||
t.Helper()
|
||||
var now time.Time
|
||||
if err := pool.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); err != nil {
|
||||
t.Fatalf("read database clock: %v", err)
|
||||
}
|
||||
return now
|
||||
}
|
||||
retryCommand()
|
||||
authorized := harness.delivery(ctx, t, deliveryID)
|
||||
if authorized.Status() != domain.DeliveryStatusUnknown || authorized.NextAttemptAt().IsZero() {
|
||||
t.Fatalf("authorized delivery state = %s due %s; want scheduled unknown work", authorized.Status(), authorized.NextAttemptAt())
|
||||
}
|
||||
// Authorization keeps the later of the app and database timestamps.
|
||||
// The cutoff pass above uses the fake app clock, so advancing only to
|
||||
// database-now can still leave the delivery not due yet.
|
||||
dueAfterAuthorization := authorized.NextAttemptAt().Add(time.Second)
|
||||
if databaseNow := dbClock().Add(time.Second); databaseNow.After(dueAfterAuthorization) {
|
||||
dueAfterAuthorization = databaseNow
|
||||
}
|
||||
harness.clock.Set(dueAfterAuthorization)
|
||||
owner := uuid.New()
|
||||
var claimed outbound.ClaimedDelivery
|
||||
if err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
claimed, err = unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{
|
||||
Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: mailSenderLease,
|
||||
})
|
||||
return err
|
||||
}); err != nil || claimed.Delivery.ID() != deliveryID || !claimed.ManualRetryPending {
|
||||
t.Fatalf("manual send claim = %s, pending %t, error %v; want the authorized delivery", claimed.Delivery.ID(), claimed.ManualRetryPending, err)
|
||||
}
|
||||
started, err := harness.deliveries.MarkSendStarted(ctx, deliveryID, owner, true, 23*time.Hour)
|
||||
if err != nil || !started {
|
||||
t.Fatalf("MarkSendStarted() for operator decision = %t, %v; want started", started, err)
|
||||
}
|
||||
harness.exec(ctx, t, "UPDATE deliveries SET claimed_until = clock_timestamp() - interval '1 second' WHERE id = $1", deliveryID)
|
||||
|
||||
callsBeforeRecovery := len(fixture.Requests())
|
||||
retryCommand()
|
||||
if len(fixture.Requests()) != callsBeforeRecovery {
|
||||
t.Fatal("operator recovery called the provider instead of only recording the lost result and scheduling work")
|
||||
}
|
||||
recovered := harness.delivery(ctx, t, deliveryID)
|
||||
attempts := harness.attempts(ctx, t, deliveryID)
|
||||
if recovered.AttemptCount() != 2 || recovered.Status() != domain.DeliveryStatusUnknown || recovered.NextAttemptAt().IsZero() || len(attempts) != 2 ||
|
||||
attempts[0].Outcome != domain.DeliveryOutcomeUnknown || attempts[1].Outcome != domain.DeliveryOutcomeUnknown ||
|
||||
attempts[1].At.Before(attempts[0].At) {
|
||||
t.Fatalf("recovered delivery = %s due %s after %d attempts, attempts %+v; want the lost manual call appended as unknown and another decision scheduled", recovered.Status(), recovered.NextAttemptAt(), recovered.AttemptCount(), attempts)
|
||||
}
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT attempt_count, duplicate_risk_acknowledged, previous_lease_expired
|
||||
FROM delivery_retry_decisions
|
||||
WHERE delivery_id = $1
|
||||
ORDER BY decision_id`, deliveryID)
|
||||
if err != nil {
|
||||
t.Fatalf("read retry decisions: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var decisions []struct {
|
||||
attemptCount int32
|
||||
duplicateRiskAcknowledged bool
|
||||
previousLeaseExpired bool
|
||||
}
|
||||
for rows.Next() {
|
||||
var decision struct {
|
||||
attemptCount int32
|
||||
duplicateRiskAcknowledged bool
|
||||
previousLeaseExpired bool
|
||||
}
|
||||
if err := rows.Scan(&decision.attemptCount, &decision.duplicateRiskAcknowledged, &decision.previousLeaseExpired); err != nil {
|
||||
t.Fatalf("scan retry decision: %v", err)
|
||||
}
|
||||
decisions = append(decisions, decision)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatalf("read retry decisions: %v", err)
|
||||
}
|
||||
if len(decisions) != 2 || decisions[0].attemptCount != 1 || decisions[1].attemptCount != 2 ||
|
||||
!decisions[0].duplicateRiskAcknowledged || !decisions[1].duplicateRiskAcknowledged ||
|
||||
decisions[0].previousLeaseExpired || !decisions[1].previousLeaseExpired {
|
||||
t.Fatalf("retry decisions = %+v; want each decision tied to its unknown attempt and second decision marked as lease recovery", decisions)
|
||||
}
|
||||
|
||||
dueAfterRecovery := recovered.NextAttemptAt().Add(time.Second)
|
||||
if databaseNow := dbClock().Add(time.Second); databaseNow.After(dueAfterRecovery) {
|
||||
dueAfterRecovery = databaseNow
|
||||
}
|
||||
harness.clock.Set(dueAfterRecovery)
|
||||
fixture.Script(resendfixture.Reply{})
|
||||
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted {
|
||||
t.Fatalf("pass after recovered operator decision = %+v, want accepted", result)
|
||||
}
|
||||
requests := fixture.Requests()[calls:]
|
||||
if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey ||
|
||||
!slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject ||
|
||||
requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML {
|
||||
t.Fatalf("provider requests after recovery = %+v; want initial and manually authorized request with the pinned key and body", requests)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a used-up quota parks the delivery in a user-visible waiting status", func(t *testing.T) {
|
||||
reset(t)
|
||||
calls := len(fixture.Requests())
|
||||
|
||||
@@ -8,9 +8,15 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
)
|
||||
|
||||
const registrationConsentMigrationName = "00016_bind_registration_consent.sql"
|
||||
const (
|
||||
registrationConsentMigrationVersion = 16
|
||||
registrationConsentMigrationName = "00016_bind_registration_consent.sql"
|
||||
mailRetryMigrationName = "00017_retry_unknown_mail.sql"
|
||||
)
|
||||
|
||||
func TestRegistrationConsentMigration(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
@@ -24,10 +30,7 @@ func TestRegistrationConsentMigration(t *testing.T) {
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("apply migrations before preparing legacy data: %v", err)
|
||||
}
|
||||
rolledBack, err := migrator.DownOne(ctx)
|
||||
if err != nil || rolledBack.Name != registrationConsentMigrationName {
|
||||
t.Fatalf("roll back the registration-consent migration = %+v, %v", rolledBack, err)
|
||||
}
|
||||
rollbackThroughRegistrationConsent(ctx, t, migrator)
|
||||
assertRegistrationConsentColumn(ctx, t, pool, false)
|
||||
|
||||
const userID = "018f0000-0000-7000-8000-000000000001"
|
||||
@@ -41,8 +44,8 @@ func TestRegistrationConsentMigration(t *testing.T) {
|
||||
seedRegistrationConsentFixture(ctx, t, pool, userID, createdAt, registrationAt, registrationConsentID, settingsConsentID, otherConsentID, c1SettingsVersion, settingsAt)
|
||||
|
||||
applied, err := migrator.Up(ctx)
|
||||
if err != nil || len(applied) != 1 || applied[0].Name != registrationConsentMigrationName {
|
||||
t.Fatalf("apply registration-consent migration = %+v, %v", applied, err)
|
||||
if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName {
|
||||
t.Fatalf("apply registration-consent and later migrations = %+v, %v", applied, err)
|
||||
}
|
||||
assertConsentRegistrationVersion(ctx, t, pool, registrationConsentID, 2)
|
||||
assertConsentRegistrationVersionNull(ctx, t, pool, settingsConsentID, otherConsentID)
|
||||
@@ -89,17 +92,14 @@ func TestRegistrationConsentMigration(t *testing.T) {
|
||||
t.Fatal("a refused registration C1 version change altered its version or revocation state")
|
||||
}
|
||||
|
||||
rolledBack, err = migrator.DownOne(ctx)
|
||||
if err != nil || rolledBack.Name != registrationConsentMigrationName {
|
||||
t.Fatalf("roll back registration-consent migration = %+v, %v", rolledBack, err)
|
||||
}
|
||||
rollbackThroughRegistrationConsent(ctx, t, migrator)
|
||||
assertRegistrationConsentColumn(ctx, t, pool, false)
|
||||
if countConsentRecords(ctx, t, pool) != beforeMismatch {
|
||||
t.Fatal("rolling back the registration-consent migration changed the consent ledger")
|
||||
}
|
||||
applied, err = migrator.Up(ctx)
|
||||
if err != nil || len(applied) != 1 || applied[0].Name != registrationConsentMigrationName {
|
||||
t.Fatalf("reapply registration-consent migration = %+v, %v", applied, err)
|
||||
if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName {
|
||||
t.Fatalf("reapply registration-consent and later migrations = %+v, %v", applied, err)
|
||||
}
|
||||
assertRegistrationConsentColumn(ctx, t, pool, true)
|
||||
assertConsentRegistrationVersion(ctx, t, pool, compatibilityConsentID, 3)
|
||||
@@ -113,10 +113,7 @@ func TestRegistrationConsentMigration(t *testing.T) {
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("apply migrations before preparing stale legacy data: %v", err)
|
||||
}
|
||||
rolledBack, err := migrator.DownOne(ctx)
|
||||
if err != nil || rolledBack.Name != registrationConsentMigrationName {
|
||||
t.Fatalf("roll back the registration-consent migration = %+v, %v", rolledBack, err)
|
||||
}
|
||||
rollbackThroughRegistrationConsent(ctx, t, migrator)
|
||||
assertRegistrationConsentColumn(ctx, t, pool, false)
|
||||
|
||||
const userID = "018f0000-0000-7000-8000-000000000101"
|
||||
@@ -147,14 +144,36 @@ func TestRegistrationConsentMigration(t *testing.T) {
|
||||
if _, err := pool.Exec(ctx, `UPDATE users SET last_registered_at = $2, updated_at = $2 WHERE id = $1::uuid`, userID, grantAt); err != nil {
|
||||
t.Fatalf("correct the synthetic legacy registration timestamp: %v", err)
|
||||
}
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("migration did not succeed after the legacy data was corrected: %v", err)
|
||||
applied, err := migrator.Up(ctx)
|
||||
if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName {
|
||||
t.Fatalf("migrations did not succeed after the legacy data was corrected: %+v, %v", applied, err)
|
||||
}
|
||||
assertRegistrationConsentColumn(ctx, t, pool, true)
|
||||
assertConsentRegistrationVersion(ctx, t, pool, consentID, 1)
|
||||
})
|
||||
}
|
||||
|
||||
// rollbackThroughRegistrationConsent removes later migrations as well, so
|
||||
// each fixture is truly at the schema immediately before migration 00016.
|
||||
func rollbackThroughRegistrationConsent(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) {
|
||||
t.Helper()
|
||||
for {
|
||||
rolledBack, err := migrator.DownOne(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("roll back through registration-consent migration: %v", err)
|
||||
}
|
||||
if rolledBack.Version < registrationConsentMigrationVersion {
|
||||
t.Fatalf("rolled back migration %d before reaching migration %d", rolledBack.Version, registrationConsentMigrationVersion)
|
||||
}
|
||||
if rolledBack.Version == registrationConsentMigrationVersion {
|
||||
if rolledBack.Name != registrationConsentMigrationName {
|
||||
t.Fatalf("rolled back migration %d named %q, want %q", rolledBack.Version, rolledBack.Name, registrationConsentMigrationName)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func seedRegistrationConsentFixture(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
|
||||
@@ -0,0 +1,495 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
httpadapter "lincodex/backend/internal/adapter/primary/http"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/argon2id"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/health"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
const (
|
||||
sessionHTTPTestTimeout = 5 * time.Minute
|
||||
sessionHTTPTestOrigin = "http://localhost:8080"
|
||||
sessionHTTPTestPass = "correct horse battery staple"
|
||||
)
|
||||
|
||||
type sessionHTTPHarness struct {
|
||||
pool *pgxpool.Pool
|
||||
store *postgresadapter.IdentityStore
|
||||
router http.Handler
|
||||
credentials *identity.Credentials
|
||||
clock *testClock
|
||||
logs *strings.Builder
|
||||
}
|
||||
|
||||
func newSessionHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness {
|
||||
t.Helper()
|
||||
return newSessionHTTPHarnessWithSettings(ctx, t, env, identity.SessionSettings{
|
||||
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit),
|
||||
EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
|
||||
IdleTimeout: env.Config.IdentitySessionIdleTimeout,
|
||||
AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
|
||||
})
|
||||
}
|
||||
|
||||
func newSessionHTTPHarnessWithSettings(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
env *testEnvironment,
|
||||
settings identity.SessionSettings,
|
||||
) *sessionHTTPHarness {
|
||||
t.Helper()
|
||||
pool := env.newPool(ctx, t)
|
||||
store := postgresadapter.NewIdentityStore(pool)
|
||||
hasher, err := argon2id.NewHasher(1)
|
||||
if err != nil {
|
||||
t.Fatalf("NewHasher() error = %v", err)
|
||||
}
|
||||
credentials := identity.NewCredentials(hasher)
|
||||
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)}
|
||||
service, err := identity.NewSessionService(identity.SessionDependencies{
|
||||
Transactor: postgresadapter.NewTransactor(pool),
|
||||
Users: store.Users(),
|
||||
Sessions: store.Sessions(),
|
||||
Credentials: credentials,
|
||||
Limiter: env.Redis,
|
||||
Keyring: keyring,
|
||||
Clock: clock.Now,
|
||||
}, settings)
|
||||
if err != nil {
|
||||
t.Fatalf("NewSessionService() error = %v", err)
|
||||
}
|
||||
logs := &strings.Builder{}
|
||||
logger := slog.New(slog.NewJSONHandler(logs, nil))
|
||||
responder := problem.NewResponder(logger)
|
||||
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
||||
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(service, env.Config.AppPublicURL))
|
||||
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler))
|
||||
router, err := httpadapter.NewRouter(
|
||||
healthHandler,
|
||||
handler,
|
||||
v1.NewSessionSecurity(service, env.Config.AppPublicURL),
|
||||
responder,
|
||||
prometheus.New(),
|
||||
logger,
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
|
||||
}
|
||||
|
||||
func createSessionHTTPUser(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
harness *sessionHTTPHarness,
|
||||
email string,
|
||||
passwordHash domain.PasswordHash,
|
||||
verified bool,
|
||||
) domain.User {
|
||||
t.Helper()
|
||||
address, err := domain.NewEmailAddress(email)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
now := harness.clock.Now().Truncate(time.Microsecond)
|
||||
user, err := domain.NewUser(domain.Registration{
|
||||
Email: address,
|
||||
PasswordHash: passwordHash,
|
||||
Scenario: domain.ScenarioCandidate,
|
||||
RegisteredAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewUser() error = %v", err)
|
||||
}
|
||||
if err := harness.store.Users().Create(ctx, user); err != nil {
|
||||
t.Fatalf("Create(%s) error = %v", email, err)
|
||||
}
|
||||
if !verified {
|
||||
return user
|
||||
}
|
||||
user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond))
|
||||
if err != nil {
|
||||
t.Fatalf("MarkEmailVerified() error = %v", err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
func (harness *sessionHTTPHarness) request(
|
||||
t *testing.T,
|
||||
method string,
|
||||
path string,
|
||||
body string,
|
||||
origin string,
|
||||
cookie string,
|
||||
csrf string,
|
||||
remoteAddr string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if origin != "" {
|
||||
request.Header.Set("Origin", origin)
|
||||
}
|
||||
if cookie != "" {
|
||||
request.Header.Set("Cookie", "__Host-lincodex_session="+cookie)
|
||||
}
|
||||
if csrf != "" {
|
||||
request.Header.Set("X-CSRF-Token", csrf)
|
||||
}
|
||||
request.RemoteAddr = remoteAddr
|
||||
recorder := httptest.NewRecorder()
|
||||
harness.router.ServeHTTP(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
|
||||
func loginSessionHTTP(t *testing.T, harness *sessionHTTPHarness, email, password string, origin, cookie, remoteAddr string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}{Email: email, Password: password})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal login request: %v", err)
|
||||
}
|
||||
return harness.request(t, http.MethodPost, "/api/v1/identity/sessions", string(body), origin, cookie, "", remoteAddr)
|
||||
}
|
||||
|
||||
func requireSessionProblem(t *testing.T, response *httptest.ResponseRecorder, status int, code string) {
|
||||
t.Helper()
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode problem response %d %s: %v", response.Code, response.Body.String(), err)
|
||||
}
|
||||
if response.Code != status || body.Code != code {
|
||||
t.Fatalf("response = %d code=%q body=%s, want %d code=%q", response.Code, body.Code, response.Body.String(), status, code)
|
||||
}
|
||||
}
|
||||
|
||||
func requireSessionCookie(t *testing.T, response *httptest.ResponseRecorder) *http.Cookie {
|
||||
t.Helper()
|
||||
cookies := response.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("Set-Cookie values = %v, want exactly one session cookie", response.Header().Values("Set-Cookie"))
|
||||
}
|
||||
cookie := cookies[0]
|
||||
if cookie.Name != "__Host-lincodex_session" || cookie.Value == "" || cookie.Path != "/" || cookie.Domain != "" ||
|
||||
!cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode || cookie.MaxAge <= 0 || cookie.Expires.IsZero() {
|
||||
t.Fatalf("session cookie attributes = %+v", cookie)
|
||||
}
|
||||
return cookie
|
||||
}
|
||||
|
||||
func requireExpiredSessionCookie(t *testing.T, response *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
cookies := response.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("Set-Cookie values = %v, want one cleared session cookie", response.Header().Values("Set-Cookie"))
|
||||
}
|
||||
cookie := cookies[0]
|
||||
if cookie.Name != "__Host-lincodex_session" || cookie.Value != "" || cookie.Path != "/" || cookie.Domain != "" ||
|
||||
!cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode || cookie.MaxAge >= 0 {
|
||||
t.Fatalf("cleared session cookie attributes = %+v", cookie)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitySessionsOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout)
|
||||
defer cancel()
|
||||
harness := newSessionHTTPHarness(ctx, t, env)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
verifiedEmail := "verified@example.test"
|
||||
unverifiedEmail := "unverified@example.test"
|
||||
verifiedUser := createSessionHTTPUser(ctx, t, harness, verifiedEmail, passwordHash, true)
|
||||
createSessionHTTPUser(ctx, t, harness, unverifiedEmail, passwordHash, false)
|
||||
|
||||
unknown := loginSessionHTTP(t, harness, "unknown@example.test", sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.1:1234")
|
||||
wrongPassword := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, "", "192.0.2.2:1234")
|
||||
requireSessionProblem(t, unknown, http.StatusUnauthorized, "invalid_credentials")
|
||||
requireSessionProblem(t, wrongPassword, http.StatusUnauthorized, "invalid_credentials")
|
||||
if unknown.Header().Get("Content-Type") != wrongPassword.Header().Get("Content-Type") ||
|
||||
!strings.Contains(unknown.Header().Get("Content-Type"), "application/problem+json") {
|
||||
t.Fatalf("unknown and wrong-password response media types differ: %q and %q", unknown.Header().Get("Content-Type"), wrongPassword.Header().Get("Content-Type"))
|
||||
}
|
||||
if len(unknown.Header().Values("Set-Cookie")) != 0 || len(wrongPassword.Header().Values("Set-Cookie")) != 0 {
|
||||
t.Fatal("a rejected login set a session cookie")
|
||||
}
|
||||
unverified := loginSessionHTTP(t, harness, unverifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.3:1234")
|
||||
requireSessionProblem(t, unverified, http.StatusForbidden, "email_not_verified")
|
||||
if len(unverified.Header().Values("Set-Cookie")) != 0 {
|
||||
t.Fatal("unverified login set a session cookie")
|
||||
}
|
||||
|
||||
badOriginBody, err := json.Marshal(struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}{Email: verifiedEmail, Password: sessionHTTPTestPass})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal bad-origin login request: %v", err)
|
||||
}
|
||||
badOriginRequest := httptest.NewRequest(http.MethodPost, "/api/v1/identity/sessions", strings.NewReader(string(badOriginBody)))
|
||||
badOriginRequest.Header.Set("Content-Type", "application/json")
|
||||
badOriginRequest.Header.Set("Origin", "http://attacker.example")
|
||||
badOriginRequest.Header.Set("X-Forwarded-Host", "localhost:8080")
|
||||
badOriginRequest.RemoteAddr = "192.0.2.4:1234"
|
||||
badOrigin := httptest.NewRecorder()
|
||||
harness.router.ServeHTTP(badOrigin, badOriginRequest)
|
||||
requireSessionProblem(t, badOrigin, http.StatusForbidden, "csrf_check_failed")
|
||||
if len(badOrigin.Header().Values("Set-Cookie")) != 0 {
|
||||
t.Fatal("a login with a disallowed Origin set a session cookie")
|
||||
}
|
||||
|
||||
limitedEmail := "limit@example.test"
|
||||
for attempt := 1; attempt <= 10; attempt++ {
|
||||
response := loginSessionHTTP(t, harness, limitedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", fmt.Sprintf("198.51.100.%d:1234", attempt))
|
||||
requireSessionProblem(t, response, http.StatusUnauthorized, "invalid_credentials")
|
||||
}
|
||||
limited := loginSessionHTTP(t, harness, limitedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "198.51.100.11:1234")
|
||||
requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited")
|
||||
if limited.Header().Get("Retry-After") == "" {
|
||||
t.Fatal("email login limit response has no Retry-After")
|
||||
}
|
||||
|
||||
malformedCookieLogin := loginSessionHTTP(t, harness, verifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "not-a-session-token", "192.0.2.5:1234")
|
||||
if malformedCookieLogin.Code != http.StatusCreated {
|
||||
t.Fatalf("login with a malformed incoming cookie status = %d, body=%s", malformedCookieLogin.Code, malformedCookieLogin.Body.String())
|
||||
}
|
||||
firstCookie := requireSessionCookie(t, malformedCookieLogin)
|
||||
if malformedCookieLogin.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("login Cache-Control = %q, want no-store", malformedCookieLogin.Header().Get("Cache-Control"))
|
||||
}
|
||||
var firstBody struct {
|
||||
Account struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
} `json:"account"`
|
||||
CSRFToken string `json:"csrf_token"`
|
||||
}
|
||||
if err := json.Unmarshal(malformedCookieLogin.Body.Bytes(), &firstBody); err != nil {
|
||||
t.Fatalf("decode login response: %v", err)
|
||||
}
|
||||
if firstBody.Account.ID != verifiedUser.ID.String() || firstBody.Account.Email != verifiedEmail || !firstBody.Account.EmailVerified || firstBody.CSRFToken == "" {
|
||||
t.Fatalf("login account or CSRF token = %+v", firstBody)
|
||||
}
|
||||
|
||||
currentSession := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.6:1234")
|
||||
if currentSession.Code != http.StatusOK || currentSession.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("current session response = %d %s, Cache-Control=%q", currentSession.Code, currentSession.Body.String(), currentSession.Header().Get("Cache-Control"))
|
||||
}
|
||||
var sessionBody struct {
|
||||
Account struct {
|
||||
Email string `json:"email"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
} `json:"account"`
|
||||
CSRFToken string `json:"csrf_token"`
|
||||
}
|
||||
if err := json.Unmarshal(currentSession.Body.Bytes(), &sessionBody); err != nil {
|
||||
t.Fatalf("decode current session response: %v", err)
|
||||
}
|
||||
if sessionBody.Account.Email != verifiedEmail || !sessionBody.Account.EmailVerified || sessionBody.CSRFToken != firstBody.CSRFToken {
|
||||
t.Fatalf("current session response = %+v, want the authenticated account and CSRF token", sessionBody)
|
||||
}
|
||||
currentAccount := harness.request(t, http.MethodGet, "/api/v1/identity/me", "", "", firstCookie.Value, "", "192.0.2.7:1234")
|
||||
if currentAccount.Code != http.StatusOK || currentAccount.Header().Get("Cache-Control") != "no-store" || !strings.Contains(currentAccount.Body.String(), verifiedEmail) {
|
||||
t.Fatalf("current account response = %d %s, Cache-Control=%q", currentAccount.Code, currentAccount.Body.String(), currentAccount.Header().Get("Cache-Control"))
|
||||
}
|
||||
unsupported := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", firstCookie.Value, "", "192.0.2.8:1234")
|
||||
requireSessionProblem(t, unsupported, http.StatusUnauthorized, "unauthenticated")
|
||||
|
||||
wrongPasswordWithSession := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.9:1234")
|
||||
requireSessionProblem(t, wrongPasswordWithSession, http.StatusUnauthorized, "invalid_credentials")
|
||||
stillActive := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.10:1234")
|
||||
if stillActive.Code != http.StatusOK {
|
||||
t.Fatalf("failed login revoked its incoming session: status=%d body=%s", stillActive.Code, stillActive.Body.String())
|
||||
}
|
||||
|
||||
rotated := loginSessionHTTP(t, harness, verifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.11:1234")
|
||||
if rotated.Code != http.StatusCreated {
|
||||
t.Fatalf("rotating login status = %d, body=%s", rotated.Code, rotated.Body.String())
|
||||
}
|
||||
secondCookie := requireSessionCookie(t, rotated)
|
||||
if secondCookie.Value == firstCookie.Value {
|
||||
t.Fatal("rotating login reused the session token")
|
||||
}
|
||||
var secondBody struct {
|
||||
CSRFToken string `json:"csrf_token"`
|
||||
}
|
||||
if err := json.Unmarshal(rotated.Body.Bytes(), &secondBody); err != nil {
|
||||
t.Fatalf("decode rotated login response: %v", err)
|
||||
}
|
||||
if secondBody.CSRFToken == "" || secondBody.CSRFToken == firstBody.CSRFToken {
|
||||
t.Fatal("rotated login did not issue a new session-bound CSRF token")
|
||||
}
|
||||
replayed := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.12:1234")
|
||||
requireSessionProblem(t, replayed, http.StatusUnauthorized, "unauthenticated")
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
origin string
|
||||
csrf string
|
||||
}{
|
||||
{name: "wrong origin", origin: "http://attacker.example", csrf: secondBody.CSRFToken},
|
||||
{name: "wrong CSRF token", origin: sessionHTTPTestOrigin, csrf: firstBody.CSRFToken},
|
||||
{name: "missing CSRF token", origin: sessionHTTPTestOrigin},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
response := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", test.origin, secondCookie.Value, test.csrf, "192.0.2.13:1234")
|
||||
requireSessionProblem(t, response, http.StatusForbidden, "csrf_check_failed")
|
||||
if len(response.Header().Values("Set-Cookie")) != 0 {
|
||||
t.Fatalf("rejected logout cleared the session cookie: %v", response.Header().Values("Set-Cookie"))
|
||||
}
|
||||
active := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", secondCookie.Value, "", "192.0.2.14:1234")
|
||||
if active.Code != http.StatusOK {
|
||||
t.Fatalf("rejected logout revoked the session: %d %s", active.Code, active.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
logout := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", sessionHTTPTestOrigin, secondCookie.Value, secondBody.CSRFToken, "192.0.2.15:1234")
|
||||
if logout.Code != http.StatusNoContent || logout.Body.Len() != 0 {
|
||||
t.Fatalf("logout response = %d %q, want 204 with no body", logout.Code, logout.Body.String())
|
||||
}
|
||||
requireExpiredSessionCookie(t, logout)
|
||||
replayAfterLogout := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", secondCookie.Value, "", "192.0.2.16:1234")
|
||||
requireSessionProblem(t, replayAfterLogout, http.StatusUnauthorized, "unauthenticated")
|
||||
staleLogout := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", sessionHTTPTestOrigin, secondCookie.Value, secondBody.CSRFToken, "192.0.2.17:1234")
|
||||
requireSessionProblem(t, staleLogout, http.StatusUnauthorized, "unauthenticated")
|
||||
requireExpiredSessionCookie(t, staleLogout)
|
||||
|
||||
for _, secret := range []string{firstCookie.Value, secondCookie.Value, sessionHTTPTestPass, "incorrect horse battery staple"} {
|
||||
if secret != "" && strings.Contains(harness.logs.String(), secret) {
|
||||
t.Fatalf("a session token or password reached request logs")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExpiryAcrossAPIRestart(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout)
|
||||
defer cancel()
|
||||
first := newSessionHTTPHarness(ctx, t, env)
|
||||
|
||||
passwordHash, err := first.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
absoluteEmail := "absolute@example.test"
|
||||
idleEmail := "idle@example.test"
|
||||
createSessionHTTPUser(ctx, t, first, absoluteEmail, passwordHash, true)
|
||||
createSessionHTTPUser(ctx, t, first, idleEmail, passwordHash, true)
|
||||
|
||||
absoluteLogin := loginSessionHTTP(t, first, absoluteEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.20:1234")
|
||||
if absoluteLogin.Code != http.StatusCreated {
|
||||
t.Fatalf("absolute-expiry login status = %d, body=%s", absoluteLogin.Code, absoluteLogin.Body.String())
|
||||
}
|
||||
absoluteCookie := requireSessionCookie(t, absoluteLogin)
|
||||
idleLogin := loginSessionHTTP(t, first, idleEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.21:1234")
|
||||
if idleLogin.Code != http.StatusCreated {
|
||||
t.Fatalf("idle-expiry login status = %d, body=%s", idleLogin.Code, idleLogin.Body.String())
|
||||
}
|
||||
idleCookie := requireSessionCookie(t, idleLogin)
|
||||
|
||||
second := newSessionHTTPHarness(ctx, t, env)
|
||||
for _, cookie := range []*http.Cookie{absoluteCookie, idleCookie} {
|
||||
response := second.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.22:1234")
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("session did not survive an API handler restart: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
absoluteToken, err := domain.ParseSecretToken(absoluteCookie.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseSecretToken(absolute cookie) error = %v", err)
|
||||
}
|
||||
idleToken, err := domain.ParseSecretToken(idleCookie.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseSecretToken(idle cookie) error = %v", err)
|
||||
}
|
||||
now := second.clock.Now()
|
||||
absoluteHash := absoluteToken.Hash()
|
||||
idleHash := idleToken.Hash()
|
||||
if _, err := second.pool.Exec(ctx,
|
||||
`UPDATE sessions SET created_at = $1, last_seen_at = $1, expires_at = $2 WHERE token_hash = $3`,
|
||||
now.Add(-2*time.Second), now.Add(-time.Second), absoluteHash[:],
|
||||
); err != nil {
|
||||
t.Fatalf("expire absolute session: %v", err)
|
||||
}
|
||||
idleCreatedAt := now.Add(-env.Config.IdentitySessionIdleTimeout - 2*time.Second)
|
||||
if _, err := second.pool.Exec(ctx,
|
||||
`UPDATE sessions SET created_at = $1, last_seen_at = $2 WHERE token_hash = $3`,
|
||||
idleCreatedAt, now.Add(-env.Config.IdentitySessionIdleTimeout-time.Second), idleHash[:],
|
||||
); err != nil {
|
||||
t.Fatalf("age idle session: %v", err)
|
||||
}
|
||||
for _, cookie := range []*http.Cookie{absoluteCookie, idleCookie} {
|
||||
response := second.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.23:1234")
|
||||
requireSessionProblem(t, response, http.StatusUnauthorized, "unauthenticated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortIdleSessionRefreshesWhileActive(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout)
|
||||
defer cancel()
|
||||
harness := newSessionHTTPHarnessWithSettings(ctx, t, env, identity.SessionSettings{
|
||||
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit),
|
||||
EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
|
||||
IdleTimeout: time.Minute,
|
||||
AbsoluteLifetime: 2 * time.Minute,
|
||||
})
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
user := createSessionHTTPUser(ctx, t, harness, "short-idle@example.test", passwordHash, true)
|
||||
login := loginSessionHTTP(t, harness, user.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.30:1234")
|
||||
if login.Code != http.StatusCreated {
|
||||
t.Fatalf("login status = %d, body=%s", login.Code, login.Body.String())
|
||||
}
|
||||
cookie := requireSessionCookie(t, login)
|
||||
|
||||
harness.clock.Advance(40 * time.Second)
|
||||
firstActivity := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.31:1234")
|
||||
if firstActivity.Code != http.StatusOK {
|
||||
t.Fatalf("session expired before first activity: %d %s", firstActivity.Code, firstActivity.Body.String())
|
||||
}
|
||||
harness.clock.Advance(40 * time.Second)
|
||||
secondActivity := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.32:1234")
|
||||
if secondActivity.Code != http.StatusOK {
|
||||
t.Fatalf("session was not refreshed by activity: %d %s", secondActivity.Code, secondActivity.Body.String())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user