Skip to content

The open alternative to Salesforce, designed for AI.

messaging: fix IMAP rare edge case for non RFC compliant servers (#24888)

neo773174a68a5f88b
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/imap/services/imap-sync.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/imap/services/imap-sync.service.ts
index 734bb56a01a..ac108585c42 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/imap/services/imap-sync.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/imap/services/imap-sync.service.ts
@@ -6,7 +6,6 @@ import {
MessageImportDriverException,
MessageImportDriverExceptionCode,
} from 'src/modules/messaging/message-import-manager/drivers/exceptions/message-import-driver.exception';
-import { canUseQresync } from 'src/modules/messaging/message-import-manager/drivers/imap/utils/can-use-qresync.util';
import { type MailboxState } from 'src/modules/messaging/message-import-manager/drivers/imap/utils/extract-mailbox-state.util';
import { type ImapSyncCursor } from 'src/modules/messaging/message-import-manager/drivers/imap/utils/parse-sync-cursor.util';
@@ -30,7 +29,6 @@ export class ImapSyncService {
client,
previousCursor,
mailboxState,
- folderPath,
);
return { messageUids };
@@ -60,70 +58,21 @@ export class ImapSyncService {
client: ImapFlow,
previousCursor: ImapSyncCursor | null,
mailboxState: MailboxState,
- folderPath: string,
): Promise<number[]> {
const lastSyncedUid = previousCursor?.highestUid ?? 0;
const { maxUid } = mailboxState;
- if (canUseQresync(client, previousCursor, mailboxState)) {
- this.logger.debug(`Using QRESYNC for folder ${folderPath}`);
-
- try {
- return await this.fetchWithQresync(
- client,
- lastSyncedUid,
- BigInt(previousCursor!.modSeq!),
- );
- } catch (error) {
- this.logger.warn(
- `QRESYNC failed for ${folderPath}, falling back to UID range: ${error.message}`,
- );
- }
- }
-
- this.logger.debug(`Using UID range fetch for folder ${folderPath}`);
-
- return this.fetchWithUidRange(client, lastSyncedUid, maxUid);
- }
-
- private async fetchWithUidRange(
- client: ImapFlow,
- lastSyncedUid: number,
- highestAvailableUid: number,
- ): Promise<number[]> {
- if (lastSyncedUid >= highestAvailableUid) {
+ if (lastSyncedUid >= maxUid) {
return [];
}
- const uidRange = `${lastSyncedUid + 1}:${highestAvailableUid}`;
+ const uidRange = `${lastSyncedUid + 1}:${maxUid}`;
const uids = await client.search({ uid: uidRange }, { uid: true });
- if (!uids || !Array.isArray(uids)) {
- return [];
- }
-
- return uids;
- }
-
- private async fetchWithQresync(
- client: ImapFlow,
- lastSyncedUid: number,
- lastModSeq: bigint,
- ): Promise<number[]> {
- const uids = await client.search(
- {
- modseq: lastModSeq + BigInt(1),
- uid: `${lastSyncedUid + 1}:*`,
- },
- { uid: true },
- );
-
- if (!uids || !Array.isArray(uids) || !uids.length) {
+ if (!Array.isArray(uids)) {
return [];
}
- this.logger.debug(`QRESYNC found ${uids.length} new/modified messages`);
-
return uids;
}
}
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/imap/utils/can-use-qresync.util.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/imap/utils/can-use-qresync.util.ts
deleted file mode 100644
index b7ce8d7521f..00000000000
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/imap/utils/can-use-qresync.util.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { type ImapFlow } from 'imapflow';
-
-import { type MailboxState } from './extract-mailbox-state.util';
-import { type ImapSyncCursor } from './parse-sync-cursor.util';
-
-export const canUseQresync = (
- client: ImapFlow,
- previousCursor: ImapSyncCursor | null,
- mailboxState: MailboxState,
-): boolean => {
- const supportsQresync = client.capabilities.has('QRESYNC');
- const hasModSeq = previousCursor?.modSeq !== undefined;
- const hasServerModSeq = mailboxState.highestModSeq !== undefined;
- const uidValidityMatches =
- (previousCursor?.uidValidity ?? 0) === mailboxState.uidValidity ||
- previousCursor?.uidValidity === 0;
-
- return supportsQresync && hasModSeq && hasServerModSeq && uidValidityMatches;
-};
diff --git a/packages/twenty-server/test/integration/imap/suites/imap-folder-discovery.integration-spec.ts b/packages/twenty-server/test/integration/imap/suites/imap-folder-discovery.integration-spec.ts
index 4beab34ca2a..28a0b993783 100644
--- a/packages/twenty-server/test/integration/imap/suites/imap-folder-discovery.integration-spec.ts
+++ b/packages/twenty-server/test/integration/imap/suites/imap-folder-discovery.integration-spec.ts
@@ -4,25 +4,22 @@ import { isNonEmptyString } from '@sniptt/guards';
import { deleteConnectedAccount } from 'test/integration/metadata/suites/connected-account/utils/delete-connected-account.util';
import { updateConfigVariable } from 'test/integration/twenty-config/utils/update-config-variable.util';
-import { connectGreenmailImapAccount } from 'test/integration/utils/connect-greenmail-imap-account.util';
+import { connectDovecotImapAccount } from 'test/integration/utils/connect-dovecot-imap-account.util';
import { queryMessageFolders } from 'test/integration/utils/query-messaging.util';
import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
-import { type GreenmailServer } from 'test/integration/utils/start-greenmail-container.util';
+import { type DovecotServer } from 'test/integration/utils/start-dovecot-container.util';
-const PASSWORD = 'greenmail-password';
-
-// GreenMail registers a declared user under the local part of its address, so
-// that is the login, while the channel keeps the full address as its handle.
+const PASSWORD = 'dovecot-password';
const HANDLE = `imap-folder-discovery-${randomUUID()}@acme.test`;
describe('IMAP folder discovery (integration)', () => {
- let greenmail: GreenmailServer;
+ let dovecot: DovecotServer;
let connectedAccountId: string;
let messageChannelId: string;
beforeAll(async () => {
- ({ greenmail, connectedAccountId, messageChannelId } =
- await connectGreenmailImapAccount({
+ ({ dovecot, connectedAccountId, messageChannelId } =
+ await connectDovecotImapAccount({
handle: HANDLE,
password: PASSWORD,
}));
@@ -40,14 +37,39 @@ describe('IMAP folder discovery (integration)', () => {
}).catch(() => undefined);
}
- await greenmail?.stop().catch(() => undefined);
+ await dovecot?.stop().catch(() => undefined);
});
it('discovers the mailboxes exposed by the IMAP server', async () => {
await runMessageChannelSync(messageChannelId);
+ const folderNames = (await queryMessageFolders(messageChannelId)).map(
+ (folder) => folder.name,
+ );
+
+ expect(folderNames).toEqual(
+ expect.arrayContaining(['INBOX', 'Sent', 'Drafts']),
+ );
+ }, 300000);
+
+ it('skips the mailboxes excluded from folder management', async () => {
+ await runMessageChannelSync(messageChannelId);
+
+ const folderNames = (await queryMessageFolders(messageChannelId)).map(
+ (folder) => folder.name,
+ );
+
+ expect(folderNames).not.toContain('Trash');
+ expect(folderNames).not.toContain('Junk');
+ }, 300000);
+
+ it('marks the special-use sent folder as the sent folder', async () => {
+ await runMessageChannelSync(messageChannelId);
+
const folders = await queryMessageFolders(messageChannelId);
- expect(folders.map((folder) => folder.name)).toContain('INBOX');
+ expect(
+ folders.filter((folder) => folder.isSentFolder).map(({ name }) => name),
+ ).toEqual(['Sent']);
}, 300000);
});
diff --git a/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts b/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts
index bee01613b52..03ce26a77fd 100644
--- a/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts
+++ b/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts
@@ -4,24 +4,24 @@ import { isNonEmptyString } from '@sniptt/guards';
import { MessageChannelSyncStatus } from 'twenty-shared/types';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import { MessageFolderEntity } from 'src/engine/metadata-modules/message-folder/entities/message-folder.entity';
+import { ImapSyncService } from 'src/modules/messaging/message-import-manager/drivers/imap/services/imap-sync.service';
import { deleteConnectedAccount } from 'test/integration/metadata/suites/connected-account/utils/delete-connected-account.util';
import { updateConfigVariable } from 'test/integration/twenty-config/utils/update-config-variable.util';
-import { connectGreenmailImapAccount } from 'test/integration/utils/connect-greenmail-imap-account.util';
-import { deliverMailOverSmtp } from 'test/integration/utils/deliver-mail-over-smtp.util';
+import { appendMessageOverImap } from 'test/integration/utils/append-message-over-imap.util';
+import { connectDovecotImapAccount } from 'test/integration/utils/connect-dovecot-imap-account.util';
import { findImportedMessageSubjects } from 'test/integration/utils/find-imported-records.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
-import { type GreenmailServer } from 'test/integration/utils/start-greenmail-container.util';
+import { type DovecotServer } from 'test/integration/utils/start-dovecot-container.util';
-const PASSWORD = 'greenmail-password';
-
-// GreenMail registers a declared user under the local part of its address, so
-// that is the login, while the channel keeps the full address as its handle.
+const PASSWORD = 'dovecot-password';
const HANDLE = `imap-messages-import-${randomUUID()}@acme.test`;
describe('IMAP messages import (integration)', () => {
- let greenmail: GreenmailServer;
+ let dovecot: DovecotServer;
let connectedAccountId: string;
let messageChannelId: string;
@@ -30,18 +30,27 @@ describe('IMAP messages import (integration)', () => {
MessageChannelEntity,
).findOneByOrFail({ id: messageChannelId });
- const deliverMessage = (subject: string) =>
- deliverMailOverSmtp({
- host: greenmail.host,
- port: greenmail.smtpPort,
+ const deliverMessage = ({
+ subject,
+ folder = 'INBOX',
+ }: {
+ subject: string;
+ folder?: string;
+ }) =>
+ appendMessageOverImap({
+ host: dovecot.host,
+ port: dovecot.imapPort,
+ username: HANDLE,
+ password: PASSWORD,
+ folder,
from: `sender-${randomUUID()}@external.test`,
to: HANDLE,
subject,
});
beforeAll(async () => {
- ({ greenmail, connectedAccountId, messageChannelId } =
- await connectGreenmailImapAccount({
+ ({ dovecot, connectedAccountId, messageChannelId } =
+ await connectDovecotImapAccount({
handle: HANDLE,
password: PASSWORD,
}));
@@ -59,13 +68,13 @@ describe('IMAP messages import (integration)', () => {
}).catch(() => undefined);
}
- await greenmail?.stop().catch(() => undefined);
+ await dovecot?.stop().catch(() => undefined);
});
it('imports a message delivered to the mailbox', async () => {
const subject = `IMAP message ${randomUUID()}`;
- await deliverMessage(subject);
+ await deliverMessage({ subject });
await runMessageChannelSync(messageChannelId);
@@ -79,4 +88,105 @@ describe('IMAP messages import (integration)', () => {
MessageChannelSyncStatus.ACTIVE,
);
}, 300000);
+
+ it('imports a message that arrives after a sync cursor was persisted', async () => {
+ const firstSubject = `IMAP incremental first ${randomUUID()}`;
+
+ await deliverMessage({ subject: firstSubject });
+ await runMessageChannelSync(messageChannelId);
+
+ expect(await findImportedMessageSubjects([firstSubject])).toEqual([
+ firstSubject,
+ ]);
+
+ const secondSubject = `IMAP incremental second ${randomUUID()}`;
+
+ await deliverMessage({ subject: secondSubject });
+ await runMessageChannelSync(messageChannelId);
+
+ expect(await findImportedMessageSubjects([secondSubject])).toEqual([
+ secondSubject,
+ ]);
+ }, 300000);
+
+ it('records the server MODSEQ in the folder sync cursor', async () => {
+ await runMessageChannelSync(messageChannelId);
+
+ const inbox = await getCoreRepository<MessageFolderEntity>(
+ MessageFolderEntity,
+ ).findOneByOrFail({ messageChannelId, name: 'INBOX' });
+
+ expect(JSON.parse(inbox.syncCursor ?? '{}')).toEqual(
+ expect.objectContaining({
+ modSeq: expect.any(String),
+ highestUid: expect.any(Number),
+ uidValidity: expect.any(Number),
+ }),
+ );
+ }, 300000);
+
+ it('skips opening a folder whose MODSEQ and UIDNEXT have not moved', async () => {
+ await runMessageChannelSync(messageChannelId);
+
+ const syncFolderSpy = jest.spyOn(
+ getAppProviderByClassName<ImapSyncService>('ImapSyncService'),
+ 'syncFolder',
+ );
+
+ try {
+ await runMessageChannelSync(messageChannelId);
+
+ expect(syncFolderSpy).not.toHaveBeenCalled();
+
+ await deliverMessage({ subject: `IMAP skip path ${randomUUID()}` });
+ await runMessageChannelSync(messageChannelId);
+
+ expect(syncFolderSpy).toHaveBeenCalled();
+ } finally {
+ syncFolderSpy.mockRestore();
+ }
+ }, 300000);
+
+ it('imports a message that arrives after unrelated activity in another folder', async () => {
+ await deliverMessage({
+ subject: `IMAP sent activity ${randomUUID()}`,
+ folder: 'Sent',
+ });
+ await runMessageChannelSync(messageChannelId);
+
+ const subject = `IMAP inbox after sent activity ${randomUUID()}`;
+
+ await deliverMessage({ subject });
+ await runMessageChannelSync(messageChannelId);
+
+ expect(await findImportedMessageSubjects([subject])).toEqual([subject]);
+ }, 300000);
+
+ // Servers that scope HIGHESTMODSEQ to the account rather than the mailbox hand
+ // us a cursor MODSEQ higher than any message the folder will receive next.
+ // Dovecot is compliant and cannot produce that state, so it is written directly.
+ it('imports new mail when the stored MODSEQ is ahead of the mailbox', async () => {
+ await runMessageChannelSync(messageChannelId);
+
+ const messageFolderRepository =
+ getCoreRepository<MessageFolderEntity>(MessageFolderEntity);
+ const inbox = await messageFolderRepository.findOneByOrFail({
+ messageChannelId,
+ name: 'INBOX',
+ });
+
+ await messageFolderRepository.update(inbox.id, {
+ syncCursor: JSON.stringify({
+ ...JSON.parse(inbox.syncCursor ?? '{}'),
+ modSeq: '999999',
+ }),
+ });
+
+ const subject = `IMAP stale modseq ${randomUUID()}`;
+
+ await deliverMessage({ subject });
+ await runMessageChannelSync(messageChannelId);
+
+ expect(await findImportedMessageSubjects([subject])).toEqual([subject]);
+ }, 300000);
});
diff --git a/packages/twenty-server/test/integration/utils/append-message-over-imap.util.ts b/packages/twenty-server/test/integration/utils/append-message-over-imap.util.ts
new file mode 100644
index 00000000000..02d6abb0beb
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/append-message-over-imap.util.ts
@@ -0,0 +1,50 @@
+import { ImapFlow } from 'imapflow';
+
+// Dovecot only stores and serves mailboxes, so mail is placed with APPEND
+// rather than delivered over SMTP. This also removes the delivery race an SMTP
+// hand-off introduces between sending and the message becoming fetchable.
+export const appendMessageOverImap = async ({
+ host,
+ port,
+ username,
+ password,
+ folder,
+ from,
+ to,
+ subject,
+}: {
+ host: string;
+ port: number;
+ username: string;
+ password: string;
+ folder: string;
+ from: string;
+ to: string;
+ subject: string;
+}): Promise<void> => {
+ const client = new ImapFlow({
+ host,
+ port,
+ secure: false,
+ auth: { user: username, pass: password },
+ logger: false,
+ });
+
+ await client.connect();
+
+ try {
+ const message = [
+ `From: ${from}`,
+ `To: ${to}`,
+ `Subject: ${subject}`,
+ 'Content-Type: text/plain; charset=utf-8',
+ '',
+ `body of ${subject}`,
+ '',
+ ].join('\r\n');
+
+ await client.append(folder, Buffer.from(message));
+ } finally {
+ await client.logout();
+ }
+};
diff --git a/packages/twenty-server/test/integration/utils/connect-greenmail-imap-account.util.ts b/packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.ts
similarity index 71%
rename from packages/twenty-server/test/integration/utils/connect-greenmail-imap-account.util.ts
rename to packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.ts
index ad651f61c29..a3dd19b9d26 100644
--- a/packages/twenty-server/test/integration/utils/connect-greenmail-imap-account.util.ts
+++ b/packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.ts
@@ -3,45 +3,41 @@ import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channe
import { saveImapSmtpCaldavAccount } from 'test/integration/metadata/suites/connected-account/utils/save-imap-smtp-caldav-account.util';
import { updateConfigVariable } from 'test/integration/twenty-config/utils/update-config-variable.util';
-import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
import {
- type GreenmailServer,
- startGreenmailContainer,
-} from 'test/integration/utils/start-greenmail-container.util';
+ type DovecotServer,
+ startDovecotContainer,
+} from 'test/integration/utils/start-dovecot-container.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
-export type GreenmailImapAccount = {
- greenmail: GreenmailServer;
+export type DovecotImapAccount = {
+ dovecot: DovecotServer;
connectedAccountId: string;
messageChannelId: string;
};
// The IMAP driver routes through the SSRF guard, which rejects the container's
// private address before the connection is attempted.
-export const connectGreenmailImapAccount = async ({
+export const connectDovecotImapAccount = async ({
handle,
password,
}: {
handle: string;
password: string;
-}): Promise<GreenmailImapAccount> => {
+}): Promise<DovecotImapAccount> => {
await updateConfigVariable({
input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },
});
- const greenmail = await startGreenmailContainer({
- username: handle,
- password,
- });
- const mailboxLogin = handle.split('@')[0];
+ const dovecot = await startDovecotContainer({ password });
const { data } = await saveImapSmtpCaldavAccount({
input: {
handle,
connectionParameters: {
IMAP: {
- host: greenmail.host,
- port: greenmail.imapPort,
- username: mailboxLogin,
+ host: dovecot.host,
+ port: dovecot.imapPort,
+ username: handle,
password,
connectionSecurity: EmailConnectionSecurity.NONE,
},
@@ -57,5 +53,5 @@ export const connectGreenmailImapAccount = async ({
).findOneByOrFail({ connectedAccountId })
).id;
- return { greenmail, connectedAccountId, messageChannelId };
+ return { dovecot, connectedAccountId, messageChannelId };
};
diff --git a/packages/twenty-server/test/integration/utils/query-messaging.util.ts b/packages/twenty-server/test/integration/utils/query-messaging.util.ts
index 0cdcef8b0c7..9160cf53c15 100644
--- a/packages/twenty-server/test/integration/utils/query-messaging.util.ts
+++ b/packages/twenty-server/test/integration/utils/query-messaging.util.ts
@@ -31,7 +31,7 @@ export const getDataOrThrow = (response: MetadataAPIResponse) => {
export type MessageFolderDto = Pick<
MessageFolderDTO,
- 'id' | 'name' | 'isSynced'
+ 'id' | 'name' | 'isSynced' | 'isSentFolder'
>;
export type MessageChannelDto = Pick<
@@ -147,6 +147,7 @@ export const queryMessageFolders = async (
id
name
isSynced
+ isSentFolder
}
}
`,
diff --git a/packages/twenty-server/test/integration/utils/start-dovecot-container.util.ts b/packages/twenty-server/test/integration/utils/start-dovecot-container.util.ts
new file mode 100644
index 00000000000..ca7781ebde2
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/start-dovecot-container.util.ts
@@ -0,0 +1,54 @@
+import {
+ GenericContainer,
+ type StartedTestContainer,
+ Wait,
+} from 'testcontainers';
+
+const DOVECOT_IMAGE =
+ 'dovecot/dovecot:2.4.4@sha256:723e3392fe16c6fad8ddc605ea767cc01b4bad9cd9f13eb1dbac15e79c89b2d4';
+const DOVECOT_IMAP_PORT = 31143;
+
+export type DovecotServer = {
+ host: string;
+ imapPort: number;
+ stop: () => Promise<void>;
+};
+
+// Unlike GreenMail, Dovecot advertises CONDSTORE, QRESYNC and SPECIAL-USE, and
+// scopes HIGHESTMODSEQ per mailbox as RFC 7162 requires, so it is the reference
+// server for the incremental sync path. Its static passdb accepts any username
+// with USER_PASSWORD.
+// Cleartext auth has to be switched on and SSL switched off because these tests
+// connect without TLS: while STARTTLS is advertised ImapFlow upgrades to it and
+// then rejects the image's self-signed certificate.
+const DOVECOT_TEST_CONFIG = ['auth_allow_cleartext = yes', 'ssl = no', ''].join(
+ '\n',
+);
+
+export const startDovecotContainer = async ({
+ password,
+}: {
+ password: string;
+}): Promise<DovecotServer> => {
+ const container: StartedTestContainer = await new GenericContainer(
+ DOVECOT_IMAGE,
+ )
+ .withEnvironment({ USER_PASSWORD: `{PLAIN}${password}` })
+ .withCopyContentToContainer([
+ {
+ content: DOVECOT_TEST_CONFIG,
+ target: '/etc/dovecot/conf.d/99-integration-test.conf',
+ },
+ ])
+ .withExposedPorts(DOVECOT_IMAP_PORT)
+ .withWaitStrategy(Wait.forListeningPorts())
+ .start();
+
+ return {
+ host: container.getHost(),
+ imapPort: container.getMappedPort(DOVECOT_IMAP_PORT),
+ stop: async () => {
+ await container.stop();
+ },
+ };
+};