Skip to content

The open alternative to Salesforce, designed for AI.

test(server): integration coverage for messaging and calendar sync (#24104)

neo7734168900223bb
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/__tests__/parse-gaxios-error.util.spec.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/__tests__/parse-gaxios-error.util.spec.ts
new file mode 100644
index 00000000000..cee413758b9
--- /dev/null
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/__tests__/parse-gaxios-error.util.spec.ts
@@ -0,0 +1,45 @@
+import { type GaxiosError } from 'gaxios';
+
+import { CalendarEventImportDriverExceptionCode } from 'src/modules/calendar/calendar-event-import-manager/drivers/exceptions/calendar-event-import-driver.exception';
+import { parseGaxiosError } from 'src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/parse-gaxios-error.util';
+
+const gaxiosErrorWithCode = (code: string) =>
+ ({ code, message: `socket failure: ${code}` }) as GaxiosError;
+
+describe('parseGaxiosError', () => {
+ it.each([
+ 'ECONNRESET',
+ 'ENOTFOUND',
+ 'ECONNABORTED',
+ 'ETIMEDOUT',
+ 'ERR_NETWORK',
+ ])('maps the %s socket failure to a temporary error', (code) => {
+ const exception = parseGaxiosError(gaxiosErrorWithCode(code));
+
+ expect(exception.code).toBe(
+ CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
+ );
+ expect(exception.message).toBe(`socket failure: ${code}`);
+ });
+
+ it.each(['EHOSTUNREACH', 'ECONNREFUSED', 'EPIPE'])(
+ 'maps the unmatched %s socket failure to an unknown network error',
+ (code) => {
+ const exception = parseGaxiosError(gaxiosErrorWithCode(code));
+
+ expect(exception.code).toBe(
+ CalendarEventImportDriverExceptionCode.UNKNOWN_NETWORK_ERROR,
+ );
+ },
+ );
+
+ it('maps an error without a code to an unknown network error', () => {
+ const exception = parseGaxiosError({
+ message: 'no code at all',
+ } as GaxiosError);
+
+ expect(exception.code).toBe(
+ CalendarEventImportDriverExceptionCode.UNKNOWN_NETWORK_ERROR,
+ );
+ });
+});
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gaxios-error.spec.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gaxios-error.spec.ts
index 3ac412324dd..f3adc138fa2 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gaxios-error.spec.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gaxios-error.spec.ts
@@ -37,6 +37,18 @@ describe('isGmailNetworkError', () => {
expect(result).toBe(true);
});
+ it('should return a MessageImportDriverException for EHOSTUNREACH', () => {
+ const result = isGmailNetworkError({ code: 'EHOSTUNREACH' });
+
+ expect(result).toBe(true);
+ });
+
+ it('should not treat ECONNREFUSED as a network error', () => {
+ const result = isGmailNetworkError({ code: 'ECONNREFUSED' });
+
+ expect(result).toBe(false);
+ });
+
it('should return undefined for unknown error codes', () => {
const error = { code: 'UNKNOWN_ERROR' } as any;
const result = isGmailNetworkError(error);
diff --git a/packages/twenty-server/test/integration/aws/mocks/sns-payload.util.ts b/packages/twenty-server/test/integration/aws/mocks/sns-payload.util.ts
new file mode 100644
index 00000000000..89c4072bd83
--- /dev/null
+++ b/packages/twenty-server/test/integration/aws/mocks/sns-payload.util.ts
@@ -0,0 +1,123 @@
+import { createSign, generateKeyPairSync, randomUUID } from 'node:crypto';
+
+import { http, HttpResponse } from 'msw';
+
+import { type MswHandler } from 'test/integration/utils/http-mock.util';
+
+// The SNS validator fetches the signing certificate over https and verifies the
+// canonical string with it. Node's verify() accepts a bare public key, so the
+// suite serves one at a URL matching the validator's amazonaws.com pattern
+// instead of minting a real X.509 certificate.
+export const SNS_SIGNING_CERT_URL =
+ 'https://sns.eu-west-3.amazonaws.com/SimpleNotificationService-abcdef0123456789abcdef0123456789.pem';
+
+const { publicKey, privateKey } = generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+});
+
+const publicKeyPem = publicKey
+ .export({ type: 'spki', format: 'pem' })
+ .toString();
+
+const SIGNED_KEYS_BY_TYPE = {
+ Notification: [
+ 'Message',
+ 'MessageId',
+ 'Subject',
+ 'Timestamp',
+ 'TopicArn',
+ 'Type',
+ ],
+ SubscriptionConfirmation: [
+ 'Message',
+ 'MessageId',
+ 'SubscribeURL',
+ 'Timestamp',
+ 'Token',
+ 'TopicArn',
+ 'Type',
+ ],
+ UnsubscribeConfirmation: [
+ 'Message',
+ 'MessageId',
+ 'SubscribeURL',
+ 'Timestamp',
+ 'Token',
+ 'TopicArn',
+ 'Type',
+ ],
+} as const;
+
+export const snsSigningCertHandler = (): MswHandler =>
+ http.get(SNS_SIGNING_CERT_URL, () => HttpResponse.text(publicKeyPem));
+
+type SnsPayloadType = keyof typeof SIGNED_KEYS_BY_TYPE;
+
+const signPayload = (
+ type: SnsPayloadType,
+ payload: Record<string, string>,
+): string => {
+ const signer = createSign('sha256WithRSAEncryption');
+
+ for (const key of SIGNED_KEYS_BY_TYPE[type]) {
+ if (key in payload) {
+ signer.write(`${key}\n${payload[key]}\n`);
+ }
+ }
+
+ signer.end();
+
+ return signer.sign(privateKey, 'base64');
+};
+
+export const snsNotification = ({
+ topicArn,
+ message,
+ signed = true,
+}: {
+ topicArn: string;
+ message: unknown;
+ signed?: boolean;
+}): Record<string, string> => {
+ const payload: Record<string, string> = {
+ Type: 'Notification',
+ MessageId: randomUUID(),
+ TopicArn: topicArn,
+ Message: JSON.stringify(message),
+ Timestamp: '2026-01-01T00:00:00.000Z',
+ SignatureVersion: '2',
+ SigningCertURL: SNS_SIGNING_CERT_URL,
+ };
+
+ return {
+ ...payload,
+ Signature: signed
+ ? signPayload('Notification', payload)
+ : Buffer.from('not-a-signature').toString('base64'),
+ };
+};
+
+export const snsSubscriptionConfirmation = ({
+ topicArn,
+ subscribeUrl,
+}: {
+ topicArn: string;
+ subscribeUrl: string;
+}): Record<string, string> => {
+ const payload: Record<string, string> = {
+ Type: 'SubscriptionConfirmation',
+ MessageId: randomUUID(),
+ TopicArn: topicArn,
+ Token: randomUUID().replace(/-/g, ''),
+ SubscribeURL: subscribeUrl,
+ Message: 'You have chosen to subscribe to the topic.',
+ Timestamp: '2026-01-01T00:00:00.000Z',
+ SignatureVersion: '2',
+ SigningCertURL: SNS_SIGNING_CERT_URL,
+ };
+
+ return {
+ ...payload,
+ Signature: signPayload('SubscriptionConfirmation', payload),
+ };
+};
diff --git a/packages/twenty-server/test/integration/aws/suites/ses-inbound-webhook.integration-spec.ts b/packages/twenty-server/test/integration/aws/suites/ses-inbound-webhook.integration-spec.ts
new file mode 100644
index 00000000000..5a13c6d7b05
--- /dev/null
+++ b/packages/twenty-server/test/integration/aws/suites/ses-inbound-webhook.integration-spec.ts
@@ -0,0 +1,200 @@
+import { randomUUID } from 'node:crypto';
+
+import { http, HttpResponse } from 'msw';
+import request from 'supertest';
+
+import { MessageSuppressionEntity } from 'src/engine/core-modules/emailing-domain/message-suppression.entity';
+import { UnsubscribeTokenService } from 'src/engine/core-modules/emailing-domain/services/unsubscribe-token.service';
+import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+import {
+ snsNotification,
+ snsSigningCertHandler,
+ snsSubscriptionConfirmation,
+} from 'test/integration/aws/mocks/sns-payload.util';
+import { updateConfigVariable } from 'test/integration/twenty-config/utils/update-config-variable.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 { setupHttpMock } from 'test/integration/utils/http-mock.util';
+
+const ALLOWED_TOPIC_ARN =
+ 'arn:aws:sns:eu-west-3:000000000000:twenty-ses-inbound-test';
+
+const SES_INBOUND_WEBHOOK_PATH = '/webhooks/messaging/ses/inbound';
+
+const SUBSCRIBE_URL =
+ 'https://sns.eu-west-3.amazonaws.com/?Action=ConfirmSubscription&Token=test-token';
+
+const inboundNotification = ({
+ recipients,
+ subject,
+ actionType = 'S3',
+}: {
+ recipients: string[];
+ subject?: string;
+ actionType?: string;
+}) => ({
+ mail: { commonHeaders: { subject } },
+ receipt: {
+ recipients,
+ action: { type: actionType, objectKey: `inbound/${randomUUID()}` },
+ },
+});
+
+const postSesInboundWebhook = (payload: Record<string, string>) =>
+ request(`http://localhost:${APP_PORT}`)
+ .post(SES_INBOUND_WEBHOOK_PATH)
+ .set('Content-Type', 'application/json')
+ .send(JSON.stringify(payload));
+
+describe('SES inbound webhook (integration)', () => {
+ const httpMock = setupHttpMock(snsSigningCertHandler());
+
+ let unsubscribeTokenService: UnsubscribeTokenService;
+
+ const findSuppressionReasons = async (emailAddress: string) => {
+ const suppressions = await getCoreRepository<MessageSuppressionEntity>(
+ MessageSuppressionEntity,
+ ).findBy({ workspaceId: SEED_APPLE_WORKSPACE_ID, emailAddress });
+
+ return suppressions.map((suppression) => suppression.reason);
+ };
+
+ const postUnsubscribeMail = (subject?: string) =>
+ postSesInboundWebhook(
+ snsNotification({
+ topicArn: ALLOWED_TOPIC_ARN,
+ message: inboundNotification({
+ recipients: ['[email protected]'],
+ subject,
+ }),
+ }),
+ );
+
+ beforeAll(async () => {
+ await updateConfigVariable({
+ input: { key: 'SES_SNS_TOPIC_ARN_ALLOWLIST', value: ALLOWED_TOPIC_ARN },
+ });
+
+ unsubscribeTokenService =
+ getAppProviderByClassName<UnsubscribeTokenService>(
+ 'UnsubscribeTokenService',
+ );
+ }, 60000);
+
+ it('suppresses the sender of a valid unsubscribe email', async () => {
+ const emailAddress = `unsub-${randomUUID()}@acme.com`;
+
+ const response = await postUnsubscribeMail(
+ unsubscribeTokenService.sign({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ emailAddress,
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(await findSuppressionReasons(emailAddress)).toEqual([
+ MessageSuppressionReason.UNSUBSCRIBE,
+ ]);
+ }, 60000);
+
+ it('suppresses nothing for a preview unsubscribe token', async () => {
+ const emailAddress = `preview-${randomUUID()}@acme.com`;
+
+ const response = await postUnsubscribeMail(
+ unsubscribeTokenService.sign({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ emailAddress,
+ preview: true,
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(await findSuppressionReasons(emailAddress)).toEqual([]);
+ }, 60000);
+
+ it('ignores an unsubscribe email whose subject is not a valid token', async () => {
+ const response = await postUnsubscribeMail('please unsubscribe me');
+
+ expect(response.status).toBe(200);
+ }, 60000);
+
+ it('ignores an unsubscribe email that carries no subject', async () => {
+ const response = await postUnsubscribeMail();
+
+ expect(response.status).toBe(200);
+ }, 60000);
+
+ it('ignores an inbound email delivered through an unsupported action', async () => {
+ const response = await postSesInboundWebhook(
+ snsNotification({
+ topicArn: ALLOWED_TOPIC_ARN,
+ message: inboundNotification({
+ recipients: ['[email protected]'],
+ actionType: 'Lambda',
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ }, 60000);
+
+ it('confirms an SNS subscription by calling the subscribe URL', async () => {
+ let subscribeUrlWasCalled = false;
+
+ httpMock.use(
+ http.get(SUBSCRIBE_URL, () => {
+ subscribeUrlWasCalled = true;
+
+ return HttpResponse.text('<ConfirmSubscriptionResponse />');
+ }),
+ );
+
+ const response = await postSesInboundWebhook(
+ snsSubscriptionConfirmation({
+ topicArn: ALLOWED_TOPIC_ARN,
+ subscribeUrl: SUBSCRIBE_URL,
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(subscribeUrlWasCalled).toBe(true);
+ }, 60000);
+
+ it('rejects an inbound notification from a topic outside the allowlist', async () => {
+ const response = await postSesInboundWebhook(
+ snsNotification({
+ topicArn: 'arn:aws:sns:eu-west-3:000000000000:some-other-topic',
+ message: inboundNotification({
+ recipients: ['[email protected]'],
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(403);
+ }, 60000);
+
+ it('rejects an inbound body that is not valid JSON', async () => {
+ const response = await request(`http://localhost:${APP_PORT}`)
+ .post(SES_INBOUND_WEBHOOK_PATH)
+ .set('Content-Type', 'application/json')
+ .send('not-json');
+
+ expect(response.status).toBe(400);
+ }, 60000);
+
+ it('rejects an inbound notification whose signature does not verify', async () => {
+ const response = await postSesInboundWebhook(
+ snsNotification({
+ topicArn: ALLOWED_TOPIC_ARN,
+ signed: false,
+ message: inboundNotification({
+ recipients: ['[email protected]'],
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(403);
+ }, 60000);
+});
diff --git a/packages/twenty-server/test/integration/google/calendar/channel-visibility.integration-spec.ts b/packages/twenty-server/test/integration/google/calendar/channel-visibility.integration-spec.ts
new file mode 100644
index 00000000000..5b8ce3cf93e
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/calendar/channel-visibility.integration-spec.ts
@@ -0,0 +1,108 @@
+import { randomUUID } from 'node:crypto';
+
+import {
+ CalendarChannelVisibility,
+ ConnectedAccountProvider,
+} from 'twenty-shared/types';
+
+import { FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED } from 'twenty-shared/constants';
+
+import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
+
+import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
+import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { makeGraphqlAPIRequestWithMemberRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-member-role.util';
+import { googleCalendarEvent } from 'test/integration/google/mocks/google-calendar-event.util';
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { runCalendarChannelEventsImport } from 'test/integration/utils/run-calendar-channel-events-import.util';
+import { runCalendarChannelListFetch } from 'test/integration/utils/run-calendar-channel-list-fetch.util';
+
+const HANDLE = '[email protected]';
+
+const RESTRICTED = FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
+
+describe('Calendar channel visibility (integration)', () => {
+ const eventTitle = `Calendar event ${randomUUID()}`;
+
+ const gmail = setupGoogleMock({ handle: HANDLE });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ const calendarEventQuery = () =>
+ findManyOperationFactory({
+ objectMetadataSingularName: 'calendarEvent',
+ objectMetadataPluralName: 'calendarEvents',
+ gqlFields: 'title description',
+ filter: { title: { eq: eventTitle } },
+ });
+
+ const readEventAs = async (
+ makeRequest:
+ | typeof makeGraphqlAPIRequest
+ | typeof makeGraphqlAPIRequestWithMemberRole,
+ ) => {
+ const response = await makeRequest(calendarEventQuery());
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.calendarEvents.edges.map(
+ (edge: { node: { title: string; description: string } }) => edge.node,
+ );
+ };
+
+ const setVisibility = async (visibility: CalendarChannelVisibility) => {
+ await getCoreRepository<CalendarChannelEntity>(
+ CalendarChannelEntity,
+ ).update({ id: channel.calendarChannelId }, { visibility });
+ };
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+
+ gmail.serveCalendarEvents([
+ googleCalendarEvent({
+ summary: eventTitle,
+ description: 'Agenda for the meeting',
+ }),
+ ]);
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+ await runCalendarChannelEventsImport(channel.calendarChannelId);
+ }, 120000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('shows the full event to another member when the channel shares everything', async () => {
+ await setVisibility(CalendarChannelVisibility.SHARE_EVERYTHING);
+
+ const [event] = await readEventAs(makeGraphqlAPIRequestWithMemberRole);
+
+ expect(event.title).toBe(eventTitle);
+ expect(event.description).not.toBe(RESTRICTED);
+ }, 60000);
+
+ it('masks the title and description for another member under metadata visibility', async () => {
+ await setVisibility(CalendarChannelVisibility.METADATA);
+
+ const [event] = await readEventAs(makeGraphqlAPIRequestWithMemberRole);
+
+ expect(event.title).toBe(RESTRICTED);
+ expect(event.description).toBe(RESTRICTED);
+ }, 60000);
+
+ it('always shows the full event to the owner of the connected account', async () => {
+ await setVisibility(CalendarChannelVisibility.METADATA);
+
+ const [event] = await readEventAs(makeGraphqlAPIRequest);
+
+ expect(event.title).toBe(eventTitle);
+ expect(event.description).not.toBe(RESTRICTED);
+ }, 60000);
+});
diff --git a/packages/twenty-server/test/integration/google/calendar/contact-auto-creation.integration-spec.ts b/packages/twenty-server/test/integration/google/calendar/contact-auto-creation.integration-spec.ts
new file mode 100644
index 00000000000..4ac10a5643c
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/calendar/contact-auto-creation.integration-spec.ts
@@ -0,0 +1,94 @@
+import { randomUUID } from 'node:crypto';
+
+import {
+ CalendarChannelContactAutoCreationPolicy,
+ ConnectedAccountProvider,
+} from 'twenty-shared/types';
+
+import { googleCalendarEvent } from 'test/integration/google/mocks/google-calendar-event.util';
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { findCreatedPeopleEmails } from 'test/integration/utils/find-imported-records.util';
+import {
+ queryCalendarChannel,
+ updateCalendarChannel,
+} from 'test/integration/utils/query-messaging.util';
+import { resetCalendarChannelSyncState } from 'test/integration/utils/reset-channel-sync-state.util';
+import { runCalendarChannelEventsImport } from 'test/integration/utils/run-calendar-channel-events-import.util';
+import { runCalendarChannelListFetch } from 'test/integration/utils/run-calendar-channel-list-fetch.util';
+
+const HANDLE = '[email protected]';
+
+describe('Calendar contact auto-creation (integration)', () => {
+ const gmail = setupGoogleMock({ handle: HANDLE });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ const syncEventWithAttendee = async (attendee: string) => {
+ gmail.serveCalendarEvents(
+ [
+ googleCalendarEvent({
+ summary: `Calendar event ${randomUUID()}`,
+ attendees: [{ email: attendee }],
+ }),
+ ],
+ { nextSyncToken: `sync-token-${randomUUID()}` },
+ );
+
+ await resetCalendarChannelSyncState(channel.calendarChannelId, '');
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+ await runCalendarChannelEventsImport(channel.calendarChannelId);
+
+ return findCreatedPeopleEmails([attendee]);
+ };
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+ }, 60000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('creates a person for an attendee when auto-creation is enabled', async () => {
+ await updateCalendarChannel(channel.calendarChannelId, {
+ isContactAutoCreationEnabled: true,
+ });
+
+ const attendee = `attendee-enabled-${randomUUID()}@acme.com`;
+
+ expect(await syncEventWithAttendee(attendee)).toEqual([attendee]);
+ }, 120000);
+
+ it('creates no person for an attendee when auto-creation is disabled', async () => {
+ await updateCalendarChannel(channel.calendarChannelId, {
+ isContactAutoCreationEnabled: false,
+ });
+
+ const attendee = `attendee-disabled-${randomUUID()}@acme.com`;
+
+ expect(await syncEventWithAttendee(attendee)).toEqual([]);
+ }, 120000);
+
+ // Calendar contact creation is gated on isContactAutoCreationEnabled alone;
+ // the policy is stored and served but no import path reads it.
+ it.each(Object.values(CalendarChannelContactAutoCreationPolicy))(
+ 'persists the %s contact auto-creation policy',
+ async (contactAutoCreationPolicy) => {
+ await updateCalendarChannel(channel.calendarChannelId, {
+ contactAutoCreationPolicy,
+ });
+
+ const channelState = await queryCalendarChannel(channel);
+
+ expect(channelState.contactAutoCreationPolicy).toBe(
+ contactAutoCreationPolicy,
+ );
+ },
+ 60000,
+ );
+});
diff --git a/packages/twenty-server/test/integration/google/calendar/import-error-mapping.integration-spec.ts b/packages/twenty-server/test/integration/google/calendar/import-error-mapping.integration-spec.ts
new file mode 100644
index 00000000000..4d8cddc8c9c
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/calendar/import-error-mapping.integration-spec.ts
@@ -0,0 +1,210 @@
+import {
+ CalendarChannelSyncStage,
+ CalendarChannelSyncStatus,
+ ConnectedAccountProvider,
+} from 'twenty-shared/types';
+
+import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+
+import {
+ type GoogleApiFailure,
+ setupGoogleMock,
+} from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import {
+ queryCalendarChannel,
+ queryConnectedAccount,
+} from 'test/integration/utils/query-messaging.util';
+import { resetCalendarChannelSyncState } from 'test/integration/utils/reset-channel-sync-state.util';
+import { runCalendarChannelListFetch } from 'test/integration/utils/run-calendar-channel-list-fetch.util';
+
+const HANDLE = '[email protected]';
+
+// Providers return 401 and 403 transiently, so revoking on them disconnects
+// working accounts. Only a response that proves the grant is gone revokes.
+const INSUFFICIENT_PERMISSIONS_FAILURES: [string, GoogleApiFailure][] = [
+ [
+ 'a 400 invalid_grant response',
+ {
+ status: 400,
+ reason: 'invalid_grant',
+ message: 'Token has been expired or revoked.',
+ },
+ ],
+];
+
+const TEMPORARY_FAILURES: [string, GoogleApiFailure][] = [
+ [
+ 'a 401 unauthorized response',
+ { status: 401, reason: 'authError', message: 'Invalid Credentials' },
+ ],
+ [
+ 'a 403 response that is not a rate limit',
+ {
+ status: 403,
+ reason: 'insufficientPermissions',
+ message: 'Request had insufficient authentication scopes.',
+ },
+ ],
+ [
+ 'a 500 response with an unmapped reason',
+ { status: 500, reason: 'somethingElse', message: 'Internal error' },
+ ],
+ [
+ 'a response with an unmapped status',
+ { status: 418, reason: 'teapot', message: 'I am a teapot' },
+ ],
+ [
+ 'a 403 rateLimitExceeded response',
+ {
+ status: 403,
+ reason: 'rateLimitExceeded',
+ message: 'Rate Limit Exceeded',
+ },
+ ],
+ [
+ 'a 403 userRateLimitExceeded response',
+ {
+ status: 403,
+ reason: 'userRateLimitExceeded',
+ message: 'User Rate Limit Exceeded',
+ },
+ ],
+ [
+ 'a 400 failedPrecondition response',
+ {
+ status: 400,
+ reason: 'failedPrecondition',
+ message: 'Precondition check failed.',
+ },
+ ],
+ [
+ 'a 500 backendError response',
+ { status: 500, reason: 'backendError', message: 'Backend Error' },
+ ],
+ [
+ 'a 500 internal_failure response',
+ { status: 500, reason: 'internal_failure', message: 'Internal failure' },
+ ],
+];
+
+const UNKNOWN_FAILURES: [string, GoogleApiFailure][] = [
+ [
+ 'a 400 response with an unmapped reason',
+ { status: 400, reason: 'invalidArgument', message: 'Invalid query' },
+ ],
+];
+
+describe('Google Calendar import error mapping (integration)', () => {
+ const google = setupGoogleMock({ handle: HANDLE });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+ }, 60000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ beforeEach(async () => {
+ await resetCalendarChannelSyncState(channel.calendarChannelId);
+
+ await getCoreRepository<ConnectedAccountEntity>(
+ ConnectedAccountEntity,
+ ).update({ id: channel.connectedAccountId }, { authFailedAt: null });
+ });
+
+ it.each(INSUFFICIENT_PERMISSIONS_FAILURES)(
+ 'fails the calendar channel as insufficient-permissions on %s',
+ async (_label, failure) => {
+ google.failCalendarEventList(failure);
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+
+ const channelState = await queryCalendarChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ CalendarChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS,
+ );
+ expect(channelState.syncStage).toBe(CalendarChannelSyncStage.FAILED);
+
+ const account = await queryConnectedAccount(channel.connectedAccountId);
+
+ expect(account.authFailedAt).not.toBeNull();
+ },
+ 60000,
+ );
+
+ it.each(TEMPORARY_FAILURES)(
+ 'throttles the calendar channel without failing it on %s',
+ async (_label, failure) => {
+ google.failCalendarEventList(failure);
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+
+ const channelState = await queryCalendarChannel(channel);
+
+ expect(channelState.throttleFailureCount).toBe(1);
+ expect(channelState.syncStage).toBe(
+ CalendarChannelSyncStage.CALENDAR_EVENT_LIST_FETCH_PENDING,
+ );
+ expect(channelState.syncStatus).not.toBe(
+ CalendarChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStatus).not.toBe(
+ CalendarChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS,
+ );
+ },
+ 60000,
+ );
+
+ it.each(UNKNOWN_FAILURES)(
+ 'fails the calendar channel as unknown on %s',
+ async (_label, failure) => {
+ google.failCalendarEventList(failure);
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+
+ const channelState = await queryCalendarChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ CalendarChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStage).toBe(CalendarChannelSyncStage.FAILED);
+ },
+ 60000,
+ );
+
+ it('leaves the calendar channel untouched on a 404 during list fetch', async () => {
+ google.failCalendarEventList({
+ status: 404,
+ reason: 'notFound',
+ message: 'Not Found',
+ });
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+
+ const channelState = await queryCalendarChannel(channel);
+
+ expect(channelState.syncStatus).not.toBe(
+ CalendarChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStatus).not.toBe(
+ CalendarChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS,
+ );
+ expect(channelState.throttleFailureCount).toBe(0);
+
+ const storedChannel = await getCoreRepository<CalendarChannelEntity>(
+ CalendarChannelEntity,
+ ).findOneByOrFail({ id: channel.calendarChannelId });
+
+ expect(storedChannel.syncCursor).toBe('reset-cursor');
+ }, 60000);
+});
diff --git a/packages/twenty-server/test/integration/google/calendar/sync-failure-lifecycle.integration-spec.ts b/packages/twenty-server/test/integration/google/calendar/sync-failure-lifecycle.integration-spec.ts
index 87e485044cc..2c58806ed4c 100644
--- a/packages/twenty-server/test/integration/google/calendar/sync-failure-lifecycle.integration-spec.ts
+++ b/packages/twenty-server/test/integration/google/calendar/sync-failure-lifecycle.integration-spec.ts
@@ -134,9 +134,7 @@ describe('Calendar sync failure lifecycle (integration)', () => {
const relaunchedChannel = await queryCalendarChannel(throttledChannel);
- expect(relaunchedChannel.syncStatus).toBe(
- CalendarChannelSyncStatus.ACTIVE,
- );
+ expect(relaunchedChannel.syncStatus).toBe(CalendarChannelSyncStatus.ACTIVE);
expect(relaunchedChannel.syncStage).toBe(
CalendarChannelSyncStage.CALENDAR_EVENT_LIST_FETCH_PENDING,
);
diff --git a/packages/twenty-server/test/integration/google/messaging/blocklist-cleanup.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/blocklist-cleanup.integration-spec.ts
new file mode 100644
index 00000000000..32481be653d
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/blocklist-cleanup.integration-spec.ts
@@ -0,0 +1,116 @@
+import { randomUUID } from 'node:crypto';
+
+import { ConnectedAccountProvider } from 'twenty-shared/types';
+
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+
+import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
+import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { googleCalendarEvent } from 'test/integration/google/mocks/google-calendar-event.util';
+import { getGmailMessageSubject } from 'test/integration/google/mocks/gmail-message-subject.util';
+import { gmailMessage } from 'test/integration/google/mocks/gmail-message.util';
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import {
+ findImportedCalendarEventTitles,
+ findImportedMessageSubjects,
+} from 'test/integration/utils/find-imported-records.util';
+import { runCalendarChannelEventsImport } from 'test/integration/utils/run-calendar-channel-events-import.util';
+import { runCalendarChannelListFetch } from 'test/integration/utils/run-calendar-channel-list-fetch.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
+
+const HANDLE = '[email protected]';
+const BLOCKED_HANDLE = `blocked-${randomUUID()}@acme.com`;
+
+describe('Blocklist cleanup (integration)', () => {
+ const blockedMessage = gmailMessage({ from: BLOCKED_HANDLE, to: HANDLE });
+ const keptMessage = gmailMessage({
+ from: `kept-${randomUUID()}@acme.com`,
+ to: HANDLE,
+ });
+
+ const blockedSubject = getGmailMessageSubject(blockedMessage);
+ const keptSubject = getGmailMessageSubject(keptMessage);
+
+ const blockedEventTitle = `Blocked event ${randomUUID()}`;
+ const keptEventTitle = `Kept event ${randomUUID()}`;
+
+ const gmail = setupGoogleMock({
+ handle: HANDLE,
+ inbox: [blockedMessage, keptMessage],
+ });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+
+ await runMessageChannelSync(channel.channelId);
+
+ gmail.serveCalendarEvents([
+ googleCalendarEvent({
+ summary: blockedEventTitle,
+ attendees: [{ email: BLOCKED_HANDLE }],
+ }),
+ googleCalendarEvent({
+ summary: keptEventTitle,
+ attendees: [{ email: `kept-attendee-${randomUUID()}@acme.com` }],
+ }),
+ ]);
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+ await runCalendarChannelEventsImport(channel.calendarChannelId);
+ }, 180000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('imports both the message and the calendar event before anything is blocked', async () => {
+ expect(
+ await findImportedMessageSubjects([blockedSubject, keptSubject]),
+ ).toEqual([blockedSubject, keptSubject].sort());
+
+ expect(
+ await findImportedCalendarEventTitles([
+ blockedEventTitle,
+ keptEventTitle,
+ ]),
+ ).toEqual([blockedEventTitle, keptEventTitle].sort());
+ }, 60000);
+
+ // Blocking a handle deletes their messages but deliberately leaves calendar
+ // events alone: an event the blocked handle merely attended is still the
+ // workspace's own meeting, so it is not swept up with them.
+ it('deletes the blocked handle messages and keeps every calendar event', async () => {
+ const response = await makeGraphqlAPIRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: 'blocklist',
+ gqlFields: 'id handle',
+ data: {
+ handle: BLOCKED_HANDLE,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ await waitForAllJobsToFinish();
+
+ expect(
+ await findImportedMessageSubjects([blockedSubject, keptSubject]),
+ ).toEqual([keptSubject]);
+
+ expect(
+ await findImportedCalendarEventTitles([
+ blockedEventTitle,
+ keptEventTitle,
+ ]),
+ ).toEqual([blockedEventTitle, keptEventTitle].sort());
+ }, 120000);
+});
diff --git a/packages/twenty-server/test/integration/google/messaging/channel-deletion-cleanup.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/channel-deletion-cleanup.integration-spec.ts
new file mode 100644
index 00000000000..a090745b327
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/channel-deletion-cleanup.integration-spec.ts
@@ -0,0 +1,94 @@
+import { randomUUID } from 'node:crypto';
+
+import { ConnectedAccountProvider } from 'twenty-shared/types';
+
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import {
+ CalendarChannelDeletionCleanupJob,
+ type CalendarChannelDeletionCleanupJobData,
+} from 'src/modules/calendar/calendar-event-cleaner/jobs/calendar-channel-deletion-cleanup.job';
+import {
+ MessagingMessageChannelDeletionCleanupJob,
+ type MessagingMessageChannelDeletionCleanupJobData,
+} from 'src/modules/messaging/message-cleaner/jobs/messaging-message-channel-deletion-cleanup.job';
+
+import { googleCalendarEvent } from 'test/integration/google/mocks/google-calendar-event.util';
+import { getGmailMessageSubject } from 'test/integration/google/mocks/gmail-message-subject.util';
+import { gmailMessage } from 'test/integration/google/mocks/gmail-message.util';
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { enqueueJobAndDrain } from 'test/integration/utils/enqueue-job-and-drain.util';
+import {
+ findImportedCalendarEventTitles,
+ findImportedMessageSubjects,
+} from 'test/integration/utils/find-imported-records.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { runCalendarChannelEventsImport } from 'test/integration/utils/run-calendar-channel-events-import.util';
+import { runCalendarChannelListFetch } from 'test/integration/utils/run-calendar-channel-list-fetch.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+
+const HANDLE = '[email protected]';
+
+describe('Channel deletion cleanup (integration)', () => {
+ const inbox = [gmailMessage()];
+ const expectedSubject = getGmailMessageSubject(inbox[0]);
+ const eventTitle = `Calendar event ${randomUUID()}`;
+
+ const gmail = setupGoogleMock({ handle: HANDLE, inbox });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+ let workspaceId: string;
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+
+ workspaceId = (
+ await getCoreRepository<MessageChannelEntity>(
+ MessageChannelEntity,
+ ).findOneByOrFail({ id: channel.channelId })
+ ).workspaceId;
+
+ await runMessageChannelSync(channel.channelId);
+
+ gmail.serveCalendarEvents([googleCalendarEvent({ summary: eventTitle })]);
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+ await runCalendarChannelEventsImport(channel.calendarChannelId);
+ }, 180000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('drops the imported messages when the message channel is cleaned up', async () => {
+ expect(await findImportedMessageSubjects([expectedSubject])).toEqual([
+ expectedSubject,
+ ]);
+
+ await enqueueJobAndDrain<MessagingMessageChannelDeletionCleanupJobData>(
+ MessageQueue.messagingQueue,
+ MessagingMessageChannelDeletionCleanupJob.name,
+ { workspaceId, messageChannelId: channel.channelId },
+ );
+
+ expect(await findImportedMessageSubjects([expectedSubject])).toEqual([]);
+ }, 120000);
+
+ it('drops the imported calendar events when the calendar channel is cleaned up', async () => {
+ expect(await findImportedCalendarEventTitles([eventTitle])).toEqual([
+ eventTitle,
+ ]);
+
+ await enqueueJobAndDrain<CalendarChannelDeletionCleanupJobData>(
+ MessageQueue.calendarQueue,
+ CalendarChannelDeletionCleanupJob.name,
+ { workspaceId, calendarChannelId: channel.calendarChannelId },
+ );
+
+ expect(await findImportedCalendarEventTitles([eventTitle])).toEqual([]);
+ }, 120000);
+});
diff --git a/packages/twenty-server/test/integration/google/messaging/channel-misconfiguration.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/channel-misconfiguration.integration-spec.ts
new file mode 100644
index 00000000000..f37c94761e7
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/channel-misconfiguration.integration-spec.ts
@@ -0,0 +1,88 @@
+import {
+ ConnectedAccountProvider,
+ MessageChannelSyncStage,
+ MessageChannelSyncStatus,
+} from 'twenty-shared/types';
+
+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+
+import { gmailMessage } from 'test/integration/google/mocks/gmail-message.util';
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { queryMessageChannel } from 'test/integration/utils/query-messaging.util';
+import { resetMessageChannelSyncState } from 'test/integration/utils/reset-channel-sync-state.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+
+const HANDLE = '[email protected]';
+
+describe('Gmail channel misconfiguration (integration)', () => {
+ // A full sync has no cursor to store when the first message carries no
+ // historyId.
+ const inbox = [gmailMessage({ historyId: undefined })];
+
+ setupGoogleMock({ handle: HANDLE, inbox });
+
+ const connectedAccountRepository = getCoreRepository<ConnectedAccountEntity>(
+ ConnectedAccountEntity,
+ );
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+ let handleAliases: string[] | null;
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+
+ handleAliases = (
+ await connectedAccountRepository.findOneByOrFail({
+ id: channel.connectedAccountId,
+ })
+ ).handleAliases;
+ }, 60000);
+
+ afterAll(async () => {
+ await connectedAccountRepository
+ .update({ id: channel?.connectedAccountId }, { handleAliases })
+ .catch(() => undefined);
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ beforeEach(async () => {
+ await resetMessageChannelSyncState(channel.channelId, '');
+ });
+
+ it('fails the channel when the connected account has no handle aliases', async () => {
+ await connectedAccountRepository.update(
+ { id: channel.connectedAccountId },
+ { handleAliases: null },
+ );
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStage).toBe(MessageChannelSyncStage.FAILED);
+ }, 60000);
+
+ it('fails the channel when the full sync yields no next sync cursor', async () => {
+ await connectedAccountRepository.update(
+ { id: channel.connectedAccountId },
+ { handleAliases },
+ );
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStage).toBe(MessageChannelSyncStage.FAILED);
+ }, 60000);
+});
diff --git a/packages/twenty-server/test/integration/google/messaging/channel-visibility.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/channel-visibility.integration-spec.ts
new file mode 100644
index 00000000000..9196e0245dd
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/channel-visibility.integration-spec.ts
@@ -0,0 +1,109 @@
+import {
+ ConnectedAccountProvider,
+ MessageChannelVisibility,
+} from 'twenty-shared/types';
+
+import { FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED } from 'twenty-shared/constants';
+
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+
+import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
+import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { makeGraphqlAPIRequestWithMemberRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-member-role.util';
+import { getGmailMessageSubject } from 'test/integration/google/mocks/gmail-message-subject.util';
+import { gmailMessage } from 'test/integration/google/mocks/gmail-message.util';
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+
+const HANDLE = '[email protected]';
+
+const RESTRICTED = FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
+
+describe('Message channel visibility (integration)', () => {
+ const inbox = [gmailMessage()];
+ const subject = getGmailMessageSubject(inbox[0]);
+
+ setupGoogleMock({ handle: HANDLE, inbox });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ const messageQuery = () =>
+ findManyOperationFactory({
+ objectMetadataSingularName: 'message',
+ objectMetadataPluralName: 'messages',
+ gqlFields: 'subject text',
+ filter: { subject: { eq: subject } },
+ });
+
+ const readMessageAs = async (
+ makeRequest:
+ | typeof makeGraphqlAPIRequest
+ | typeof makeGraphqlAPIRequestWithMemberRole,
+ ) => {
+ const response = await makeRequest(messageQuery());
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.messages.edges.map(
+ (edge: { node: { subject: string; text: string } }) => edge.node,
+ );
+ };
+
+ const setVisibility = async (visibility: MessageChannelVisibility) => {
+ await getCoreRepository<MessageChannelEntity>(MessageChannelEntity).update(
+ { id: channel.channelId },
+ { visibility },
+ );
+ };
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+
+ await runMessageChannelSync(channel.channelId);
+ }, 120000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('shows the full message to another member when the channel shares everything', async () => {
+ await setVisibility(MessageChannelVisibility.SHARE_EVERYTHING);
+
+ const [message] = await readMessageAs(makeGraphqlAPIRequestWithMemberRole);
+
+ expect(message.subject).toBe(subject);
+ expect(message.text).not.toBe(RESTRICTED);
+ }, 60000);
+
+ it('masks the body but keeps the subject for another member under subject visibility', async () => {
+ await setVisibility(MessageChannelVisibility.SUBJECT);
+
+ const [message] = await readMessageAs(makeGraphqlAPIRequestWithMemberRole);
+
+ expect(message.subject).toBe(subject);
+ expect(message.text).toBe(RESTRICTED);
+ }, 60000);
+
+ it('masks both the subject and the body for another member under metadata visibility', async () => {
+ await setVisibility(MessageChannelVisibility.METADATA);
+
+ const [message] = await readMessageAs(makeGraphqlAPIRequestWithMemberRole);
+
+ expect(message.subject).toBe(RESTRICTED);
+ expect(message.text).toBe(RESTRICTED);
+ }, 60000);
+
+ it('always shows the full message to the owner of the connected account', async () => {
+ await setVisibility(MessageChannelVisibility.METADATA);
+
+ const [message] = await readMessageAs(makeGraphqlAPIRequest);
+
+ expect(message.subject).toBe(subject);
+ expect(message.text).not.toBe(RESTRICTED);
+ }, 60000);
+});
diff --git a/packages/twenty-server/test/integration/google/messaging/contact-auto-creation-policy.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/contact-auto-creation-policy.integration-spec.ts
new file mode 100644
index 00000000000..daa09b6cb24
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/contact-auto-creation-policy.integration-spec.ts
@@ -0,0 +1,185 @@
+import { randomUUID } from 'node:crypto';
+
+import { type gmail_v1 } from 'googleapis';
+
+import {
+ ConnectedAccountProvider,
+ MessageChannelContactAutoCreationPolicy,
+} from 'twenty-shared/types';
+
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+
+import { gmailMessage } from 'test/integration/google/mocks/gmail-message.util';
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { findCreatedPeopleEmails } from 'test/integration/utils/find-imported-records.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { resetMessageChannelSyncState } from 'test/integration/utils/reset-channel-sync-state.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+
+const HANDLE = '[email protected]';
+
+describe('Gmail contact auto-creation policy (integration)', () => {
+ const inbox: gmail_v1.Schema$Message[] = [];
+
+ const gmail = setupGoogleMock({ handle: HANDLE, inbox });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ const syncConversationWith = async ({
+ inboundSender,
+ outboundRecipient,
+ channelSettings,
+ }: {
+ inboundSender: string;
+ outboundRecipient: string;
+ channelSettings: Pick<
+ MessageChannelEntity,
+ | 'contactAutoCreationPolicy'
+ | 'excludeGroupEmails'
+ | 'excludeNonProfessionalEmails'
+ > &
+ Partial<Pick<MessageChannelEntity, 'isContactAutoCreationEnabled'>>;
+ }) => {
+ const messages = [
+ gmailMessage({ from: inboundSender, to: HANDLE }),
+ gmailMessage({ from: HANDLE, to: outboundRecipient }),
+ ];
+
+ inbox.push(...messages);
+ gmail.serveMessageList(messages);
+
+ await getCoreRepository<MessageChannelEntity>(MessageChannelEntity).update(
+ { id: channel.channelId },
+ channelSettings,
+ );
+
+ await resetMessageChannelSyncState(channel.channelId, '');
+
+ await runMessageChannelSync(channel.channelId);
+
+ return findCreatedPeopleEmails([inboundSender, outboundRecipient]);
+ };
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+ }, 60000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('creates no contact when the policy is NONE', async () => {
+ const inboundSender = `inbound-none-${randomUUID()}@acme.com`;
+ const outboundRecipient = `outbound-none-${randomUUID()}@acme.com`;
+
+ expect(
+ await syncConversationWith({
+ inboundSender,
+ outboundRecipient,
+ channelSettings: {
+ contactAutoCreationPolicy:
+ MessageChannelContactAutoCreationPolicy.NONE,
+ excludeGroupEmails: false,
+ excludeNonProfessionalEmails: false,
+ },
+ }),
+ ).toEqual([]);
+ }, 60000);
+
+ it('creates only the recipient of a sent message when the policy is SENT', async () => {
+ const inboundSender = `inbound-sent-${randomUUID()}@acme.com`;
+ const outboundRecipient = `outbound-sent-${randomUUID()}@acme.com`;
+
+ expect(
+ await syncConversationWith({
+ inboundSender,
+ outboundRecipient,
+ channelSettings: {
+ contactAutoCreationPolicy:
+ MessageChannelContactAutoCreationPolicy.SENT,
+ excludeGroupEmails: false,
+ excludeNonProfessionalEmails: false,
+ },
+ }),
+ ).toEqual([outboundRecipient]);
+ }, 60000);
+
+ it('creates both sides when the policy is SENT_AND_RECEIVED', async () => {
+ const inboundSender = `inbound-both-${randomUUID()}@acme.com`;
+ const outboundRecipient = `outbound-both-${randomUUID()}@acme.com`;
+
+ expect(
+ await syncConversationWith({
+ inboundSender,
+ outboundRecipient,
+ channelSettings: {
+ contactAutoCreationPolicy:
+ MessageChannelContactAutoCreationPolicy.SENT_AND_RECEIVED,
+ excludeGroupEmails: false,
+ excludeNonProfessionalEmails: false,
+ },
+ }),
+ ).toEqual([inboundSender, outboundRecipient].sort());
+ }, 60000);
+
+ it('creates no contact when auto-creation is disabled on the channel', async () => {
+ const inboundSender = `inbound-disabled-${randomUUID()}@acme.com`;
+ const outboundRecipient = `outbound-disabled-${randomUUID()}@acme.com`;
+
+ expect(
+ await syncConversationWith({
+ inboundSender,
+ outboundRecipient,
+ channelSettings: {
+ isContactAutoCreationEnabled: false,
+ contactAutoCreationPolicy:
+ MessageChannelContactAutoCreationPolicy.SENT_AND_RECEIVED,
+ excludeGroupEmails: false,
+ excludeNonProfessionalEmails: false,
+ },
+ }),
+ ).toEqual([]);
+ }, 60000);
+
+ it('skips group email addresses when they are excluded', async () => {
+ const inboundSender = `contact@acme-${randomUUID()}.com`;
+ const outboundRecipient = `outbound-group-${randomUUID()}@acme.com`;
+
+ expect(
+ await syncConversationWith({
+ inboundSender,
+ outboundRecipient,
+ channelSettings: {
+ isContactAutoCreationEnabled: true,
+ contactAutoCreationPolicy:
+ MessageChannelContactAutoCreationPolicy.SENT_AND_RECEIVED,
+ excludeGroupEmails: true,
+ excludeNonProfessionalEmails: false,
+ },
+ }),
+ ).toEqual([outboundRecipient]);
+ }, 60000);
+
+ it('skips non-professional email addresses when they are excluded', async () => {
+ const inboundSender = `inbound-personal-${randomUUID()}@gmail.com`;
+ const outboundRecipient = `outbound-work-${randomUUID()}@acme.com`;
+
+ expect(
+ await syncConversationWith({
+ inboundSender,
+ outboundRecipient,
+ channelSettings: {
+ isContactAutoCreationEnabled: true,
+ contactAutoCreationPolicy:
+ MessageChannelContactAutoCreationPolicy.SENT_AND_RECEIVED,
+ excludeGroupEmails: false,
+ excludeNonProfessionalEmails: true,
+ },
+ }),
+ ).toEqual([outboundRecipient]);
+ }, 60000);
+});
diff --git a/packages/twenty-server/test/integration/google/messaging/email-group-channel-exclusion.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/email-group-channel-exclusion.integration-spec.ts
new file mode 100644
index 00000000000..fe44f9f453d
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/email-group-channel-exclusion.integration-spec.ts
@@ -0,0 +1,94 @@
+import { randomUUID } from 'node:crypto';
+
+import {
+ ConnectedAccountProvider,
+ MessageChannelSyncStage,
+ MessageChannelSyncStatus,
+ MessageChannelType,
+} from 'twenty-shared/types';
+
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import { MessagingRelaunchFailedMessageChannelsCronJob } from 'src/modules/messaging/message-import-manager/crons/jobs/messaging-relaunch-failed-message-channels.cron.job';
+
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { runSyncCron } from 'test/integration/utils/run-sync-cron.util';
+
+const HANDLE = '[email protected]';
+
+describe('Email group channel sync exclusion (integration)', () => {
+ setupGoogleMock({ handle: HANDLE });
+
+ const messageChannelRepository =
+ getCoreRepository<MessageChannelEntity>(MessageChannelEntity);
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+ let emailGroupChannelId: string;
+
+ const readChannel = (id: string) =>
+ messageChannelRepository.findOneByOrFail({ id });
+
+ const failChannel = (id: string) =>
+ messageChannelRepository.update(
+ { id },
+ {
+ syncStatus: MessageChannelSyncStatus.FAILED_UNKNOWN,
+ syncStage: MessageChannelSyncStage.FAILED,
+ throttleFailureCount: 3,
+ },
+ );
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+
+ const emailChannel = await readChannel(channel.channelId);
+
+ // Cloned so columns added to the channel later do not break this insert.
+ const { id: _id, ...emailChannelColumns } = emailChannel;
+
+ const emailGroupChannel = await messageChannelRepository.save({
+ ...emailChannelColumns,
+ handle: `group-${randomUUID()}@apple.dev`,
+ type: MessageChannelType.EMAIL_GROUP,
+ isSyncEnabled: true,
+ });
+
+ emailGroupChannelId = emailGroupChannel.id;
+ }, 60000);
+
+ afterAll(async () => {
+ await messageChannelRepository
+ .delete({ id: emailGroupChannelId })
+ .catch(() => undefined);
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('relaunches a failed email channel but never a failed email group channel', async () => {
+ await failChannel(channel.channelId);
+ await failChannel(emailGroupChannelId);
+
+ await runSyncCron(MessagingRelaunchFailedMessageChannelsCronJob);
+
+ const relaunchedChannel = await readChannel(channel.channelId);
+
+ expect(relaunchedChannel.syncStatus).toBe(MessageChannelSyncStatus.ACTIVE);
+ expect(relaunchedChannel.syncStage).toBe(
+ MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+ );
+ expect(relaunchedChannel.throttleFailureCount).toBe(0);
+
+ const untouchedGroupChannel = await readChannel(emailGroupChannelId);
+
+ expect(untouchedGroupChannel.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(untouchedGroupChannel.syncStage).toBe(
+ MessageChannelSyncStage.FAILED,
+ );
+ expect(untouchedGroupChannel.throttleFailureCount).toBe(3);
+ }, 120000);
+});
diff --git a/packages/twenty-server/test/integration/google/messaging/folder-discovery.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/folder-discovery.integration-spec.ts
index 53b9eda2128..f012adc68f1 100644
--- a/packages/twenty-server/test/integration/google/messaging/folder-discovery.integration-spec.ts
+++ b/packages/twenty-server/test/integration/google/messaging/folder-discovery.integration-spec.ts
@@ -44,7 +44,9 @@ describe('Gmail folder discovery (integration)', () => {
const folders = await queryMessageFolders(channel.channelId);
expect(
- Object.fromEntries(folders.map((folder) => [folder.name, folder.isSynced])),
+ Object.fromEntries(
+ folders.map((folder) => [folder.name, folder.isSynced]),
+ ),
).toEqual({
INBOX: true,
SENT: true,
@@ -64,7 +66,9 @@ describe('Gmail folder discovery (integration)', () => {
const folders = await queryMessageFolders(channel.channelId);
expect(
- Object.fromEntries(folders.map((folder) => [folder.name, folder.isSynced])),
+ Object.fromEntries(
+ folders.map((folder) => [folder.name, folder.isSynced]),
+ ),
).toEqual({
INBOX: true,
SENT: true,
diff --git a/packages/twenty-server/test/integration/google/messaging/import-error-mapping.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/import-error-mapping.integration-spec.ts
new file mode 100644
index 00000000000..61b373604ac
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/import-error-mapping.integration-spec.ts
@@ -0,0 +1,224 @@
+import {
+ ConnectedAccountProvider,
+ MessageChannelSyncStage,
+ MessageChannelSyncStatus,
+} from 'twenty-shared/types';
+
+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+
+import {
+ type GoogleApiFailure,
+ setupGoogleMock,
+} from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import {
+ queryConnectedAccount,
+ queryMessageChannel,
+} from 'test/integration/utils/query-messaging.util';
+import { resetMessageChannelSyncState } from 'test/integration/utils/reset-channel-sync-state.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+
+const HANDLE = '[email protected]';
+
+// Providers return 401 and 403 transiently, so revoking on them disconnects
+// working accounts. Only a response that proves the grant is gone revokes.
+const INSUFFICIENT_PERMISSIONS_FAILURES: [string, GoogleApiFailure][] = [
+ [
+ 'a 400 invalid_grant response',
+ {
+ status: 400,
+ reason: 'invalid_grant',
+ message: 'Token has been expired or revoked.',
+ },
+ ],
+ [
+ 'a 400 failedPrecondition response for a disabled mail service',
+ {
+ status: 400,
+ reason: 'failedPrecondition',
+ message: 'Mail service not enabled',
+ },
+ ],
+];
+
+const TEMPORARY_FAILURES: [string, GoogleApiFailure][] = [
+ [
+ 'a 401 unauthorized response',
+ { status: 401, reason: 'authError', message: 'Invalid Credentials' },
+ ],
+ [
+ 'a 403 insufficientPermissions response',
+ {
+ status: 403,
+ reason: 'insufficientPermissions',
+ message: 'Request had insufficient authentication scopes.',
+ },
+ ],
+ [
+ 'a 403 domainPolicy response',
+ {
+ status: 403,
+ reason: 'domainPolicy',
+ message: 'The domain policy has disabled third-party Drive apps',
+ },
+ ],
+ [
+ 'a 500 response with an unmapped reason',
+ { status: 500, reason: 'somethingElse', message: 'Internal error' },
+ ],
+ [
+ 'a response with an unmapped status',
+ { status: 418, reason: 'teapot', message: 'I am a teapot' },
+ ],
+ [
+ 'a 403 rate limit response',
+ {
+ status: 403,
+ reason: 'rateLimitExceeded',
+ message: 'Rate Limit Exceeded',
+ },
+ ],
+ [
+ 'a 400 failedPrecondition response unrelated to the mail service',
+ {
+ status: 400,
+ reason: 'failedPrecondition',
+ message: 'Precondition check failed.',
+ },
+ ],
+ [
+ 'a 503 service unavailable response',
+ {
+ status: 503,
+ reason: 'backendError',
+ message: 'The service is currently unavailable.',
+ },
+ ],
+ [
+ 'a 500 backendError response',
+ { status: 500, reason: 'backendError', message: 'Backend Error' },
+ ],
+];
+
+const UNKNOWN_FAILURES: [string, GoogleApiFailure][] = [
+ [
+ 'a 400 response with an unmapped reason',
+ { status: 400, reason: 'invalidArgument', message: 'Invalid query' },
+ ],
+];
+
+describe('Gmail import error mapping (integration)', () => {
+ const gmail = setupGoogleMock({ handle: HANDLE });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+ }, 60000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ beforeEach(async () => {
+ await resetMessageChannelSyncState(channel.channelId);
+
+ await getCoreRepository<ConnectedAccountEntity>(
+ ConnectedAccountEntity,
+ ).update({ id: channel.connectedAccountId }, { authFailedAt: null });
+ });
+
+ it.each(INSUFFICIENT_PERMISSIONS_FAILURES)(
+ 'fails the channel as insufficient-permissions on %s',
+ async (_label, failure) => {
+ gmail.failMessageList(failure);
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS,
+ );
+ expect(channelState.syncStage).toBe(MessageChannelSyncStage.FAILED);
+
+ const account = await queryConnectedAccount(channel.connectedAccountId);
+
+ expect(account.authFailedAt).not.toBeNull();
+ },
+ 60000,
+ );
+
+ it.each(TEMPORARY_FAILURES)(
+ 'throttles the channel without failing it on %s',
+ async (_label, failure) => {
+ gmail.failMessageList(failure);
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.throttleFailureCount).toBe(1);
+ expect(channelState.syncStage).toBe(
+ MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+ );
+ expect(channelState.syncStatus).not.toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStatus).not.toBe(
+ MessageChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS,
+ );
+ },
+ 60000,
+ );
+
+ it.each(UNKNOWN_FAILURES)(
+ 'fails the channel as unknown on %s',
+ async (_label, failure) => {
+ gmail.failMessageList(failure);
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStage).toBe(MessageChannelSyncStage.FAILED);
+ expect(channelState.throttleFailureCount).toBe(0);
+ },
+ 60000,
+ );
+
+ it('restarts the channel from a clean cursor on a 404 sync cursor error', async () => {
+ gmail.failMessageList({
+ status: 404,
+ reason: 'notFound',
+ message: 'Requested entity was not found.',
+ });
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStage).toBe(
+ MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+ );
+ expect(channelState.syncStatus).not.toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.throttleFailureCount).toBe(0);
+ expect(channelState.syncStageStartedAt).toBeNull();
+
+ const storedChannel = await getCoreRepository<MessageChannelEntity>(
+ MessageChannelEntity,
+ ).findOneByOrFail({ id: channel.channelId });
+
+ expect(storedChannel.syncCursor).toBeFalsy();
+ }, 60000);
+});
diff --git a/packages/twenty-server/test/integration/google/messaging/participant-matching.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/participant-matching.integration-spec.ts
new file mode 100644
index 00000000000..04ff391ca2c
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/participant-matching.integration-spec.ts
@@ -0,0 +1,143 @@
+import { randomUUID } from 'node:crypto';
+
+import {
+ ConnectedAccountProvider,
+ MessageChannelContactAutoCreationPolicy,
+} from 'twenty-shared/types';
+
+import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+
+import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
+import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { googleCalendarEvent } from 'test/integration/google/mocks/google-calendar-event.util';
+import { gmailMessage } from 'test/integration/google/mocks/gmail-message.util';
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { runCalendarChannelEventsImport } from 'test/integration/utils/run-calendar-channel-events-import.util';
+import { runCalendarChannelListFetch } from 'test/integration/utils/run-calendar-channel-list-fetch.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
+
+const HANDLE = '[email protected]';
+
+const UNMATCHED_HANDLE = `unmatched-${randomUUID()}@acme.com`;
+const UNMATCHED_ATTENDEE = `attendee-${randomUUID()}@acme.com`;
+
+const findParticipantPersonIds = async (
+ objectMetadataSingularName: string,
+ objectMetadataPluralName: string,
+ handle: string,
+) => {
+ const participants = await findRecordNodesByFilter<{
+ personId: string | null;
+ }>(objectMetadataSingularName, objectMetadataPluralName, 'personId', {
+ handle: { eq: handle },
+ });
+
+ return participants.map((participant) => participant.personId);
+};
+
+describe('Participant matching on person creation (integration)', () => {
+ const gmail = setupGoogleMock({
+ handle: HANDLE,
+ inbox: [gmailMessage({ from: UNMATCHED_HANDLE, to: HANDLE })],
+ });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+
+ await getCoreRepository<MessageChannelEntity>(MessageChannelEntity).update(
+ { id: channel.channelId },
+ {
+ isContactAutoCreationEnabled: false,
+ contactAutoCreationPolicy: MessageChannelContactAutoCreationPolicy.NONE,
+ },
+ );
+
+ await getCoreRepository<CalendarChannelEntity>(
+ CalendarChannelEntity,
+ ).update(
+ { id: channel.calendarChannelId },
+ { isContactAutoCreationEnabled: false },
+ );
+
+ await runMessageChannelSync(channel.channelId);
+
+ gmail.serveCalendarEvents([
+ googleCalendarEvent({
+ summary: `Calendar event ${randomUUID()}`,
+ attendees: [{ email: UNMATCHED_ATTENDEE }],
+ }),
+ ]);
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+ await runCalendarChannelEventsImport(channel.calendarChannelId);
+ }, 180000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('leaves the imported participants unmatched while no person owns the handle', async () => {
+ expect(
+ await findParticipantPersonIds(
+ 'messageParticipant',
+ 'messageParticipants',
+ UNMATCHED_HANDLE,
+ ),
+ ).toEqual([null]);
+
+ expect(
+ await findParticipantPersonIds(
+ 'calendarEventParticipant',
+ 'calendarEventParticipants',
+ UNMATCHED_ATTENDEE,
+ ),
+ ).toEqual([null]);
+ }, 60000);
+
+ it('matches both message and calendar participants when the person is created', async () => {
+ const createPerson = async (primaryEmail: string) => {
+ const response = await makeGraphqlAPIRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: 'person',
+ gqlFields: 'id',
+ data: { emails: { primaryEmail } },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.createPerson.id as string;
+ };
+
+ const messagePersonId = await createPerson(UNMATCHED_HANDLE);
+ const attendeePersonId = await createPerson(UNMATCHED_ATTENDEE);
+
+ await waitForAllJobsToFinish();
+
+ expect(
+ await findParticipantPersonIds(
+ 'messageParticipant',
+ 'messageParticipants',
+ UNMATCHED_HANDLE,
+ ),
+ ).toEqual([messagePersonId]);
+
+ expect(
+ await findParticipantPersonIds(
+ 'calendarEventParticipant',
+ 'calendarEventParticipants',
+ UNMATCHED_ATTENDEE,
+ ),
+ ).toEqual([attendeePersonId]);
+ }, 120000);
+});
diff --git a/packages/twenty-server/test/integration/google/messaging/token-failure-modes.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/token-failure-modes.integration-spec.ts
new file mode 100644
index 00000000000..cd2b874c3cb
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/token-failure-modes.integration-spec.ts
@@ -0,0 +1,124 @@
+import {
+ ConnectedAccountProvider,
+ MessageChannelSyncStage,
+ MessageChannelSyncStatus,
+} from 'twenty-shared/types';
+
+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { queryMessageChannel } from 'test/integration/utils/query-messaging.util';
+import { resetMessageChannelSyncState } from 'test/integration/utils/reset-channel-sync-state.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+
+const HANDLE = '[email protected]';
+
+// The refresh service only mints a new token once the stored credentials are
+// stale; a recent refresh short-circuits to the tokens already on the account.
+const STALE_CREDENTIALS_AT = new Date(Date.now() - 56 * 60 * 1000);
+const FRESH_CREDENTIALS_AT = new Date();
+
+describe('Gmail token failure modes (integration)', () => {
+ setupGoogleMock({ handle: HANDLE });
+
+ const connectedAccountRepository = getCoreRepository<ConnectedAccountEntity>(
+ ConnectedAccountEntity,
+ );
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+ let storedAccount: ConnectedAccountEntity;
+
+ const restoreAccount = () =>
+ connectedAccountRepository.update(
+ { id: channel.connectedAccountId },
+ {
+ accessToken: storedAccount.accessToken,
+ refreshToken: storedAccount.refreshToken,
+ provider: storedAccount.provider,
+ lastCredentialsRefreshedAt: storedAccount.lastCredentialsRefreshedAt,
+ authFailedAt: null,
+ },
+ );
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+
+ storedAccount = await connectedAccountRepository.findOneByOrFail({
+ id: channel.connectedAccountId,
+ });
+ }, 60000);
+
+ afterAll(async () => {
+ await restoreAccount().catch(() => undefined);
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ beforeEach(async () => {
+ await restoreAccount();
+ await resetMessageChannelSyncState(channel.channelId);
+ });
+
+ it('fails the channel as insufficient-permissions when the refresh token is gone', async () => {
+ await connectedAccountRepository.update(
+ { id: channel.connectedAccountId },
+ {
+ refreshToken: null,
+ lastCredentialsRefreshedAt: STALE_CREDENTIALS_AT,
+ },
+ );
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS,
+ );
+ expect(channelState.syncStage).toBe(MessageChannelSyncStage.FAILED);
+ }, 60000);
+
+ it('fails the channel as unknown when the stored access token is gone', async () => {
+ await connectedAccountRepository.update(
+ { id: channel.connectedAccountId },
+ {
+ accessToken: null,
+ lastCredentialsRefreshedAt: FRESH_CREDENTIALS_AT,
+ },
+ );
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStage).toBe(MessageChannelSyncStage.FAILED);
+ }, 60000);
+
+ // The driver rejects the unsupported provider before the refresh service is
+ // reached, so this surfaces as a permissions failure.
+ it('fails the channel as insufficient-permissions when the provider cannot refresh tokens', async () => {
+ await connectedAccountRepository.update(
+ { id: channel.connectedAccountId },
+ {
+ provider: ConnectedAccountProvider.IMAP_SMTP_CALDAV,
+ lastCredentialsRefreshedAt: STALE_CREDENTIALS_AT,
+ },
+ );
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS,
+ );
+ expect(channelState.syncStage).toBe(MessageChannelSyncStage.FAILED);
+ }, 60000);
+});
diff --git a/packages/twenty-server/test/integration/google/mocks/gmail-message.util.ts b/packages/twenty-server/test/integration/google/mocks/gmail-message.util.ts
index 02fe2fe4e04..625c001331f 100644
--- a/packages/twenty-server/test/integration/google/mocks/gmail-message.util.ts
+++ b/packages/twenty-server/test/integration/google/mocks/gmail-message.util.ts
@@ -2,9 +2,16 @@ import { randomUUID } from 'node:crypto';
import { type gmail_v1 } from 'googleapis';
-export const gmailMessage = (
- overrides: Partial<gmail_v1.Schema$Message> = {},
-): gmail_v1.Schema$Message => {
+type GmailMessageOverrides = Partial<gmail_v1.Schema$Message> & {
+ from?: string;
+ to?: string;
+};
+
+export const gmailMessage = ({
+ from,
+ to,
+ ...overrides
+}: GmailMessageOverrides = {}): gmail_v1.Schema$Message => {
const id = overrides.id ?? `gmail-msg-${randomUUID()}`;
return {
@@ -16,8 +23,8 @@ export const gmailMessage = (
payload: {
mimeType: 'text/plain',
headers: [
- { name: 'From', value: `sender-${id}@example.com` },
- { name: 'To', value: `recipient-${id}@example.com` },
+ { name: 'From', value: from ?? `sender-${id}@example.com` },
+ { name: 'To', value: to ?? `recipient-${id}@example.com` },
{ name: 'Subject', value: `Subject ${id}` },
{ name: 'Message-ID', value: `<${id}@example.com>` },
{ name: 'Date', value: 'Wed, 15 Nov 2023 00:00:00 +0000' },
diff --git a/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.ts b/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.ts
index 634884ab275..c6d26ffc69d 100644
--- a/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.ts
+++ b/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.ts
@@ -33,9 +33,33 @@ export type GoogleMock = {
) => void;
rateLimitMessageList: (retryAfterIso: string) => void;
rateLimitCalendarEventList: () => void;
+ failMessageList: (failure: GoogleApiFailure) => void;
+ failCalendarEventList: (failure: GoogleApiFailure) => void;
declineTokenRefresh: () => void;
};
+export type GoogleApiFailure = {
+ status: number;
+ reason: string;
+ message: string;
+};
+
+const googleApiErrorResponse = ({
+ status,
+ reason,
+ message,
+}: GoogleApiFailure) =>
+ HttpResponse.json(
+ {
+ error: {
+ code: status,
+ message,
+ errors: [{ reason, message }],
+ },
+ },
+ { status },
+ );
+
export const setupGoogleMock = ({
handle,
inbox = [],
@@ -106,6 +130,24 @@ export const setupGoogleMock = ({
),
),
),
+ // A channel carrying a sync cursor fetches through the history endpoint
+ // rather than the message list, so both have to fail for the failure to
+ // surface regardless of which path the channel takes.
+ failMessageList: (failure) =>
+ httpMock.use(
+ http.get('*/gmail/v1/users/me/messages', () =>
+ googleApiErrorResponse(failure),
+ ),
+ http.get('*/gmail/v1/users/me/history', () =>
+ googleApiErrorResponse(failure),
+ ),
+ ),
+ failCalendarEventList: (failure) =>
+ httpMock.use(
+ http.get(GOOGLE_CALENDAR_EVENTS_URL, () =>
+ googleApiErrorResponse(failure),
+ ),
+ ),
declineTokenRefresh: () =>
httpMock.use(
...GOOGLE_TOKEN_URLS.map((url) =>
diff --git a/packages/twenty-server/test/integration/microsoft/calendar/import-error-mapping.integration-spec.ts b/packages/twenty-server/test/integration/microsoft/calendar/import-error-mapping.integration-spec.ts
new file mode 100644
index 00000000000..dae6e418ca0
--- /dev/null
+++ b/packages/twenty-server/test/integration/microsoft/calendar/import-error-mapping.integration-spec.ts
@@ -0,0 +1,166 @@
+import {
+ CalendarChannelSyncStage,
+ CalendarChannelSyncStatus,
+ ConnectedAccountProvider,
+} from 'twenty-shared/types';
+
+import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { MICROSOFT_PERMANENT_ACCOUNT_ERROR_CODES } from 'src/modules/connected-account/constants/microsoft-permanent-account-error-codes.constant';
+
+import {
+ type MicrosoftGraphFailure,
+ setupMicrosoftMock,
+} from 'test/integration/microsoft/mocks/setup-microsoft-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import {
+ queryCalendarChannel,
+ queryConnectedAccount,
+} from 'test/integration/utils/query-messaging.util';
+import { resetCalendarChannelSyncState } from 'test/integration/utils/reset-channel-sync-state.util';
+import { runCalendarChannelListFetch } from 'test/integration/utils/run-calendar-channel-list-fetch.util';
+
+const HANDLE = '[email protected]';
+
+// 429 and 503 are retried inside the Graph client before the driver sees them,
+// so they are exercised through the messaging suite instead.
+const TEMPORARY_FAILURES: [string, MicrosoftGraphFailure][] = [
+ [
+ 'a 500 response',
+ { status: 500, code: 'InternalServerError', message: 'Internal error' },
+ ],
+];
+
+describe('Microsoft calendar import error mapping (integration)', () => {
+ const microsoft = setupMicrosoftMock({ handle: HANDLE });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.MICROSOFT,
+ handle: HANDLE,
+ });
+ }, 60000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ beforeEach(async () => {
+ await resetCalendarChannelSyncState(channel.calendarChannelId, '');
+
+ await getCoreRepository<ConnectedAccountEntity>(
+ ConnectedAccountEntity,
+ ).update({ id: channel.connectedAccountId }, { authFailedAt: null });
+ });
+
+ it.each(MICROSOFT_PERMANENT_ACCOUNT_ERROR_CODES)(
+ 'fails the calendar channel as insufficient-permissions on the permanent account error %s',
+ async (code) => {
+ microsoft.failCalendarDelta({
+ status: 403,
+ code,
+ message: 'The mailbox is unavailable',
+ });
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+
+ const channelState = await queryCalendarChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ CalendarChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS,
+ );
+ expect(channelState.syncStage).toBe(CalendarChannelSyncStage.FAILED);
+
+ const account = await queryConnectedAccount(channel.connectedAccountId);
+
+ expect(account.authFailedAt).not.toBeNull();
+ },
+ 60000,
+ );
+
+ it.each(TEMPORARY_FAILURES)(
+ 'throttles the calendar channel without failing it on %s',
+ async (_label, failure) => {
+ microsoft.failCalendarDelta(failure);
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+
+ const channelState = await queryCalendarChannel(channel);
+
+ expect(channelState.throttleFailureCount).toBe(1);
+ expect(channelState.syncStage).toBe(
+ CalendarChannelSyncStage.CALENDAR_EVENT_LIST_FETCH_PENDING,
+ );
+ expect(channelState.syncStatus).not.toBe(
+ CalendarChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ },
+ 60000,
+ );
+
+ it('fails the calendar channel as unknown on a 400 bad request', async () => {
+ microsoft.failCalendarDelta({
+ status: 400,
+ code: 'BadRequest',
+ message: 'Invalid delta token',
+ });
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+
+ const channelState = await queryCalendarChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ CalendarChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStage).toBe(CalendarChannelSyncStage.FAILED);
+ }, 60000);
+
+ it('leaves the calendar channel untouched on a 404 during list fetch', async () => {
+ microsoft.failCalendarDelta({
+ status: 404,
+ code: 'ResourceNotFound',
+ message: 'Resource not found',
+ });
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+
+ const channelState = await queryCalendarChannel(channel);
+
+ expect(channelState.syncStatus).not.toBe(
+ CalendarChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.throttleFailureCount).toBe(0);
+
+ const storedChannel = await getCoreRepository<CalendarChannelEntity>(
+ CalendarChannelEntity,
+ ).findOneByOrFail({ id: channel.calendarChannelId });
+
+ expect(storedChannel.syncCursor).toBeFalsy();
+ }, 60000);
+
+ it('restarts the calendar channel from a clean cursor on a 410 expired delta token', async () => {
+ microsoft.failCalendarDelta({
+ status: 410,
+ code: 'syncStateNotFound',
+ message: 'The delta token is expired',
+ });
+
+ await runCalendarChannelListFetch(channel.calendarChannelId);
+
+ const channelState = await queryCalendarChannel(channel);
+
+ expect(channelState.syncStage).toBe(
+ CalendarChannelSyncStage.CALENDAR_EVENT_LIST_FETCH_PENDING,
+ );
+ expect(channelState.throttleFailureCount).toBe(0);
+
+ const storedChannel = await getCoreRepository<CalendarChannelEntity>(
+ CalendarChannelEntity,
+ ).findOneByOrFail({ id: channel.calendarChannelId });
+
+ expect(storedChannel.syncCursor).toBeFalsy();
+ }, 60000);
+});
diff --git a/packages/twenty-server/test/integration/microsoft/messaging/import-error-mapping.integration-spec.ts b/packages/twenty-server/test/integration/microsoft/messaging/import-error-mapping.integration-spec.ts
new file mode 100644
index 00000000000..ebb8e6de9b6
--- /dev/null
+++ b/packages/twenty-server/test/integration/microsoft/messaging/import-error-mapping.integration-spec.ts
@@ -0,0 +1,173 @@
+import {
+ ConnectedAccountProvider,
+ MessageChannelSyncStage,
+ MessageChannelSyncStatus,
+} from 'twenty-shared/types';
+
+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import { MICROSOFT_PERMANENT_ACCOUNT_ERROR_CODES } from 'src/modules/connected-account/constants/microsoft-permanent-account-error-codes.constant';
+
+import {
+ type MicrosoftGraphFailure,
+ setupMicrosoftMock,
+} from 'test/integration/microsoft/mocks/setup-microsoft-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import {
+ queryConnectedAccount,
+ queryMessageChannel,
+} from 'test/integration/utils/query-messaging.util';
+import { resetMessageChannelSyncState } from 'test/integration/utils/reset-channel-sync-state.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+
+const HANDLE = '[email protected]';
+
+const TEMPORARY_FAILURES: [string, MicrosoftGraphFailure][] = [
+ [
+ 'a 429 throttled response',
+ {
+ status: 429,
+ code: 'ApplicationThrottled',
+ message: 'Too many requests',
+ },
+ ],
+ [
+ 'a 500 response',
+ { status: 500, code: 'InternalServerError', message: 'Internal error' },
+ ],
+ [
+ 'a 503 response',
+ { status: 503, code: 'ServiceUnavailable', message: 'Service unavailable' },
+ ],
+];
+
+describe('Microsoft messaging import error mapping (integration)', () => {
+ const microsoft = setupMicrosoftMock({ handle: HANDLE });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.MICROSOFT,
+ handle: HANDLE,
+ });
+ }, 60000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ beforeEach(async () => {
+ await resetMessageChannelSyncState(channel.channelId, '');
+
+ await getCoreRepository<ConnectedAccountEntity>(
+ ConnectedAccountEntity,
+ ).update({ id: channel.connectedAccountId }, { authFailedAt: null });
+ });
+
+ it.each(MICROSOFT_PERMANENT_ACCOUNT_ERROR_CODES)(
+ 'fails the channel as insufficient-permissions on the permanent account error %s',
+ async (code) => {
+ microsoft.failMessageDelta({
+ status: 403,
+ code,
+ message: 'The mailbox is unavailable',
+ });
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS,
+ );
+ expect(channelState.syncStage).toBe(MessageChannelSyncStage.FAILED);
+
+ const account = await queryConnectedAccount(channel.connectedAccountId);
+
+ expect(account.authFailedAt).not.toBeNull();
+ },
+ 60000,
+ );
+
+ it.each(TEMPORARY_FAILURES)(
+ 'throttles the channel without failing it on %s',
+ async (_label, failure) => {
+ microsoft.failMessageDelta(failure);
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.throttleFailureCount).toBe(1);
+ expect(channelState.syncStage).toBe(
+ MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+ );
+ expect(channelState.syncStatus).not.toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ },
+ 60000,
+ );
+
+ it('fails the channel as unknown on a 400 bad request', async () => {
+ microsoft.failMessageDelta({
+ status: 400,
+ code: 'BadRequest',
+ message: 'Invalid delta token',
+ });
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStage).toBe(MessageChannelSyncStage.FAILED);
+ }, 60000);
+
+ it('fails the channel as unknown when the message list is not found', async () => {
+ microsoft.failMessageDelta({
+ status: 404,
+ code: 'ResourceNotFound',
+ message: 'Resource not found',
+ });
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStatus).toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.syncStage).toBe(MessageChannelSyncStage.FAILED);
+ }, 60000);
+
+ it('restarts the channel from a clean cursor on a 410 expired delta token', async () => {
+ microsoft.failMessageDelta({
+ status: 410,
+ code: 'syncStateNotFound',
+ message: 'The delta token is expired',
+ });
+
+ await runMessageChannelSync(channel.channelId);
+
+ const channelState = await queryMessageChannel(channel);
+
+ expect(channelState.syncStage).toBe(
+ MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+ );
+ expect(channelState.syncStatus).not.toBe(
+ MessageChannelSyncStatus.FAILED_UNKNOWN,
+ );
+ expect(channelState.throttleFailureCount).toBe(0);
+
+ const storedChannel = await getCoreRepository<MessageChannelEntity>(
+ MessageChannelEntity,
+ ).findOneByOrFail({ id: channel.channelId });
+
+ expect(storedChannel.syncCursor).toBeFalsy();
+ }, 60000);
+});
diff --git a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-calendar-event.util.ts b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-calendar-event.util.ts
index e4b36e5f47e..a9147b96781 100644
--- a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-calendar-event.util.ts
+++ b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-calendar-event.util.ts
@@ -2,7 +2,9 @@ import { randomUUID } from 'node:crypto';
import { type Event } from '@microsoft/microsoft-graph-types';
-export const microsoftCalendarEvent = (overrides: Partial<Event> = {}): Event => {
+export const microsoftCalendarEvent = (
+ overrides: Partial<Event> = {},
+): Event => {
const id = overrides.id ?? `microsoft-calendar-event-${randomUUID()}`;
return {
diff --git a/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.ts b/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.ts
index 0a91c9ea041..d87d1cbfd3c 100644
--- a/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.ts
+++ b/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.ts
@@ -1,4 +1,5 @@
import { type Event, type MailFolder } from '@microsoft/microsoft-graph-types';
+import { http, HttpResponse } from 'msw';
import { setupHttpMock } from 'test/integration/utils/http-mock.util';
import { microsoftAuthHandlers } from 'test/integration/microsoft/mocks/microsoft-auth-handlers.util';
@@ -27,8 +28,23 @@ export type MicrosoftMock = {
options?: { deltaToken?: string },
) => void;
failSubscriptionRenewal: () => void;
+ failMessageDelta: (failure: MicrosoftGraphFailure) => void;
+ failCalendarDelta: (failure: MicrosoftGraphFailure) => void;
};
+export type MicrosoftGraphFailure = {
+ status: number;
+ code: string;
+ message: string;
+};
+
+const microsoftGraphErrorResponse = ({
+ status,
+ code,
+ message,
+}: MicrosoftGraphFailure) =>
+ HttpResponse.json({ error: { code, message } }, { status });
+
export const setupMicrosoftMock = ({
handle,
folders = DEFAULT_FOLDERS,
@@ -62,5 +78,35 @@ export const setupMicrosoftMock = ({
renewalFails: true,
}),
),
+ // The driver issues the per-folder delta requests inside a /$batch POST, so
+ // the failure has to come back as the status on each sub-response rather
+ // than on the delta route itself.
+ failMessageDelta: (failure) =>
+ httpMock.use(
+ http.post('*/$batch', async ({ request }) => {
+ const { requests } = (await request.json()) as {
+ requests: { id: string }[];
+ };
+
+ return HttpResponse.json({
+ responses: requests.map(({ id }) => ({
+ id,
+ status: failure.status,
+ body: {
+ error: { code: failure.code, message: failure.message },
+ },
+ })),
+ });
+ }),
+ http.get('*/messages/delta', () =>
+ microsoftGraphErrorResponse(failure),
+ ),
+ ),
+ failCalendarDelta: (failure) =>
+ httpMock.use(
+ http.get('*/me/calendar/events/delta', () =>
+ microsoftGraphErrorResponse(failure),
+ ),
+ ),
};
};
diff --git a/packages/twenty-server/test/integration/utils/find-imported-records.util.ts b/packages/twenty-server/test/integration/utils/find-imported-records.util.ts
index 6d6cd3e56e1..ab2d1867243 100644
--- a/packages/twenty-server/test/integration/utils/find-imported-records.util.ts
+++ b/packages/twenty-server/test/integration/utils/find-imported-records.util.ts
@@ -25,3 +25,15 @@ export const findImportedCalendarEventTitles = async (
return events.map((event) => event.title).sort();
};
+
+export const findCreatedPeopleEmails = async (
+ primaryEmails: string[],
+): Promise<string[]> => {
+ const people = await findRecordNodesByFilter<{
+ emails: { primaryEmail: string };
+ }>('person', 'people', 'emails { primaryEmail }', {
+ emails: { primaryEmail: { in: primaryEmails } },
+ });
+
+ return people.map((person) => person.emails.primaryEmail).sort();
+};
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 ca9024a71a9..64d66bfa046 100644
--- a/packages/twenty-server/test/integration/utils/query-messaging.util.ts
+++ b/packages/twenty-server/test/integration/utils/query-messaging.util.ts
@@ -1,6 +1,9 @@
import gql from 'graphql-tag';
-import { type MessageFolderImportPolicy } from 'twenty-shared/types';
+import {
+ type CalendarChannelContactAutoCreationPolicy,
+ type MessageFolderImportPolicy,
+} from 'twenty-shared/types';
import { type CalendarChannelDTO } from 'src/engine/metadata-modules/calendar-channel/dtos/calendar-channel.dto';
import { type ConnectedAccountDTO } from 'src/engine/metadata-modules/connected-account/dtos/connected-account.dto';
@@ -52,6 +55,8 @@ export type CalendarChannelDto = Pick<
| 'syncStage'
| 'syncStageStartedAt'
| 'throttleFailureCount'
+ | 'isContactAutoCreationEnabled'
+ | 'contactAutoCreationPolicy'
>;
export type ConnectedAccountDto = Pick<
@@ -68,6 +73,7 @@ type MessageChannelUpdate = {
type CalendarChannelUpdate = {
isSyncEnabled?: boolean;
isContactAutoCreationEnabled?: boolean;
+ contactAutoCreationPolicy?: CalendarChannelContactAutoCreationPolicy;
};
const MESSAGE_CHANNEL_FIELDS = gql`
@@ -161,6 +167,8 @@ export const queryCalendarChannels = async (
syncStage
syncStageStartedAt
throttleFailureCount
+ isContactAutoCreationEnabled
+ contactAutoCreationPolicy
}
}
`,
diff --git a/packages/twenty-server/test/integration/utils/reset-channel-sync-state.util.ts b/packages/twenty-server/test/integration/utils/reset-channel-sync-state.util.ts
new file mode 100644
index 00000000000..d03b70c82ba
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/reset-channel-sync-state.util.ts
@@ -0,0 +1,44 @@
+import {
+ CalendarChannelSyncStage,
+ CalendarChannelSyncStatus,
+ MessageChannelSyncStage,
+ MessageChannelSyncStatus,
+} from 'twenty-shared/types';
+
+import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+
+export const resetMessageChannelSyncState = async (
+ messageChannelId: string,
+ syncCursor = 'reset-cursor',
+): Promise<void> => {
+ await getCoreRepository<MessageChannelEntity>(MessageChannelEntity).update(
+ { id: messageChannelId },
+ {
+ syncStatus: MessageChannelSyncStatus.ACTIVE,
+ syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+ syncStageStartedAt: null,
+ throttleFailureCount: 0,
+ throttleRetryAfter: null,
+ syncCursor,
+ },
+ );
+};
+
+export const resetCalendarChannelSyncState = async (
+ calendarChannelId: string,
+ syncCursor = 'reset-cursor',
+): Promise<void> => {
+ await getCoreRepository<CalendarChannelEntity>(CalendarChannelEntity).update(
+ { id: calendarChannelId },
+ {
+ syncStatus: CalendarChannelSyncStatus.ACTIVE,
+ syncStage: CalendarChannelSyncStage.CALENDAR_EVENT_LIST_FETCH_PENDING,
+ syncStageStartedAt: null,
+ throttleFailureCount: 0,
+ syncCursor,
+ },
+ );
+};