diff --git a/server/src/nest/mail-ingest/mail-ingest-imap.client.ts b/server/src/nest/mail-ingest/mail-ingest-imap.client.ts index d9aca2bbb..ec503dcc7 100644 --- a/server/src/nest/mail-ingest/mail-ingest-imap.client.ts +++ b/server/src/nest/mail-ingest/mail-ingest-imap.client.ts @@ -24,6 +24,8 @@ export interface ImapSession { listAfter(lastUid: number): Promise; /** One mail's raw bytes; null for a uid that is gone. */ source(uid: number): Promise; + /** The folder's server path, or null if the folder does not exist. */ + findFolder(parts: readonly string[]): Promise; /** Makes the folder (made of these parts, in the server's own delimiter) unless it exists; answers its path. */ ensureFolder(parts: readonly string[]): Promise; move(uids: readonly number[], folder: string): Promise; @@ -69,6 +71,8 @@ async function vettedAddress(host: string): Promise { return verdict.resolvedIp; } +class ImapFolderError extends Error {} + class ImapFlowSession implements ImapSession { /** How many mails the open folder holds; an empty one is not asked for a range, which some servers refuse. */ private exists = 0; @@ -99,9 +103,35 @@ class ImapFlowSession implements ImapSession { return message && Buffer.isBuffer(message.source) ? message.source : null; } + async findFolder(parts: readonly string[]): Promise { + try { + const status = await this.client.status([...parts], { uidValidity: true }); + if (status) return status.path; + } catch (err) { + // ImapFlow uses LIST to confirm that a mailbox refused by STATUS is missing. + if (err instanceof Error && 'code' in err && err.code === 'NotFound') return null; + throw new ImapFolderError(`Could not check IMAP folder ${parts.join('/')}. ${describeImapFailure(err)}`, { + cause: err, + }); + } + throw new ImapFolderError(`The IMAP server did not return the status of folder ${parts.join('/')}`); + } + async ensureFolder(parts: readonly string[]): Promise { - const created = await this.client.mailboxCreate([...parts]); - return created.path; + const existing = await this.findFolder(parts); + if (existing !== null) return existing; + + try { + const created = await this.client.mailboxCreate([...parts]); + return created.path; + } catch (err) { + // The folder may have been created between the status check and CREATE. + const appeared = await this.findFolder(parts).catch(() => null); + if (appeared !== null) return appeared; + throw new ImapFolderError(`Could not create IMAP folder ${parts.join('/')}. ${describeImapFailure(err)}`, { + cause: err, + }); + } } async move(uids: readonly number[], folder: string): Promise { @@ -128,7 +158,7 @@ function dateOf(value: Date | string | undefined): Date | null { /** What an admin reads when the box cannot be read: the reason, never the password. */ export function describeImapFailure(err: unknown): string { - if (err instanceof SsrfBlockedError) return err.message; + if (err instanceof SsrfBlockedError || err instanceof ImapFolderError) return err.message; const failure = (err ?? {}) as { authenticationFailed?: boolean; code?: string; diff --git a/server/src/nest/mail-ingest/mail-ingest-imap.job.ts b/server/src/nest/mail-ingest/mail-ingest-imap.job.ts index f9622ca57..28a8c4e19 100644 --- a/server/src/nest/mail-ingest/mail-ingest-imap.job.ts +++ b/server/src/nest/mail-ingest/mail-ingest-imap.job.ts @@ -128,7 +128,9 @@ export class MailIngestImapJob implements OnApplicationBootstrap { * it waited {@link DEFER_DAYS} already, and is then given up the same way. */ private async retryDeferred(session: ImapSession, now: Date): Promise { - await session.open(await session.ensureFolder(DEFERRED_FOLDER)); + const folder = await session.findFolder(DEFERRED_FOLDER); + if (folder === null) return 0; + await session.open(folder); const due = (await session.listAfter(0)).slice(0, DEFERRED_PER_RUN); if (due.length === 0) return 0; const outcomes = await this.takeAll(session, due); diff --git a/server/tests/unit/nest/mail-ingest/mail-ingest-imap.client.test.ts b/server/tests/unit/nest/mail-ingest/mail-ingest-imap.client.test.ts index eea2bf6ab..1ac623c11 100644 --- a/server/tests/unit/nest/mail-ingest/mail-ingest-imap.client.test.ts +++ b/server/tests/unit/nest/mail-ingest/mail-ingest-imap.client.test.ts @@ -5,7 +5,7 @@ * newest mail IMAP always names, makes the processed folder, moves by uid and * says goodbye even over a broken connection. */ -import { MailIngestImapClient } from '../../../../src/nest/mail-ingest/mail-ingest-imap.client'; +import { describeImapFailure, MailIngestImapClient } from '../../../../src/nest/mail-ingest/mail-ingest-imap.client'; import { SsrfBlockedError } from '../../../../src/utils/ssrfGuard'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -16,7 +16,8 @@ const { checkSsrf, flow, ImapFlow } = vi.hoisted(() => { mailboxOpen: vi.fn(async () => ({ uidValidity: 77n, exists: 3 })), fetch: vi.fn(), fetchOne: vi.fn(), - mailboxCreate: vi.fn(async () => ({ path: 'TREK.processed', created: false })), + status: vi.fn(async (parts: string[]): Promise<{ path: string } | false> => ({ path: parts.join('.') })), + mailboxCreate: vi.fn(async () => ({ path: 'TREK.processed', created: true })), messageMove: vi.fn(async () => true), logout: vi.fn(async () => undefined), close: vi.fn(), @@ -43,6 +44,7 @@ const CONFIG = { } as const; const ARRIVED = new Date('2030-01-15T10:00:00Z'); +const missingFolder = () => Object.assign(new Error('Mailbox does not exist'), { code: 'NotFound' }); async function* messages(...uids: number[]) { for (const uid of uids) yield { uid, size: uid * 10, internalDate: uid === 42 ? 'not a date' : ARRIVED }; @@ -95,6 +97,7 @@ describe('MailIngestImapClient', () => { expect(await session.source(41)).toEqual(Buffer.from('raw')); expect(await session.source(43)).toBeNull(); + flow.status.mockRejectedValueOnce(missingFolder()); expect(await session.ensureFolder(['TREK', 'processed'])).toBe('TREK.processed'); expect(flow.mailboxCreate).toHaveBeenCalledWith(['TREK', 'processed']); await session.move([41, 42], 'TREK.processed'); @@ -103,6 +106,39 @@ describe('MailIngestImapClient', () => { expect(flow.messageMove).toHaveBeenCalledTimes(1); }); + it('uses the existing server path on consecutive connections without creating the folder', async () => { + flow.status + .mockResolvedValueOnce({ path: 'INBOX.TREK.processed' }) + .mockResolvedValueOnce({ path: 'INBOX.TREK.processed' }); + const client = new MailIngestImapClient(); + const first = await client.connect(CONFIG); + expect(await first.ensureFolder(['TREK', 'processed'])).toBe('INBOX.TREK.processed'); + const next = await client.connect(CONFIG); + expect(await next.ensureFolder(['TREK', 'processed'])).toBe('INBOX.TREK.processed'); + expect(flow.status).toHaveBeenCalledWith(['TREK', 'processed'], { uidValidity: true }); + expect(flow.mailboxCreate).not.toHaveBeenCalled(); + }); + + it('does not create when the server could not check the folder', async () => { + flow.status.mockResolvedValueOnce(false); + const session = await new MailIngestImapClient().connect(CONFIG); + await expect(session.ensureFolder(['TREK', 'processed'])).rejects.toThrow('status of folder TREK/processed'); + expect(flow.mailboxCreate).not.toHaveBeenCalled(); + }); + + it('uses the folder if it appeared during CREATE and reports the folder if creation really failed', async () => { + const refused = Object.assign(new Error('Command failed'), { responseText: 'CREATE failed' }); + const session = await new MailIngestImapClient().connect(CONFIG); + flow.status.mockRejectedValueOnce(missingFolder()); + flow.mailboxCreate.mockRejectedValueOnce(refused); + expect(await session.ensureFolder(['TREK', 'processed'])).toBe('TREK.processed'); + + flow.status.mockRejectedValueOnce(missingFolder()).mockRejectedValueOnce(missingFolder()); + flow.mailboxCreate.mockRejectedValueOnce(refused); + const reason = await session.ensureFolder(['TREK', 'processed']).catch(describeImapFailure); + expect(reason).toBe('Could not create IMAP folder TREK/processed. The IMAP server answered: CREATE failed'); + }); + it('does not ask an empty folder for a range', async () => { flow.mailboxOpen.mockResolvedValueOnce({ uidValidity: 5n, exists: 0 }); const session = await new MailIngestImapClient().connect(CONFIG); diff --git a/server/tests/unit/nest/mail-ingest/mail-ingest-transports.test.ts b/server/tests/unit/nest/mail-ingest/mail-ingest-transports.test.ts index 34f282e3d..bb3efd351 100644 --- a/server/tests/unit/nest/mail-ingest/mail-ingest-transports.test.ts +++ b/server/tests/unit/nest/mail-ingest/mail-ingest-transports.test.ts @@ -87,6 +87,7 @@ const session = { open: vi.fn(), listAfter: vi.fn(), source: vi.fn(), + findFolder: vi.fn(async (parts: readonly string[]): Promise => parts.join('.')), ensureFolder: vi.fn(async (parts: readonly string[]) => parts.join('.')), move: vi.fn(async () => undefined), close: vi.fn(async () => undefined), @@ -268,7 +269,11 @@ describe('the IMAP run', () => { }); it('moves nothing with an empty box, and touches nothing unless IMAP is the transport', async () => { + session.findFolder.mockResolvedValueOnce(null); expect(await job().tick(NOW)).toBe(0); + expect(session.findFolder).toHaveBeenCalledWith(['TREK', 'deferred']); + expect(session.open).toHaveBeenCalledExactlyOnceWith('INBOX'); + expect(session.ensureFolder).not.toHaveBeenCalled(); expect(session.move).not.toHaveBeenCalled(); expect(intake.receive).not.toHaveBeenCalled(); expect(processing.runSoon).not.toHaveBeenCalled(); @@ -283,6 +288,26 @@ describe('the IMAP run', () => { expect(imap.connect).not.toHaveBeenCalled(); }); + it('leaves mail and the cursor in place when folder creation fails, and retries on the next tick', async () => { + cursor.findCursor.mockResolvedValue({ uid_validity: 9, last_uid: 40 }); + session.listAfter.mockResolvedValueOnce([ref(41)]); + session.ensureFolder.mockRejectedValueOnce( + Object.assign(new Error('Command failed'), { responseText: 'CREATE failed' }), + ); + expect(await job().tick(NOW)).toBe(0); + expect(cursor.recordError).toHaveBeenCalledWith('imap', 'INBOX', 'The IMAP server answered: CREATE failed'); + expect(cursor.recordOk).not.toHaveBeenCalled(); + expect(session.move).not.toHaveBeenCalled(); + expect(cursor.releaseLease).toHaveBeenCalled(); + + boxes([ref(41)]); + intake.receive.mockResolvedValueOnce({ status: 'duplicate' }); + expect(await job().tick(NOW)).toBe(0); + expect(session.listAfter).toHaveBeenNthCalledWith(2, 40); + expect(session.move).toHaveBeenCalledExactlyOnceWith([41], 'TREK.processed'); + expect(cursor.recordOk).toHaveBeenCalledWith('imap', 'INBOX', expect.any(String), { uidValidity: 9, lastUid: 41 }); + }); + it('records why a run failed for the status card, and keeps the cursor where it was', async () => { imap.connect.mockRejectedValueOnce(Object.assign(new Error('Command failed'), { authenticationFailed: true })); expect(await job().tick(NOW)).toBe(0);