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.
117 lines
4.0 KiB
Go
117 lines
4.0 KiB
Go
// Command lambdamail-protocols is the entry point for the protocols service.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/emersion/go-imap/v2/imapserver"
|
|
gosmtp "github.com/emersion/go-smtp"
|
|
|
|
"lambdamail/protocols/internal/application/usecase"
|
|
"lambdamail/protocols/internal/health"
|
|
"lambdamail/protocols/internal/infrastructure/diskstorage"
|
|
"lambdamail/protocols/internal/infrastructure/postgres"
|
|
tlsprovider "lambdamail/protocols/internal/infrastructure/tls"
|
|
imappresentation "lambdamail/protocols/internal/presentation/imap"
|
|
smtppresentation "lambdamail/protocols/internal/presentation/smtp"
|
|
)
|
|
|
|
func main() {
|
|
ctx := context.Background()
|
|
|
|
pool, err := postgres.NewPool(ctx, os.Getenv("DATABASE_URL"))
|
|
if err != nil {
|
|
log.Fatalf("open database pool: %v", err)
|
|
}
|
|
defer pool.Close()
|
|
|
|
spoolDir := envOrDefault("PROTOCOLS_SPOOL_DIR", "/var/lambdamail/spool")
|
|
if err := os.MkdirAll(spoolDir, 0o755); err != nil {
|
|
log.Fatalf("create spool dir %s: %v", spoolDir, err)
|
|
}
|
|
|
|
mailboxes := postgres.NewMailboxRepository(pool)
|
|
blobs := diskstorage.NewLocalDiskBlobStorage(pool, spoolDir)
|
|
messages := postgres.NewInboundMessageRepository(pool)
|
|
useCase := usecase.NewProcessInboundEmailUseCase(mailboxes, blobs, messages)
|
|
|
|
certProvider, err := tlsprovider.NewLocalFileCertProvider(
|
|
os.Getenv("PROTOCOLS_CERT_PATH"),
|
|
os.Getenv("PROTOCOLS_KEY_PATH"),
|
|
)
|
|
if err != nil {
|
|
log.Printf("WARNING: could not load configured TLS certificate (%v) - falling back to an ephemeral self-signed certificate; this is degraded mode, not suitable for real deployments", err)
|
|
certProvider, err = tlsprovider.NewEphemeralSelfSignedCertProvider()
|
|
if err != nil {
|
|
log.Fatalf("generate fallback self-signed certificate: %v", err)
|
|
}
|
|
}
|
|
|
|
backend := smtppresentation.NewBackend(useCase)
|
|
smtpServer := gosmtp.NewServer(backend)
|
|
smtpServer.Addr = ":25"
|
|
smtpServer.Domain = envOrDefault("PRIMARY_MAIL_HOST", "mail.localhost")
|
|
smtpServer.MaxMessageBytes = 52428800 // 50 MB default; per-domain limit is a future iteration
|
|
smtpServer.MaxRecipients = 100
|
|
smtpServer.TLSConfig = &tls.Config{
|
|
GetCertificate: certProvider.GetCertificate,
|
|
MinVersion: tls.VersionTLS12,
|
|
CipherSuites: []uint16{
|
|
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
|
|
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
|
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
|
|
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
|
|
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
|
|
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
|
},
|
|
CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384},
|
|
}
|
|
|
|
go func() {
|
|
log.Printf("lambdamail-protocols SMTP listening on %s", smtpServer.Addr)
|
|
if err := smtpServer.ListenAndServe(); err != nil {
|
|
log.Fatalf("smtp serve: %v", err)
|
|
}
|
|
}()
|
|
|
|
authRepo := postgres.NewAuthRepository(pool)
|
|
imapFolders := postgres.NewImapFolderRepository(pool)
|
|
messageQuery := postgres.NewMessageQueryRepository(pool)
|
|
flagRepo := postgres.NewFlagRepository(pool)
|
|
blobReader := diskstorage.NewLocalDiskBlobReader(pool)
|
|
imapUseCase := usecase.NewImapSessionUseCase(authRepo, imapFolders, messageQuery, flagRepo, blobReader)
|
|
|
|
imapServer := imapserver.New(&imapserver.Options{
|
|
NewSession: func(c *imapserver.Conn) (imapserver.Session, *imapserver.GreetingData, error) {
|
|
return imappresentation.NewSession(c, imapUseCase)
|
|
},
|
|
TLSConfig: &tls.Config{GetCertificate: certProvider.GetCertificate, MinVersion: tls.VersionTLS12},
|
|
InsecureAuth: false,
|
|
})
|
|
|
|
go func() {
|
|
log.Printf("lambdamail-protocols IMAP listening on :143")
|
|
if err := imapServer.ListenAndServe(":143"); err != nil {
|
|
log.Fatalf("imap serve: %v", err)
|
|
}
|
|
}()
|
|
|
|
handler := health.Handler(func() error { return pool.Ping(ctx) })
|
|
addr := ":8080"
|
|
log.Printf("lambdamail-protocols health listening on %s", addr)
|
|
if err := http.ListenAndServe(addr, handler); err != nil {
|
|
log.Fatalf("serve: %v", err)
|
|
}
|
|
}
|
|
|
|
func envOrDefault(key, fallback string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return fallback
|
|
}
|