#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,20 @@
|
||||
package port
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// MailboxAuth is the subset of mailbox data needed to verify a login.
|
||||
type MailboxAuth struct {
|
||||
ID uuid.UUID
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
// AuthRepository resolves a login address to its stored credential.
|
||||
type AuthRepository interface {
|
||||
// FindByAddress returns nil, nil (not an error) when no active mailbox
|
||||
// with an active domain matches address.
|
||||
FindByAddress(ctx context.Context, address string) (*MailboxAuth, error)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package port
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// BlobReader reads a previously stored message's full raw bytes.
|
||||
type BlobReader interface {
|
||||
ReadByID(ctx context.Context, blobID uuid.UUID) ([]byte, error)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package port
|
||||
|
||||
import "context"
|
||||
|
||||
// FlagOp mirrors imap.StoreFlagsOp without importing the imap package here
|
||||
// (this port stays framework-free).
|
||||
type FlagOp int
|
||||
|
||||
const (
|
||||
FlagOpAdd FlagOp = iota
|
||||
FlagOpDel
|
||||
FlagOpSet
|
||||
)
|
||||
|
||||
// FlagRepository mutates a message's IMAP flags (STORE).
|
||||
type FlagRepository interface {
|
||||
// SetFlags applies op with flags to the message identified by
|
||||
// (folderID, uid). Add/Del insert/delete individual message_flags rows;
|
||||
// Set replaces the message's full flag set in one transaction.
|
||||
SetFlags(ctx context.Context, folderID string, uid uint32, op FlagOp, flags []string) error
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package port
|
||||
|
||||
import "context"
|
||||
|
||||
// ImapFolderRecord is the IMAP-relevant subset of a folder row.
|
||||
type ImapFolderRecord struct {
|
||||
ID string
|
||||
Name string
|
||||
UIDNext uint32
|
||||
UIDValidity uint32
|
||||
NumMessages uint32
|
||||
}
|
||||
|
||||
// ImapFolderRepository resolves a mailbox's folders for LIST and SELECT.
|
||||
type ImapFolderRepository interface {
|
||||
ListFolders(ctx context.Context, mailboxID string) ([]ImapFolderRecord, error)
|
||||
// FindByName returns nil, nil (not an error) when no folder with that
|
||||
// name exists for the mailbox.
|
||||
FindByName(ctx context.Context, mailboxID, name string) (*ImapFolderRecord, error)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package port
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// MessageRecord is one message's IMAP-relevant data.
|
||||
type MessageRecord struct {
|
||||
UID uint32
|
||||
BlobID uuid.UUID
|
||||
SizeBytes int64
|
||||
ReceivedAt time.Time
|
||||
Flags []string
|
||||
}
|
||||
|
||||
// MessageQueryRepository lists a folder's messages for FETCH.
|
||||
type MessageQueryRepository interface {
|
||||
// ListMessages returns every message in folderID, ordered by UID
|
||||
// ascending. The caller derives IMAP sequence numbers from this order
|
||||
// (row N is sequence number N+1) - safe because this sub-project never
|
||||
// expunges a message, so sequence numbers never need remapping.
|
||||
ListMessages(ctx context.Context, folderID string) ([]MessageRecord, error)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/alexedwards/argon2id"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lambdamail/protocols/internal/application/port"
|
||||
)
|
||||
|
||||
// ErrAuthFailed is returned by Login for any credential problem - unknown
|
||||
// address, wrong password, or (once AuthRepository filters it) an inactive
|
||||
// mailbox/domain. Deliberately the same error in every case: distinguishing
|
||||
// them would let a client enumerate valid addresses (PLAN.md section 14.6).
|
||||
var ErrAuthFailed = errors.New("imap session: authentication failed")
|
||||
|
||||
// ErrNoSuchFolder is returned by SelectFolder when the named folder doesn't exist.
|
||||
var ErrNoSuchFolder = errors.New("imap session: no such folder")
|
||||
|
||||
// ImapSessionUseCase implements the read/auth half of PLAN.md section 3's
|
||||
// HandleImapCommandUseCase (this sub-project's scope: LOGIN, LIST, SELECT,
|
||||
// FETCH, STORE; SEARCH/EXPUNGE/IDLE/MOVE land in later sub-projects).
|
||||
type ImapSessionUseCase struct {
|
||||
auth port.AuthRepository
|
||||
folders port.ImapFolderRepository
|
||||
messages port.MessageQueryRepository
|
||||
flags port.FlagRepository
|
||||
blobs port.BlobReader
|
||||
}
|
||||
|
||||
func NewImapSessionUseCase(auth port.AuthRepository, folders port.ImapFolderRepository, messages port.MessageQueryRepository, flags port.FlagRepository, blobs port.BlobReader) *ImapSessionUseCase {
|
||||
return &ImapSessionUseCase{auth: auth, folders: folders, messages: messages, flags: flags, blobs: blobs}
|
||||
}
|
||||
|
||||
func (uc *ImapSessionUseCase) Login(ctx context.Context, address, password string) (string, error) {
|
||||
rec, err := uc.auth.FindByAddress(ctx, address)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if rec == nil {
|
||||
return "", ErrAuthFailed
|
||||
}
|
||||
match, err := argon2id.ComparePasswordAndHash(password, rec.PasswordHash)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !match {
|
||||
return "", ErrAuthFailed
|
||||
}
|
||||
return rec.ID.String(), nil
|
||||
}
|
||||
|
||||
func (uc *ImapSessionUseCase) ListFolders(ctx context.Context, mailboxID string) ([]port.ImapFolderRecord, error) {
|
||||
return uc.folders.ListFolders(ctx, mailboxID)
|
||||
}
|
||||
|
||||
func (uc *ImapSessionUseCase) SelectFolder(ctx context.Context, mailboxID, name string) (*port.ImapFolderRecord, error) {
|
||||
rec, err := uc.folders.FindByName(ctx, mailboxID, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rec == nil {
|
||||
return nil, ErrNoSuchFolder
|
||||
}
|
||||
return rec, nil
|
||||
}
|
||||
|
||||
func (uc *ImapSessionUseCase) FetchMessages(ctx context.Context, folderID string) ([]port.MessageRecord, error) {
|
||||
return uc.messages.ListMessages(ctx, folderID)
|
||||
}
|
||||
|
||||
func (uc *ImapSessionUseCase) ReadBlob(ctx context.Context, blobID uuid.UUID) ([]byte, error) {
|
||||
return uc.blobs.ReadByID(ctx, blobID)
|
||||
}
|
||||
|
||||
func (uc *ImapSessionUseCase) SetFlags(ctx context.Context, folderID string, uid uint32, op port.FlagOp, flags []string) error {
|
||||
return uc.flags.SetFlags(ctx, folderID, uid, op, flags)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"lambdamail/protocols/internal/application/port"
|
||||
)
|
||||
|
||||
const (
|
||||
testPassword = "correct horse battery staple"
|
||||
testPasswordHash = "$argon2id$v=19$m=65536,t=1,p=12$I88aUc0rZHHX+Bt+jX+4Ag$3jKTtg1khJjFo9az4iPvFLc3eKY8WKSFy/1YMXlKvSU"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func TestImapSessionUseCase_Login_SucceedsForCorrectPassword(t *testing.T) {
|
||||
mailboxID := uuid.New()
|
||||
// PHC hash for password "correct horse battery staple", generated with argon2id.CreateHash.
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: mailboxID, PasswordHash: testPasswordHash},
|
||||
}}
|
||||
uc := NewImapSessionUseCase(auth, nil, nil, nil, nil)
|
||||
|
||||
gotID, err := uc.Login(context.Background(), "user@example.test", testPassword)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if gotID != mailboxID.String() {
|
||||
t.Errorf("mailboxID = %q, want %q", gotID, mailboxID.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestImapSessionUseCase_Login_FailsForWrongPassword(t *testing.T) {
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{
|
||||
"user@example.test": {ID: uuid.New(), PasswordHash: testPasswordHash},
|
||||
}}
|
||||
uc := NewImapSessionUseCase(auth, nil, nil, nil, nil)
|
||||
|
||||
_, err := uc.Login(context.Background(), "user@example.test", "wrong-password")
|
||||
if !errors.Is(err, ErrAuthFailed) {
|
||||
t.Fatalf("error = %v, want ErrAuthFailed", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImapSessionUseCase_Login_FailsForUnknownAddress(t *testing.T) {
|
||||
auth := &fakeAuthRepository{byAddress: map[string]port.MailboxAuth{}}
|
||||
uc := NewImapSessionUseCase(auth, nil, nil, nil, nil)
|
||||
|
||||
_, err := uc.Login(context.Background(), "nobody@example.test", "anything")
|
||||
if !errors.Is(err, ErrAuthFailed) {
|
||||
t.Fatalf("error = %v, want ErrAuthFailed (never a distinct \"no such user\" error - PLAN.md section 14.6)", err)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func TestImapSessionUseCase_SelectFolder_ReturnsRecordForExistingFolder(t *testing.T) {
|
||||
folders := &fakeImapFolderRepository{byName: map[string]port.ImapFolderRecord{
|
||||
"INBOX": {ID: "folder-1", Name: "INBOX", UIDNext: 3, UIDValidity: 1000, NumMessages: 2},
|
||||
}}
|
||||
uc := NewImapSessionUseCase(nil, folders, nil, nil, nil)
|
||||
|
||||
rec, err := uc.SelectFolder(context.Background(), "mailbox-1", "INBOX")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if rec.ID != "folder-1" || rec.UIDNext != 3 {
|
||||
t.Errorf("rec = %+v, want folder-1 with UIDNext 3", rec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImapSessionUseCase_SelectFolder_ReturnsErrNoSuchFolderWhenMissing(t *testing.T) {
|
||||
folders := &fakeImapFolderRepository{byName: map[string]port.ImapFolderRecord{}}
|
||||
uc := NewImapSessionUseCase(nil, folders, nil, nil, nil)
|
||||
|
||||
_, err := uc.SelectFolder(context.Background(), "mailbox-1", "Nonexistent")
|
||||
if !errors.Is(err, ErrNoSuchFolder) {
|
||||
t.Fatalf("error = %v, want ErrNoSuchFolder", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user