Files
LambdaMail/services/protocols/internal/infrastructure/postgres/mailbox_repository_test.go
T
Lucas Rayan e501cdc69e #2: implement F1 sub-project 1 - inbound SMTP listener with EML storage
Adds a real :25 SMTP listener to the Go protocols service, giving F1's
"Nucleo SMTP" milestone its first working sub-project: application,
infrastructure, and presentation layers on top of F0's domain-only
Clean Architecture.

- ProcessInboundEmailUseCase resolves recipients against Postgres and
  persists accepted mail (blob dedup by content hash, transactional
  UID allocation + outbox event, never sending 250 OK before durable
  commit per PLAN.md section 6.1).
- Postgres repositories via pgx/v5 (replacing lib/pq entirely).
- Local-disk blob storage with content-hash dedup, rename-before-commit
  ordering so a DB row can never reference a file that isn't actually
  on disk.
- A local-file TLS cert provider for STARTTLS, with an ephemeral
  self-signed fallback so a missing/misconfigured cert degrades
  gracefully instead of crash-looping the service (PLAN.md section 8.4).
- A github.com/emersion/go-smtp Backend/Session adapting real SMTP
  traffic to the use case: unknown recipients get 550 5.1.1 before
  DATA, duplicate RCPT TO for the same address is deduplicated, TLS is
  hardened to the project's required PFS-only cipher/curve policy.
- A dev-seed script and Makefile target for local testing.

Explicitly out of scope (separate follow-up sub-projects): alias
resolution, SPF/DKIM/DMARC/ARC verification, Rspamd/ClamAV, Submission
ports with SASL auth, DKIM signing, outbound delivery, and the real
Traefik acme.json cert watcher.

Verified live end-to-end via WSL Docker: the full compose stack (db,
redis, migrate, auth, storage, protocols, web) reaches healthy, and a
real swaks SMTP session is accepted and durably persisted with correct
sequential UIDs, while an unknown recipient is correctly rejected with
550 5.1.1 and zero rows persisted. Built via 10 sequential tasks under
subagent-driven development, each independently reviewed, plus a final
whole-branch review that caught and fixed a TLS-crash bug, a blob
commit-ordering bug, missing TLS hardening, and missing CI integration
coverage before merge.

Known follow-up, not blocking: email_messages' partition only covers
July 2026 and needs a partition-management job before 2026-08-01.
2026-07-23 08:41:31 -03:00

121 lines
4.2 KiB
Go

package postgres
import (
"context"
"os"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
// testPool returns a pool for TEST_DATABASE_URL, or skips the test if that
// env var is unset or the database is unreachable - these are integration
// tests against a real Postgres, not unit tests.
func testPool(t *testing.T) *pgxpool.Pool {
t.Helper()
dbURL := os.Getenv("TEST_DATABASE_URL")
if dbURL == "" {
t.Skip("TEST_DATABASE_URL not set - skipping Postgres integration test")
}
pool, err := NewPool(context.Background(), dbURL)
if err != nil {
t.Skipf("cannot connect to TEST_DATABASE_URL: %v", err)
}
if err := pool.Ping(context.Background()); err != nil {
t.Skipf("cannot ping TEST_DATABASE_URL: %v", err)
}
return pool
}
func TestMailboxRepository_FindActiveByAddress_ReturnsNilForUnknownAddress(t *testing.T) {
pool := testPool(t)
defer pool.Close()
repo := NewMailboxRepository(pool)
rec, err := repo.FindActiveByAddress(context.Background(), "definitely-not-seeded@example.invalid")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if rec != nil {
t.Errorf("rec = %+v, want nil for an address with no matching mailbox", rec)
}
}
func TestMailboxRepository_FindActiveByAddress_ReturnsRecordForSeededMailbox(t *testing.T) {
pool := testPool(t)
defer pool.Close()
ctx := context.Background()
domainID := uuid.New()
domainName := "repo-test-" + domainID.String() + ".invalid"
// NOTE: reusing a single placeholder ($2) for both `name` (CITEXT) and
// `punycode_name` (VARCHAR) makes Postgres's extended-protocol parameter
// type inference fail with "inconsistent types deduced for parameter $2"
// (SQLSTATE 42P08), confirmed via isolated repro against this same DB -
// see task-3-report.md. Using distinct placeholders for the same value
// avoids that false-negative without changing what's inserted.
_, err := pool.Exec(ctx, `INSERT INTO domains (id, name, punycode_name, max_message_bytes) VALUES ($1, $2, $3, 12345)`,
domainID, domainName, domainName)
if err != nil {
t.Fatalf("seed domain: %v", err)
}
defer pool.Exec(ctx, `DELETE FROM domains WHERE id = $1`, domainID)
mailboxID := uuid.New()
address := "user@repo-test-" + domainID.String() + ".invalid"
_, err = pool.Exec(ctx, `INSERT INTO mailboxes (id, domain_id, local_part, email_address, password_hash) VALUES ($1, $2, 'user', $3, '$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG')`,
mailboxID, domainID, address)
if err != nil {
t.Fatalf("seed mailbox: %v", err)
}
repo := NewMailboxRepository(pool)
rec, err := repo.FindActiveByAddress(ctx, address)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if rec == nil {
t.Fatal("rec = nil, want a record for the seeded active mailbox")
}
if rec.ID != mailboxID {
t.Errorf("ID = %v, want %v", rec.ID, mailboxID)
}
if rec.MaxMessageBytes != 12345 {
t.Errorf("MaxMessageBytes = %d, want 12345 (from the domain row)", rec.MaxMessageBytes)
}
}
func TestMailboxRepository_FindActiveByAddress_ExcludesInactiveMailbox(t *testing.T) {
pool := testPool(t)
defer pool.Close()
ctx := context.Background()
domainID := uuid.New()
domainName := "repo-test-inactive-" + domainID.String() + ".invalid"
// See NOTE above TestMailboxRepository_FindActiveByAddress_ReturnsRecordForSeededMailbox
// re: distinct placeholders for `name`/`punycode_name`.
_, err := pool.Exec(ctx, `INSERT INTO domains (id, name, punycode_name) VALUES ($1, $2, $3)`,
domainID, domainName, domainName)
if err != nil {
t.Fatalf("seed domain: %v", err)
}
defer pool.Exec(ctx, `DELETE FROM domains WHERE id = $1`, domainID)
address := "user@repo-test-inactive-" + domainID.String() + ".invalid"
_, err = pool.Exec(ctx, `INSERT INTO mailboxes (id, domain_id, local_part, email_address, password_hash, is_active) VALUES ($1, $2, 'user', $3, '$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG', false)`,
uuid.New(), domainID, address)
if err != nil {
t.Fatalf("seed mailbox: %v", err)
}
repo := NewMailboxRepository(pool)
rec, err := repo.FindActiveByAddress(ctx, address)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if rec != nil {
t.Errorf("rec = %+v, want nil - mailbox is_active=false must be excluded", rec)
}
}