Files
LambdaMail/services/protocols/internal/presentation/imap/backend.go
T
Lucas Rayan 9fa19291d4 #4: implement F2 sub-project 1 - IMAP core (auth, LIST, SELECT, FETCH, STORE)
Adds a real :143 IMAP listener to the Go protocols service: a mailbox
owner authenticates over IMAP (Argon2id against mailboxes.password_hash,
enumeration-resistant per PLAN.md section 14.6), lists folders, selects
INBOX, fetches messages F1's SMTP path already persisted - including real
ENVELOPE/BODY[] built from the actual stored MIME bytes via go-imap/v2's
own ExtractEnvelope/ExtractBodySection helpers, not reconstructed from
denormalized columns - and sets/reads flags via STORE.

- ImapSessionUseCase orchestrates auth, folder listing/selection, message
  querying, and flag mutation against new Postgres repositories (auth,
  folders, message query, flags) and a local-disk blob reader.
- A github.com/emersion/go-imap/v2 (pinned v2.0.0-beta.8) Backend/Session
  implements 7 real methods (Login, List, Select, Unselect, Status, Fetch,
  Store) plus a correct no-op Poll; the other 10 of the interface's 18
  methods (Create/Delete/Rename/Subscribe/Unsubscribe/Append/Idle/Expunge/
  Search/Copy) are explicit stubs returning a clear "not yet implemented"
  IMAP error - SEARCH/EXPUNGE/COPY/MOVE, IDLE/CONDSTORE, mailbox
  management, and APPEND are separate follow-up sub-projects per the
  design doc's agreed ordering with the user.

Verified end-to-end with a real go-imap/v2 imapclient (embedded Postgres,
no Docker needed) driving Login -> Select -> Fetch -> Store -> List
against a message seeded through F1's real SMTP use case, proving true
SMTP-write/IMAP-read interop, not just isolated unit tests.

Built via 8 sequential tasks under subagent-driven development, each
independently reviewed, plus a final whole-branch review. Two real bugs
were found and fixed before merge, both exactly the kind unit tests with
fakes cannot catch:
- Store's UID-set resolution silently no-op'd on dynamic ranges like
  "UID STORE 1:*" (the common "mark all as read" operation) after an
  earlier draft bypassed the folder's real message list; restored to
  resolve against real messages via the same pattern Fetch already used
  correctly, with tests proving both dynamic ranges and non-UID STORE.
- go-imap/v2's server calls Session.Poll() implicitly before the status
  response of nearly every authenticated command (FETCH/STORE/SEARCH/
  APPEND/COPY), not just IDLE as assumed - a hard-stubbed Poll broke every
  real command through this path; fixed to a correct no-op.
- List had zero test coverage despite being committed scope; added unit
  tests for wildcard/delimiter matching plus a real E2E LIST assertion.

Known follow-up, not blocking: a pre-existing test-fixture hygiene gap
(hardcoded content_sha256 blob hashes with no cleanup, shared across
several Postgres integration test files including one new to this
branch) causes local-dev test collisions on repeated runs against a
persistent database - invisible to CI (fresh Postgres per run) but worth
a cleanup pass.
2026-07-23 20:34:48 -03:00

255 lines
7.6 KiB
Go

package imappresentation
import (
"bufio"
"bytes"
"context"
"errors"
"github.com/emersion/go-imap/v2"
"github.com/emersion/go-imap/v2/imapserver"
"github.com/emersion/go-message/textproto"
"lambdamail/protocols/internal/application/port"
"lambdamail/protocols/internal/application/usecase"
)
// session adapts imapserver.Session to ImapSessionUseCase.
type session struct {
useCase *usecase.ImapSessionUseCase
mailboxID string
selectedFolder *port.ImapFolderRecord
}
// NewSession is the imapserver.Options.NewSession callback.
func NewSession(_ *imapserver.Conn, uc *usecase.ImapSessionUseCase) (imapserver.Session, *imapserver.GreetingData, error) {
return &session{useCase: uc}, &imapserver.GreetingData{}, nil
}
func toIMAPError(err error) error {
switch {
case errors.Is(err, usecase.ErrAuthFailed):
return imapserver.ErrAuthFailed
case errors.Is(err, usecase.ErrNoSuchFolder):
return &imap.Error{Type: imap.StatusResponseTypeNo, Text: "No such mailbox"}
default:
return &imap.Error{Type: imap.StatusResponseTypeNo, Text: "Internal error"}
}
}
func (s *session) Close() error { return nil }
func (s *session) Login(username, password string) error {
mailboxID, err := s.useCase.Login(context.Background(), username, password)
if err != nil {
return toIMAPError(err)
}
s.mailboxID = mailboxID
return nil
}
func (s *session) Select(mailbox string, _ *imap.SelectOptions) (*imap.SelectData, error) {
rec, err := s.useCase.SelectFolder(context.Background(), s.mailboxID, mailbox)
if err != nil {
return nil, toIMAPError(err)
}
s.selectedFolder = rec
return &imap.SelectData{
NumMessages: rec.NumMessages,
UIDNext: imap.UID(rec.UIDNext),
UIDValidity: rec.UIDValidity,
}, nil
}
func (s *session) Unselect() error {
s.selectedFolder = nil
return nil
}
func (s *session) Status(mailbox string, options *imap.StatusOptions) (*imap.StatusData, error) {
rec, err := s.useCase.SelectFolder(context.Background(), s.mailboxID, mailbox)
if err != nil {
return nil, toIMAPError(err)
}
data := &imap.StatusData{Mailbox: mailbox}
if options.NumMessages {
n := rec.NumMessages
data.NumMessages = &n
}
if options.UIDNext {
data.UIDNext = imap.UID(rec.UIDNext)
}
if options.UIDValidity {
data.UIDValidity = rec.UIDValidity
}
return data, nil
}
func (s *session) List(w *imapserver.ListWriter, ref string, patterns []string, options *imap.ListOptions) error {
recs, err := s.useCase.ListFolders(context.Background(), s.mailboxID)
if err != nil {
return toIMAPError(err)
}
for _, rec := range matchFolders(recs, ref, patterns) {
if err := w.WriteList(&imap.ListData{Mailbox: rec.Name, Delim: '/'}); err != nil {
return err
}
}
return nil
}
// matchFolders filters recs down to those whose name matches at least one of
// patterns (relative to ref), using the same wildcard semantics as the LIST
// command (imapserver.MatchList: '*' matches any characters including the
// hierarchy delimiter, '%' matches any characters except the delimiter).
// Extracted from List so the matching/filtering logic can be unit-tested
// directly, since *imapserver.ListWriter cannot be constructed outside a
// live imapserver.Conn.
func matchFolders(recs []port.ImapFolderRecord, ref string, patterns []string) []port.ImapFolderRecord {
var out []port.ImapFolderRecord
for _, rec := range recs {
for _, pattern := range patterns {
if imapserver.MatchList(rec.Name, '/', ref, pattern) {
out = append(out, rec)
break
}
}
}
return out
}
// numSetIter walks every message in the selected folder in UID order,
// yielding its 1-based sequence number alongside it, and reports whether
// numSet contains that message (matching imapmemserver's own reference
// pattern of iterating known messages and calling NumSet.Contains, rather
// than trying to resolve "*" ranges ourselves).
func (s *session) numSetIter(numSet imap.NumSet, isUID bool, messages []port.MessageRecord, f func(seqNum uint32, msg port.MessageRecord)) {
for i, msg := range messages {
seqNum := uint32(i) + 1
var contains bool
switch set := numSet.(type) {
case imap.SeqSet:
contains = set.Contains(seqNum)
case imap.UIDSet:
contains = set.Contains(imap.UID(msg.UID))
}
if contains {
f(seqNum, msg)
}
}
}
func (s *session) Fetch(w *imapserver.FetchWriter, numSet imap.NumSet, options *imap.FetchOptions) error {
if s.selectedFolder == nil {
return &imap.Error{Type: imap.StatusResponseTypeNo, Text: "No mailbox selected"}
}
messages, err := s.useCase.FetchMessages(context.Background(), s.selectedFolder.ID)
if err != nil {
return toIMAPError(err)
}
var fetchErr error
s.numSetIter(numSet, options.UID, messages, func(seqNum uint32, msg port.MessageRecord) {
if fetchErr != nil {
return
}
respWriter := w.CreateMessage(seqNum)
fetchErr = s.writeFetchResponse(respWriter, msg, options)
})
return fetchErr
}
func (s *session) writeFetchResponse(w *imapserver.FetchResponseWriter, msg port.MessageRecord, options *imap.FetchOptions) error {
w.WriteUID(imap.UID(msg.UID))
if options.Flags {
flags := make([]imap.Flag, len(msg.Flags))
for i, f := range msg.Flags {
flags[i] = imap.Flag(f)
}
w.WriteFlags(flags)
}
if options.InternalDate {
w.WriteInternalDate(msg.ReceivedAt)
}
if options.RFC822Size {
w.WriteRFC822Size(msg.SizeBytes)
}
needsRaw := options.Envelope || options.BodyStructure != nil || len(options.BodySection) > 0 || len(options.BinarySection) > 0
if needsRaw {
raw, err := s.useCase.ReadBlob(context.Background(), msg.BlobID)
if err != nil {
return err
}
if options.Envelope {
header, err := textproto.ReadHeader(bufio.NewReader(bytes.NewReader(raw)))
if err != nil {
return err
}
w.WriteEnvelope(imapserver.ExtractEnvelope(header))
}
if options.BodyStructure != nil {
w.WriteBodyStructure(imapserver.ExtractBodyStructure(bytes.NewReader(raw)))
}
for _, bs := range options.BodySection {
buf := imapserver.ExtractBodySection(bytes.NewReader(raw), bs)
wc := w.WriteBodySection(bs, int64(len(buf)))
_, writeErr := wc.Write(buf)
closeErr := wc.Close()
if writeErr != nil {
return writeErr
}
if closeErr != nil {
return closeErr
}
}
}
return w.Close()
}
func (s *session) Store(w *imapserver.FetchWriter, numSet imap.NumSet, flags *imap.StoreFlags, options *imap.StoreOptions) error {
if s.selectedFolder == nil {
return &imap.Error{Type: imap.StatusResponseTypeNo, Text: "No mailbox selected"}
}
var op port.FlagOp
switch flags.Op {
case imap.StoreFlagsAdd:
op = port.FlagOpAdd
case imap.StoreFlagsDel:
op = port.FlagOpDel
case imap.StoreFlagsSet:
op = port.FlagOpSet
}
flagNames := make([]string, len(flags.Flags))
for i, f := range flags.Flags {
flagNames[i] = string(f)
}
messages, err := s.useCase.FetchMessages(context.Background(), s.selectedFolder.ID)
if err != nil {
return toIMAPError(err)
}
// Resolve numSet against the folder's real message list (same pattern as
// Fetch), rather than pulling raw values via NumSet.Nums(): dynamic
// ranges like "1:*" cannot be resolved without a concrete candidate to
// test against, and Nums() returns (nil, false) for them. This also
// naturally supports plain (non-UID) STORE via the SeqSet case.
var storeErr error
s.numSetIter(numSet, true, messages, func(_ uint32, msg port.MessageRecord) {
if storeErr != nil {
return
}
if err := s.useCase.SetFlags(context.Background(), s.selectedFolder.ID, msg.UID, op, flagNames); err != nil {
storeErr = toIMAPError(err)
}
})
if storeErr != nil {
return storeErr
}
if !flags.Silent {
return s.Fetch(w, numSet, &imap.FetchOptions{Flags: true, UID: true})
}
return nil
}