#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.
This commit is contained in:
1 parent
fc8bbaa3ce
commit
9fa19291d4
25 files changed
+1920
-1
No files matched your search
@@ -0,0 +1,254 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
package imappresentation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/emersion/go-imap/v2"
|
||||
"github.com/emersion/go-imap/v2/imapserver"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lambdamail/protocols/internal/application/port"
|
||||
"lambdamail/protocols/internal/application/usecase"
|
||||
)
|
||||
|
||||
type fakeAuthRepository struct {
|
||||
byAddress map[string]port.MailboxAuth
|
||||
}
|
||||
|
||||
func (f *fakeAuthRepository) FindByAddress(_ context.Context, address string) (*port.MailboxAuth, error) {
|
||||
rec, ok := f.byAddress[address]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &rec, nil
|
||||
}
|
||||
|
||||
type fakeImapFolderRepository struct {
|
||||
byName map[string]port.ImapFolderRecord
|
||||
}
|
||||
|
||||
func (f *fakeImapFolderRepository) ListFolders(_ context.Context, _ string) ([]port.ImapFolderRecord, error) {
|
||||
var out []port.ImapFolderRecord
|
||||
for _, rec := range f.byName {
|
||||
out = append(out, rec)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeImapFolderRepository) FindByName(_ context.Context, _ string, name string) (*port.ImapFolderRecord, error) {
|
||||
rec, ok := f.byName[name]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &rec, nil
|
||||
}
|
||||
|
||||
type fakeMessageQueryRepository struct {
|
||||
messages []port.MessageRecord
|
||||
}
|
||||
|
||||
func (f *fakeMessageQueryRepository) ListMessages(_ context.Context, _ string) ([]port.MessageRecord, error) {
|
||||
return f.messages, nil
|
||||
}
|
||||
|
||||
type fakeFlagRepository struct {
|
||||
lastFolderID string
|
||||
lastUID uint32
|
||||
lastOp port.FlagOp
|
||||
lastFlags []string
|
||||
|
||||
calls []fakeFlagCall
|
||||
}
|
||||
|
||||
type fakeFlagCall struct {
|
||||
folderID string
|
||||
uid uint32
|
||||
op port.FlagOp
|
||||
flags []string
|
||||
}
|
||||
|
||||
func (f *fakeFlagRepository) SetFlags(_ context.Context, folderID string, uid uint32, op port.FlagOp, flags []string) error {
|
||||
f.lastFolderID, f.lastUID, f.lastOp, f.lastFlags = folderID, uid, op, flags
|
||||
f.calls = append(f.calls, fakeFlagCall{folderID: folderID, uid: uid, op: op, flags: flags})
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeBlobReader struct {
|
||||
content map[uuid.UUID][]byte
|
||||
}
|
||||
|
||||
func (f *fakeBlobReader) ReadByID(_ context.Context, blobID uuid.UUID) ([]byte, error) {
|
||||
return f.content[blobID], nil
|
||||
}
|
||||
|
||||
// testPasswordHash/testPassword duplicate the constants from
|
||||
// internal/application/usecase/imap_session_test.go - a real Argon2id PHC
|
||||
// hash for "correct horse battery staple", generated once with
|
||||
// argon2id.CreateHash and hardcoded (see that file's Task 2 note for how
|
||||
// to generate it).
|
||||
const (
|
||||
testPassword = "correct horse battery staple"
|
||||
testPasswordHash = "$argon2id$v=19$m=65536,t=1,p=12$I88aUc0rZHHX+Bt+jX+4Ag$3jKTtg1khJjFo9az4iPvFLc3eKY8WKSFy/1YMXlKvSU"
|
||||
)
|
||||
|
||||
func newTestSession(auth *fakeAuthRepository, folders *fakeImapFolderRepository, messages *fakeMessageQueryRepository, flags *fakeFlagRepository, blobs *fakeBlobReader) imapserver.Session {
|
||||
uc := usecase.NewImapSessionUseCase(auth, folders, messages, flags, blobs)
|
||||
sess, _, err := NewSession(nil, uc)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return sess
|
||||
}
|
||||
|
||||
func TestSession_Login_SucceedsForCorrectCredentials(t *testing.T) {
|
||||
mailboxID := uuid.New()
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: mailboxID, PasswordHash: testPasswordHash},
|
||||
}}
|
||||
sess := newTestSession(auth, nil, nil, nil, nil)
|
||||
|
||||
if err := sess.Login("user@example.test", testPassword); err != nil {
|
||||
t.Fatalf("Login: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSession_Login_FailsForWrongPassword(t *testing.T) {
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: uuid.New(), PasswordHash: testPasswordHash},
|
||||
}}
|
||||
sess := newTestSession(auth, nil, nil, nil, nil)
|
||||
|
||||
err := sess.Login("user@example.test", "wrong")
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for wrong password, got nil")
|
||||
}
|
||||
var imapErr *imap.Error
|
||||
if !errors.As(err, &imapErr) {
|
||||
t.Fatalf("error is not an *imap.Error: %v", err)
|
||||
}
|
||||
if imapErr.Type != imap.StatusResponseTypeNo {
|
||||
t.Errorf("Type = %v, want StatusResponseTypeNo", imapErr.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSession_Select_ReturnsDataForKnownFolder(t *testing.T) {
|
||||
mailboxID := uuid.New()
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: mailboxID, PasswordHash: testPasswordHash},
|
||||
}}
|
||||
folders := &fakeImapFolderRepository{byName: map[string]port.ImapFolderRecord{
|
||||
"INBOX": {ID: "folder-1", Name: "INBOX", UIDNext: 5, UIDValidity: 999, NumMessages: 3},
|
||||
}}
|
||||
sess := newTestSession(auth, folders, &fakeMessageQueryRepository{}, &fakeFlagRepository{}, &fakeBlobReader{})
|
||||
if err := sess.Login("user@example.test", testPassword); err != nil {
|
||||
t.Fatalf("Login: %v", err)
|
||||
}
|
||||
|
||||
data, err := sess.Select("INBOX", &imap.SelectOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("Select: %v", err)
|
||||
}
|
||||
if data.UIDNext != 5 || data.UIDValidity != 999 || data.NumMessages != 3 {
|
||||
t.Errorf("data = %+v, want UIDNext=5 UIDValidity=999 NumMessages=3", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSession_Select_FailsForUnknownFolder(t *testing.T) {
|
||||
mailboxID := uuid.New()
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: mailboxID, PasswordHash: testPasswordHash},
|
||||
}}
|
||||
folders := &fakeImapFolderRepository{byName: map[string]port.ImapFolderRecord{}}
|
||||
sess := newTestSession(auth, folders, &fakeMessageQueryRepository{}, &fakeFlagRepository{}, &fakeBlobReader{})
|
||||
_ = sess.Login("user@example.test", testPassword)
|
||||
|
||||
_, err := sess.Select("Nonexistent", &imap.SelectOptions{})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for an unknown folder, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSession_Store_CallsFlagRepositoryWithCorrectArgs(t *testing.T) {
|
||||
mailboxID := uuid.New()
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: mailboxID, PasswordHash: testPasswordHash},
|
||||
}}
|
||||
folders := &fakeImapFolderRepository{byName: map[string]port.ImapFolderRecord{
|
||||
"INBOX": {ID: "folder-1", Name: "INBOX"},
|
||||
}}
|
||||
flags := &fakeFlagRepository{}
|
||||
messages := &fakeMessageQueryRepository{messages: []port.MessageRecord{{UID: 7}}}
|
||||
sess := newTestSession(auth, folders, messages, flags, &fakeBlobReader{})
|
||||
_ = sess.Login("user@example.test", testPassword)
|
||||
if _, err := sess.Select("INBOX", &imap.SelectOptions{}); err != nil {
|
||||
t.Fatalf("Select: %v", err)
|
||||
}
|
||||
|
||||
numSet := imap.UIDSetNum(7)
|
||||
err := sess.Store(nil, numSet, &imap.StoreFlags{
|
||||
Op: imap.StoreFlagsAdd,
|
||||
Silent: true,
|
||||
Flags: []imap.Flag{imap.FlagSeen},
|
||||
}, &imap.StoreOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("Store: %v", err)
|
||||
}
|
||||
if flags.lastFolderID != "folder-1" || flags.lastUID != 7 || flags.lastOp != port.FlagOpAdd {
|
||||
t.Errorf("flags recorded = folderID=%q uid=%d op=%v, want folder-1/7/FlagOpAdd", flags.lastFolderID, flags.lastUID, flags.lastOp)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSession_Store_HandlesUIDStarRange proves that UID STORE with a dynamic
|
||||
// open-ended range (e.g. "UID STORE 5:* +FLAGS (\Seen)", the "mark all as
|
||||
// read" operation) resolves against the folder's real message list instead
|
||||
// of relying on NumSet.Nums(), which returns (nil, false) for such ranges.
|
||||
func TestSession_Store_HandlesUIDStarRange(t *testing.T) {
|
||||
mailboxID := uuid.New()
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: mailboxID, PasswordHash: testPasswordHash},
|
||||
}}
|
||||
folders := &fakeImapFolderRepository{byName: map[string]port.ImapFolderRecord{
|
||||
"INBOX": {ID: "folder-1", Name: "INBOX"},
|
||||
}}
|
||||
flags := &fakeFlagRepository{}
|
||||
messages := &fakeMessageQueryRepository{messages: []port.MessageRecord{
|
||||
{UID: 5}, {UID: 7}, {UID: 9},
|
||||
}}
|
||||
sess := newTestSession(auth, folders, messages, flags, &fakeBlobReader{})
|
||||
_ = sess.Login("user@example.test", testPassword)
|
||||
if _, err := sess.Select("INBOX", &imap.SelectOptions{}); err != nil {
|
||||
t.Fatalf("Select: %v", err)
|
||||
}
|
||||
|
||||
// "5:*" - an open-ended dynamic range, the single most common real-world
|
||||
// STORE usage ("mark all as read").
|
||||
var numSet imap.UIDSet
|
||||
numSet.AddRange(5, 0)
|
||||
|
||||
err := sess.Store(nil, numSet, &imap.StoreFlags{
|
||||
Op: imap.StoreFlagsAdd,
|
||||
Silent: true,
|
||||
Flags: []imap.Flag{imap.FlagSeen},
|
||||
}, &imap.StoreOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("Store: %v", err)
|
||||
}
|
||||
|
||||
if len(flags.calls) != 3 {
|
||||
t.Fatalf("SetFlags called %d times, want 3 (all messages with UID >= 5)", len(flags.calls))
|
||||
}
|
||||
gotUIDs := map[uint32]bool{}
|
||||
for _, c := range flags.calls {
|
||||
gotUIDs[c.uid] = true
|
||||
if c.op != port.FlagOpAdd || c.folderID != "folder-1" {
|
||||
t.Errorf("call = %+v, want op=FlagOpAdd folderID=folder-1", c)
|
||||
}
|
||||
}
|
||||
for _, want := range []uint32{5, 7, 9} {
|
||||
if !gotUIDs[want] {
|
||||
t.Errorf("SetFlags was not called for UID %d", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSession_Store_AllowsSequenceNumberSet proves that plain (non-UID)
|
||||
// STORE, identified by a SeqSet rather than a UIDSet, is accepted and
|
||||
// resolved against the message at that sequence position - the
|
||||
// numSetIter-based design supports this the same way Fetch does, unlike the
|
||||
// old implementation, which rejected any non-UIDSet outright.
|
||||
func TestSession_Store_AllowsSequenceNumberSet(t *testing.T) {
|
||||
mailboxID := uuid.New()
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: mailboxID, PasswordHash: testPasswordHash},
|
||||
}}
|
||||
folders := &fakeImapFolderRepository{byName: map[string]port.ImapFolderRecord{
|
||||
"INBOX": {ID: "folder-1", Name: "INBOX"},
|
||||
}}
|
||||
flags := &fakeFlagRepository{}
|
||||
messages := &fakeMessageQueryRepository{messages: []port.MessageRecord{
|
||||
{UID: 5}, {UID: 7}, {UID: 9},
|
||||
}}
|
||||
sess := newTestSession(auth, folders, messages, flags, &fakeBlobReader{})
|
||||
_ = sess.Login("user@example.test", testPassword)
|
||||
if _, err := sess.Select("INBOX", &imap.SelectOptions{}); err != nil {
|
||||
t.Fatalf("Select: %v", err)
|
||||
}
|
||||
|
||||
// Sequence number 1 refers to the first message in the folder's list
|
||||
// (UID 5), not to "UID 1".
|
||||
numSet := imap.SeqSetNum(1)
|
||||
|
||||
err := sess.Store(nil, numSet, &imap.StoreFlags{
|
||||
Op: imap.StoreFlagsAdd,
|
||||
Silent: true,
|
||||
Flags: []imap.Flag{imap.FlagSeen},
|
||||
}, &imap.StoreOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("Store: %v", err)
|
||||
}
|
||||
|
||||
if len(flags.calls) != 1 {
|
||||
t.Fatalf("SetFlags called %d times, want 1", len(flags.calls))
|
||||
}
|
||||
if flags.calls[0].uid != 5 || flags.calls[0].folderID != "folder-1" || flags.calls[0].op != port.FlagOpAdd {
|
||||
t.Errorf("call = %+v, want uid=5 folderID=folder-1 op=FlagOpAdd", flags.calls[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestMatchFolders_FiltersByWildcardPattern exercises the folder-matching
|
||||
// logic extracted from Session.List (matchFolders). Session.List itself
|
||||
// cannot be driven directly in a unit test because *imapserver.ListWriter
|
||||
// has no exported constructor and can only be built by a live
|
||||
// *imapserver.Conn - so this test proves the matching/filtering behavior
|
||||
// that List delegates to, and fails if that logic regresses (e.g. matching
|
||||
// nothing, matching everything regardless of pattern, or mishandling the
|
||||
// hierarchy delimiter).
|
||||
func TestMatchFolders_FiltersByWildcardPattern(t *testing.T) {
|
||||
recs := []port.ImapFolderRecord{
|
||||
{ID: "1", Name: "INBOX"},
|
||||
{ID: "2", Name: "Archive"},
|
||||
{ID: "3", Name: "Archive/2024"},
|
||||
{ID: "4", Name: "Sent"},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
ref string
|
||||
patterns []string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "star matches everything including nested",
|
||||
ref: "",
|
||||
patterns: []string{"*"},
|
||||
want: []string{"INBOX", "Archive", "Archive/2024", "Sent"},
|
||||
},
|
||||
{
|
||||
name: "percent does not cross hierarchy delimiter",
|
||||
ref: "",
|
||||
patterns: []string{"%"},
|
||||
want: []string{"INBOX", "Archive", "Sent"},
|
||||
},
|
||||
{
|
||||
name: "exact literal match",
|
||||
ref: "",
|
||||
patterns: []string{"INBOX"},
|
||||
want: []string{"INBOX"},
|
||||
},
|
||||
{
|
||||
name: "multiple patterns are unioned",
|
||||
ref: "",
|
||||
patterns: []string{"INBOX", "Sent"},
|
||||
want: []string{"INBOX", "Sent"},
|
||||
},
|
||||
{
|
||||
name: "no pattern matches anything",
|
||||
ref: "",
|
||||
patterns: []string{"Nonexistent"},
|
||||
want: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := matchFolders(recs, tc.ref, tc.patterns)
|
||||
var gotNames []string
|
||||
for _, rec := range got {
|
||||
gotNames = append(gotNames, rec.Name)
|
||||
}
|
||||
if len(gotNames) != len(tc.want) {
|
||||
t.Fatalf("matchFolders() = %v, want %v", gotNames, tc.want)
|
||||
}
|
||||
wantSet := map[string]bool{}
|
||||
for _, w := range tc.want {
|
||||
wantSet[w] = true
|
||||
}
|
||||
for _, n := range gotNames {
|
||||
if !wantSet[n] {
|
||||
t.Errorf("matchFolders() included unexpected folder %q; got %v, want %v", n, gotNames, tc.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSession_List_UsesFolderRepository proves Session.List consults
|
||||
// useCase.ListFolders (via the fake ImapFolderRepository) rather than some
|
||||
// hardcoded set - a sanity check that List is actually wired to real data,
|
||||
// complementing the matchFolders unit test above and the full E2E LIST
|
||||
// assertion in imap_core_e2e_test.go which drives List through a real
|
||||
// *imapserver.ListWriter.
|
||||
func TestSession_List_UsesFolderRepository(t *testing.T) {
|
||||
mailboxID := uuid.New()
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: mailboxID, PasswordHash: testPasswordHash},
|
||||
}}
|
||||
folders := &fakeImapFolderRepository{byName: map[string]port.ImapFolderRecord{
|
||||
"INBOX": {ID: "folder-1", Name: "INBOX"},
|
||||
}}
|
||||
sess := newTestSession(auth, folders, &fakeMessageQueryRepository{}, &fakeFlagRepository{}, &fakeBlobReader{}).(*session)
|
||||
if err := sess.Login("user@example.test", testPassword); err != nil {
|
||||
t.Fatalf("Login: %v", err)
|
||||
}
|
||||
|
||||
recs, err := sess.useCase.ListFolders(context.Background(), sess.mailboxID)
|
||||
if err != nil {
|
||||
t.Fatalf("ListFolders: %v", err)
|
||||
}
|
||||
matched := matchFolders(recs, "", []string{"*"})
|
||||
if len(matched) != 1 || matched[0].Name != "INBOX" {
|
||||
t.Errorf("matched = %+v, want a single INBOX record", matched)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStubMethods_ReturnNotYetImplementedError(t *testing.T) {
|
||||
mailboxID := uuid.New()
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: mailboxID, PasswordHash: testPasswordHash},
|
||||
}}
|
||||
sess := newTestSession(auth, &fakeImapFolderRepository{}, &fakeMessageQueryRepository{}, &fakeFlagRepository{}, &fakeBlobReader{})
|
||||
_ = sess.Login("user@example.test", testPassword)
|
||||
|
||||
if err := sess.Create("Nonexistent", nil); err == nil {
|
||||
t.Error("Create: expected an error, got nil")
|
||||
}
|
||||
if _, err := sess.Search(imapserver.NumKindUID, &imap.SearchCriteria{}, &imap.SearchOptions{}); err == nil {
|
||||
t.Error("Search: expected an error, got nil")
|
||||
}
|
||||
if _, err := sess.Copy(imap.UIDSetNum(1), "Other"); err == nil {
|
||||
t.Error("Copy: expected an error, got nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Package imappresentation adapts github.com/emersion/go-imap/v2's
|
||||
// imapserver.Session interface to ImapSessionUseCase (Clean Architecture
|
||||
// layer 4 - PLAN.md section 3). This file holds every method NOT
|
||||
// implemented for real in this sub-project: each returns a clear IMAP NO
|
||||
// error, never a panic, never a silent no-op (see the design doc's
|
||||
// "all-or-nothing interface problem" section for why every one of these
|
||||
// 18 methods must exist even though only 7 do real work here).
|
||||
package imappresentation
|
||||
|
||||
import (
|
||||
"github.com/emersion/go-imap/v2"
|
||||
"github.com/emersion/go-imap/v2/imapserver"
|
||||
)
|
||||
|
||||
var errNotYetImplemented = &imap.Error{
|
||||
Type: imap.StatusResponseTypeNo,
|
||||
Text: "not yet implemented",
|
||||
}
|
||||
|
||||
func (s *session) Create(_ string, _ *imap.CreateOptions) error { return errNotYetImplemented }
|
||||
func (s *session) Delete(_ string) error { return errNotYetImplemented }
|
||||
func (s *session) Rename(_, _ string, _ *imap.RenameOptions) error { return errNotYetImplemented }
|
||||
func (s *session) Subscribe(_ string) error { return errNotYetImplemented }
|
||||
func (s *session) Unsubscribe(_ string) error { return errNotYetImplemented }
|
||||
func (s *session) Append(_ string, _ imap.LiteralReader, _ *imap.AppendOptions) (*imap.AppendData, error) {
|
||||
return nil, errNotYetImplemented
|
||||
}
|
||||
// Poll is called by imapserver before the status response of nearly every
|
||||
// command in the Authenticated/Selected state (see conn.go's c.poll), not
|
||||
// just in response to an explicit client IDLE/NOOP - returning an error here
|
||||
// would fail every real command (FETCH, STORE, ...), not just polling. This
|
||||
// sub-project doesn't push unsolicited EXISTS/EXPUNGE/FETCH updates (no
|
||||
// IDLE support - see Idle below), so reporting "no updates" via a nil
|
||||
// return is the correct, spec-compliant no-op, not a stub.
|
||||
func (s *session) Poll(_ *imapserver.UpdateWriter, _ bool) error { return nil }
|
||||
func (s *session) Idle(_ *imapserver.UpdateWriter, _ <-chan struct{}) error {
|
||||
return errNotYetImplemented
|
||||
}
|
||||
func (s *session) Expunge(_ *imapserver.ExpungeWriter, _ *imap.UIDSet) error {
|
||||
return errNotYetImplemented
|
||||
}
|
||||
func (s *session) Search(_ imapserver.NumKind, _ *imap.SearchCriteria, _ *imap.SearchOptions) (*imap.SearchData, error) {
|
||||
return nil, errNotYetImplemented
|
||||
}
|
||||
func (s *session) Copy(_ imap.NumSet, _ string) (*imap.CopyData, error) {
|
||||
return nil, errNotYetImplemented
|
||||
}
|
||||
Reference in new issue
Block a user