Files
LambdaMail/services/protocols/internal/presentation/http/router_test.go
T
Lucas RayanandClaude Opus 5 33d91fa247 #19: fix F1-F3 defects found auditing the phases against PLAN.md
Every fix here is a case where the code and the plan disagreed, and the
code was wrong.

Certificates (section 8.2, 8.4). The parser documented that it skipped
expired entries but never checked, so an expired certificate would be
served until every handshake failed. LastReload() only advanced when
acme.json changed - and it does not change for sixty days - which made
the timestamp risk R2 monitors indistinguishable from a watcher gone
blind. Expiry is now checked on every pass, LastReload records the check
and LastChange the swap, and the <7d/<24h alerts of section 8.4 exist.

ARC (section 5). buildArcSealer resolved the DKIM key at startup, before
runDnsReconciler had provisioned one. On a first boot ARC was disabled
until someone restarted the process, which the log even admitted while
offering no way for it to start. A LazySealer binds on first use instead.

Health (section 8.4). There was no degraded state at all. /health now
reports one - still 200, because restarting cannot fix a certificate
Traefik never issued.

Bounces. DSNs were sent From postmaster@lambdamail.local, a domain that
does not resolve, so the notification was itself undeliverable. They now
carry the configured mail host, a Message-ID, and Auto-Submitted so a
vacation responder cannot loop against them.

Fan-out atomicity (section 6.1). Persist ran one transaction per
recipient, so a failure halfway through an alias fan-out left earlier
recipients with a copy while the sender was told to retry - and the retry
delivered to them twice. PersistAll commits the whole delivery or none of
it. Verified against Postgres by reverting the repository to the old
behaviour and confirming the new test fails on it.

SMTP replies. The use case encoded replies in error text ("550 5.7.1 ...")
which the adapter re-parsed by prefix, so rewording a message could turn a
permanent refusal into a retry. SmtpRejection carries the decision and the
adapter renders it.

Repository tests. These only run with TEST_DATABASE_URL, which CI does
set - so the job was red: copy and expunge seeded a 68-character digest
into a CHAR(64) column, and three others used fixed digests that collide
with the UNIQUE index on any re-run. A shared testBlobDigest() helper
fixes both; the suite now passes twice in a row against one database.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 07:57:22 -03:00

106 lines
3.9 KiB
Go

package httppresentation
import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
appusecase "lambdamail/protocols/internal/application/usecase"
)
func TestRouter_MtaSts_Autoconfig_SecurityTxt_Ingest(t *testing.T) {
uc := appusecase.NewIngestReportsUseCase(nil)
router := NewRouter(uc, func() error { return nil })
// 1. Health
req := httptest.NewRequest(http.MethodGet, "/health", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("health status = %d", w.Code)
}
// 2. MTA-STS
req = httptest.NewRequest(http.MethodGet, "/.well-known/mta-sts.txt", nil)
req.Host = "mta-sts.example.test"
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "version: STSv1") {
t.Errorf("mta-sts response = %q", w.Body.String())
}
// 3. Thunderbird Autoconfig
req = httptest.NewRequest(http.MethodGet, "/mail/config-v1.1.xml", nil)
req.Host = "autoconfig.example.test"
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "<clientConfig") {
t.Errorf("autoconfig response = %q", w.Body.String())
}
// 4. Outlook Autodiscover
req = httptest.NewRequest(http.MethodPost, "/autodiscover/autodiscover.xml", nil)
req.Host = "autodiscover.example.test"
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "<Autodiscover") {
t.Errorf("autodiscover response = %q", w.Body.String())
}
// 5. Security.txt
req = httptest.NewRequest(http.MethodGet, "/.well-known/security.txt", nil)
req.Host = "example.test"
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Contact: mailto:security@example.test") {
t.Errorf("security.txt response = %q", w.Body.String())
}
// 6. Report Ingestion (DMARC)
dmarcPayload := `<?xml version="1.0"?><feedback><report_metadata><org_name>org</org_name><report_id>id</report_id><date_range><begin>1</begin><end>2</end></date_range></report_metadata><policy_published><domain>dom</domain></policy_published></feedback>`
req = httptest.NewRequest(http.MethodPost, "/api/v1/reports/dmarc", bytes.NewBufferString(dmarcPayload))
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"status":"ok"`) {
t.Errorf("dmarc ingest status = %d, body = %q", w.Code, w.Body.String())
}
}
// A certificate problem must be visible without taking the container down:
// restarting cannot fix a certificate Traefik never issued, so /health stays
// 200 and carries the degraded state instead (PLAN.md section 8.4).
func TestRouter_HealthReportsDegradedWithoutFailing(t *testing.T) {
router := NewRouter(appusecase.NewIngestReportsUseCase(nil), func() error { return nil })
router.SetDegradedCheck(func() error { return errors.New("self-signed certificate in use") })
req := httptest.NewRequest(http.MethodGet, "/health", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("degraded health status = %d, want 200 so the orchestrator does not restart-loop", w.Code)
}
if got := w.Header().Get("X-LambdaMail-Health"); got != "degraded" {
t.Errorf("X-LambdaMail-Health = %q, want degraded", got)
}
if !strings.Contains(w.Body.String(), "self-signed certificate in use") {
t.Errorf("the degraded body does not name the cause: %q", w.Body.String())
}
}
// A dependency that is actually down is a different state: that one must fail.
func TestRouter_HealthFailsWhenDependencyIsDown(t *testing.T) {
router := NewRouter(appusecase.NewIngestReportsUseCase(nil), func() error { return errors.New("database unreachable") })
req := httptest.NewRequest(http.MethodGet, "/health", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusServiceUnavailable {
t.Errorf("health status = %d, want 503", w.Code)
}
}