Files
LambdaMail/services/protocols/internal/application/usecase/inbound_system_message_test.go
T
Lucas RayanandClaude Opus 5 d8e2de2e11 #24: deliver what the composer wrote, keep a copy, and store drafts
Four faults, all in the path between the compose screen and the mailbox.

**Every message sent from the webmail had an empty body.** The HTTP handler
read a field named "body"; the composer has always sent "html". The two never
matched, so the payload handed to the queue contained headers and nothing
else. The handler now reads html and text, and still accepts body so an older
client is not broken. Sending was otherwise working, which is why this went
unnoticed: the mail left, it just said nothing.

**Bcc was discarded.** The field was absent from the request struct and from
ComposeInput, so a blind copy typed into the webmail reached nobody. It now
joins the envelope recipients and is deliberately kept out of the headers,
which is what makes it blind.

**HTML was labelled text/plain.** Even once the body was carried, the composer
produces markup and the message declared text/plain, so a recipient would see
raw tags. Messages with HTML now go out as multipart/alternative with a
plain-text part derived from the markup and ordered first per RFC 2046 5.1.4.
An empty or missing text alternative is itself a spam signal.

**Sent mail left no trace.** Nothing wrote to the Sent folder, so a delivered
message vanished from the sender's view entirely. A copy is now filed after
the message is durably queued - not before, or a send refused by the rate
limit would still leave a copy - reusing the inbound persistence path so it
gets a real IMAP UID and appears over IMAP too. A failure to file is logged
and swallowed: the mail is already on its way, and reporting failure would
invite the user to send it twice.

**Drafts were never saved.** There was no endpoint at all. The composer showed
"draft saved automatically" from a setTimeout with no request behind it, so
closing the tab lost the message the screen had just promised was safe. Adds
POST /api/v1/mail/draft, storing the draft as a whole RFC 5322 message in the
Drafts folder, and debounces the composer onto it.

The composer also navigated to Sent whether or not the send succeeded, which
is how a rejected message disappears silently. It now reports the error and
stays put.

**Delay notifications were being filed as spam.** A DSN this server writes is
injected through the same inbound path as mail from the internet, but without
a client IP - so SPF can only be "none" - and its bounce-shaped content scores
highly. The warning telling you your mail was delayed landed in your own Junk
folder. Messages the server generates itself now skip content scanning; the
exemption is narrow, and a test covers that ordinary mail is still scanned so
this cannot become a way past the filter. The DSN also declared
Auto-Submitted: auto-replied, which belongs to vacation responders; a delivery
report is auto-generated (RFC 3834 section 5), and filters read that header.

Not fixed here, because it is not a code fault: outbound port 25 is blocked by
the provider, which is what the delay notification was reporting
("i/o timeout" to Google's MX - a timeout, not a refusal, is the signature of
a block). Receiving is unaffected and queued mail keeps retrying. Documented
with the two ways out, including the relay path, which is verified working
code rather than another stub.

Verified: 22 Go packages pass, 5 new compose tests and 3 for the DSN handling.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 19:56:59 -03:00

111 lines
3.9 KiB
Go

package usecase
import (
"bytes"
"context"
"strings"
"testing"
"github.com/google/uuid"
"lambdamail/protocols/internal/application/port"
"lambdamail/protocols/internal/domain/valueobject"
)
// junkingScanner files everything as spam, standing in for the real scanner
// scoring a bounce-shaped message with no SPF result.
type junkingScanner struct{ called bool }
func (s *junkingScanner) Scan(_ context.Context, _ port.ScanInput) (*valueobject.ScanResult, error) {
s.called = true
return &valueobject.ScanResult{
Verdict: valueobject.ScanVerdictSpamJunk,
Score: 12.0,
Symbols: map[string]float64{},
HeadersToAdd: map[string]string{},
}, nil
}
// A delivery status notification this server wrote itself must never be
// spam-filtered.
//
// The report goes through the same inbound path as mail from the internet, but
// it is injected with no client IP, so SPF can only be "none" and the content
// looks exactly like a bounce. The result was that "your message to X was
// delayed" arrived in the sender's own Junk folder - the single notification
// they most need to see, filed where they will not look.
func TestSystemGeneratedMessageIsNotSpamFiltered(t *testing.T) {
blobs := &stubBlobStorage{ref: port.BlobRef{ID: uuid.New(), SHA256: "dsn", SizeBytes: 10}}
messages := &recordingMessageRepository{}
scanner := &junkingScanner{}
uc := NewProcessInboundEmailUseCase(nil, blobs, messages)
uc.SetScanner(scanner)
err := uc.Handle(context.Background(), ProcessInboundEmailInput{
Sender: "postmaster@mail.example.test",
Recipients: []port.MailboxRecord{{ID: uuid.New(), MaxMessageBytes: 100000}},
RecipientAddresses: []string{"user@example.test"},
Body: bytes.NewReader([]byte("Subject: Delivery Delay Notification\r\n\r\ndelayed\r\n")),
SystemGenerated: true,
})
if err != nil {
t.Fatalf("Handle: %v", err)
}
if scanner.called {
t.Error("the scanner ran on a message this server generated itself")
}
if len(messages.persisted) != 1 {
t.Fatalf("want 1 persisted message, got %d", len(messages.persisted))
}
if folder := messages.persisted[0].TargetFolderName; folder == "Junk" {
t.Errorf("a postmaster notification was filed as Junk")
}
}
// The exemption must be narrow: anything actually received from a peer is
// still scanned, or marking a message "system generated" would be a way past
// the spam filter.
func TestOrdinaryMessageIsStillScanned(t *testing.T) {
blobs := &stubBlobStorage{ref: port.BlobRef{ID: uuid.New(), SHA256: "x", SizeBytes: 10}}
messages := &recordingMessageRepository{}
scanner := &junkingScanner{}
uc := NewProcessInboundEmailUseCase(nil, blobs, messages)
uc.SetScanner(scanner)
err := uc.Handle(context.Background(), ProcessInboundEmailInput{
Sender: "stranger@spam.test",
Recipients: []port.MailboxRecord{{ID: uuid.New(), MaxMessageBytes: 100000}},
RecipientAddresses: []string{"user@example.test"},
Body: bytes.NewReader([]byte("Subject: buy pills\r\n\r\nspam\r\n")),
})
if err != nil {
t.Fatalf("Handle: %v", err)
}
if !scanner.called {
t.Fatal("an ordinary inbound message skipped the scanner")
}
if messages.persisted[0].TargetFolderName != "Junk" {
t.Errorf("a message the scanner called spam was not filed as Junk, got %q",
messages.persisted[0].TargetFolderName)
}
}
// A DSN announces itself as automatic so the far side's vacation responder
// does not answer it. RFC 3834 section 5 distinguishes the two values, and
// filters read the header.
func TestDsnDeclaresItselfAutoGenerated(t *testing.T) {
payload, loop := valueobject.BuildDsnReport(
valueobject.DsnActionDelayed, "mail.example.test",
"sender@example.test", "far@remote.test", "abc", "timeout",
)
if loop {
t.Fatal("unexpected loop prevention")
}
if !strings.Contains(string(payload), "Auto-Submitted: auto-generated") {
t.Errorf("a delivery report is auto-generated, not auto-replied:\n%s", payload)
}
}