The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Handle Microsoft calendar token refresh failures gracefully (#23958)
neo773d11f8e2ca147
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/microsoft-calendar-driver.module.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/microsoft-calendar-driver.module.tsindex 143382d7b75..afbe76e53ab 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/microsoft-calendar-driver.module.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/microsoft-calendar-driver.module.ts@@ -1,7 +1,10 @@import { Module } from '@nestjs/common';+import { MicrosoftCalendarEventListFetchErrorHandler } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-event-list-fetch-error-handler.service';+import { MicrosoftCalendarEventsImportErrorHandler } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-events-import-error-handler.service';import { MicrosoftCalendarGetEventsService } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-get-events.service';import { MicrosoftCalendarImportEventsService } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-import-events.service';+import { MicrosoftCalendarNetworkErrorHandler } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-network-error-handler.service';import { OAuth2ClientManagerModule } from 'src/modules/connected-account/oauth2-client-manager/oauth2-client-manager.module';@Module({@@ -9,10 +12,15 @@ import { OAuth2ClientManagerModule } from 'src/modules/connected-account/oauth2-providers: [MicrosoftCalendarGetEventsService,MicrosoftCalendarImportEventsService,+ MicrosoftCalendarNetworkErrorHandler,+ MicrosoftCalendarEventListFetchErrorHandler,+ MicrosoftCalendarEventsImportErrorHandler,],exports: [MicrosoftCalendarGetEventsService,MicrosoftCalendarImportEventsService,+ MicrosoftCalendarEventListFetchErrorHandler,+ MicrosoftCalendarEventsImportErrorHandler,],})export class MicrosoftCalendarDriverModule {}diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-event-list-fetch-error-handler.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-event-list-fetch-error-handler.service.tsnew file mode 100644index 00000000000..ba574210107--- /dev/null+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-event-list-fetch-error-handler.service.ts@@ -0,0 +1,31 @@+import { Injectable, Logger } from '@nestjs/common';++import { MicrosoftCalendarNetworkErrorHandler } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-network-error-handler.service';+import { parseMicrosoftCalendarError } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/parse-microsoft-calendar-error.util';++@Injectable()+export class MicrosoftCalendarEventListFetchErrorHandler {+ private readonly logger = new Logger(+ MicrosoftCalendarEventListFetchErrorHandler.name,+ );++ constructor(+ private readonly microsoftCalendarNetworkErrorHandler: MicrosoftCalendarNetworkErrorHandler,+ ) {}++ // oxlint-disable-next-line typescript/no-explicit-any+ public handleError(error: any): never {+ this.logger.error(+ `Error fetching calendar event list: ${JSON.stringify(error)}`,+ );++ const networkError =+ this.microsoftCalendarNetworkErrorHandler.handleError(error);++ if (networkError) {+ throw networkError;+ }++ throw parseMicrosoftCalendarError(error);+ }+}diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-events-import-error-handler.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-events-import-error-handler.service.tsnew file mode 100644index 00000000000..93bcce3a13d--- /dev/null+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-events-import-error-handler.service.ts@@ -0,0 +1,31 @@+import { Injectable, Logger } from '@nestjs/common';++import { MicrosoftCalendarNetworkErrorHandler } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-network-error-handler.service';+import { parseMicrosoftCalendarError } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/parse-microsoft-calendar-error.util';++@Injectable()+export class MicrosoftCalendarEventsImportErrorHandler {+ private readonly logger = new Logger(+ MicrosoftCalendarEventsImportErrorHandler.name,+ );++ constructor(+ private readonly microsoftCalendarNetworkErrorHandler: MicrosoftCalendarNetworkErrorHandler,+ ) {}++ // oxlint-disable-next-line typescript/no-explicit-any+ public handleError(error: any): never {+ this.logger.error(+ `Error fetching calendar events: ${JSON.stringify(error)}`,+ );++ const networkError =+ this.microsoftCalendarNetworkErrorHandler.handleError(error);++ if (networkError) {+ throw networkError;+ }++ throw parseMicrosoftCalendarError(error);+ }+}diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-get-events.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-get-events.service.tsindex 90e00142c25..95366764c65 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-get-events.service.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-get-events.service.ts@@ -6,7 +6,7 @@ import {type PageIteratorCallback,} from '@microsoft/microsoft-graph-client';-import { parseMicrosoftCalendarError } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/parse-microsoft-calendar-error.util';+import { MicrosoftCalendarEventListFetchErrorHandler } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-event-list-fetch-error-handler.service';import { type GetCalendarEventsResponse } from 'src/modules/calendar/calendar-event-import-manager/services/calendar-get-events.service';import { MicrosoftOAuth2ClientProvider } from 'src/modules/connected-account/oauth2-client-manager/drivers/microsoft/microsoft-oauth2-client.provider';import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';@@ -15,48 +15,48 @@ import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connectexport class MicrosoftCalendarGetEventsService {constructor(private readonly microsoftOAuth2ClientProvider: MicrosoftOAuth2ClientProvider,+ private readonly microsoftCalendarEventListFetchErrorHandler: MicrosoftCalendarEventListFetchErrorHandler,) {}public async getCalendarEvents(connectedAccount: Pick<ConnectedAccountEntity, 'provider' | 'id'>,syncCursor?: string,): Promise<GetCalendarEventsResponse> {- try {- const microsoftClient =- await this.microsoftOAuth2ClientProvider.getClient(connectedAccount.id);- const eventIds: string[] = [];- const eventIdsToDelete: string[] = [];-- const response: PageCollection = await microsoftClient- .api(syncCursor || '/me/calendar/events/delta')- .version('beta')- .get();-- const callback: PageIteratorCallback = (data) => {- if (data['@removed']) {- eventIdsToDelete.push(data.id);- } else {- eventIds.push(data.id);- }-- return true;- };-- const pageIterator = new PageIterator(- microsoftClient,- response,- callback,+ const microsoftClient = await this.microsoftOAuth2ClientProvider.getClient(+ connectedAccount.id,+ );++ const eventIds: string[] = [];+ const eventIdsToDelete: string[] = [];++ const response: PageCollection = await microsoftClient+ .api(syncCursor || '/me/calendar/events/delta')+ .version('beta')+ .get()+ .catch((error: unknown) =>+ this.microsoftCalendarEventListFetchErrorHandler.handleError(error),);- await pageIterator.iterate();+ const callback: PageIteratorCallback = (data) => {+ if (data['@removed']) {+ eventIdsToDelete.push(data.id);+ } else {+ eventIds.push(data.id);+ }- return {- calendarEventIds: eventIds,- calendarEventIdsToDelete: eventIdsToDelete,- nextSyncCursor: pageIterator.getDeltaLink() || '',- };- } catch (error) {- throw parseMicrosoftCalendarError(error);- }+ return true;+ };++ const pageIterator = new PageIterator(microsoftClient, response, callback);++ await pageIterator.iterate().catch((error: unknown) => {+ this.microsoftCalendarEventListFetchErrorHandler.handleError(error);+ });++ return {+ calendarEventIds: eventIds,+ calendarEventIdsToDelete: eventIdsToDelete,+ nextSyncCursor: pageIterator.getDeltaLink() || '',+ };}}diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-import-events.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-import-events.service.tsindex 449d4ccff8c..3d5a7abc5af 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-import-events.service.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-import-events.service.ts@@ -2,8 +2,8 @@ import { Injectable } from '@nestjs/common';import { type Event } from '@microsoft/microsoft-graph-types';+import { MicrosoftCalendarEventsImportErrorHandler } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-events-import-error-handler.service';import { formatMicrosoftCalendarEvents } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/format-microsoft-calendar-event.util';-import { parseMicrosoftCalendarError } from 'src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/parse-microsoft-calendar-error.util';import { type FetchedCalendarEvent } from 'src/modules/calendar/common/types/fetched-calendar-event';import { MicrosoftOAuth2ClientProvider } from 'src/modules/connected-account/oauth2-client-manager/drivers/microsoft/microsoft-oauth2-client.provider';import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';@@ -12,30 +12,31 @@ import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connectexport class MicrosoftCalendarImportEventsService {constructor(private readonly microsoftOAuth2ClientProvider: MicrosoftOAuth2ClientProvider,+ private readonly microsoftCalendarEventsImportErrorHandler: MicrosoftCalendarEventsImportErrorHandler,) {}public async getCalendarEvents(connectedAccount: Pick<ConnectedAccountEntity, 'provider' | 'id'>,eventExternalIds: string[],): Promise<FetchedCalendarEvent[]> {- try {- const microsoftClient =- await this.microsoftOAuth2ClientProvider.getClient(connectedAccount.id);-- const events: Event[] = [];-- for (const eventExternalId of eventExternalIds) {- const event = await microsoftClient- .api(`/me/calendar/events/${eventExternalId}`)- .header('Prefer', 'outlook.body-content-type="text"')- .get();-- events.push(event);- }-- return formatMicrosoftCalendarEvents(events);- } catch (error) {- throw parseMicrosoftCalendarError(error);+ const microsoftClient = await this.microsoftOAuth2ClientProvider.getClient(+ connectedAccount.id,+ );++ const events: Event[] = [];++ for (const eventExternalId of eventExternalIds) {+ const event = await microsoftClient+ .api(`/me/calendar/events/${eventExternalId}`)+ .header('Prefer', 'outlook.body-content-type="text"')+ .get()+ .catch((error: unknown) =>+ this.microsoftCalendarEventsImportErrorHandler.handleError(error),+ );++ events.push(event);}++ return formatMicrosoftCalendarEvents(events);}}diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-network-error-handler.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-network-error-handler.service.tsnew file mode 100644index 00000000000..60311f6301e--- /dev/null+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/services/microsoft-calendar-network-error-handler.service.ts@@ -0,0 +1,26 @@+import { Injectable } from '@nestjs/common';++import {+ CalendarEventImportDriverException,+ CalendarEventImportDriverExceptionCode,+} from 'src/modules/calendar/calendar-event-import-manager/drivers/exceptions/calendar-event-import-driver.exception';+import { isMicrosoftClientTemporaryError } from 'src/modules/messaging/message-import-manager/drivers/microsoft/utils/is-temporary-error.utils';++@Injectable()+export class MicrosoftCalendarNetworkErrorHandler {+ // oxlint-disable-next-line typescript/no-explicit-any+ public handleError(error: any): CalendarEventImportDriverException | null {+ const isBodyString = error.body && typeof error.body === 'string';+ const isTemporaryError =+ isBodyString && isMicrosoftClientTemporaryError(error.body);++ if (isTemporaryError) {+ return new CalendarEventImportDriverException(+ `code: ${error.code} - body: ${error.body}`,+ CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,+ );+ }++ return null;+ }+}diff --git a/packages/twenty-server/test/integration/microsoft/calendar/token-refresh-failure.integration-spec.ts b/packages/twenty-server/test/integration/microsoft/calendar/token-refresh-failure.integration-spec.tsnew file mode 100644index 00000000000..205eec0ca99--- /dev/null+++ b/packages/twenty-server/test/integration/microsoft/calendar/token-refresh-failure.integration-spec.ts@@ -0,0 +1,63 @@+import {+ CalendarChannelSyncStage,+ CalendarChannelSyncStatus,+ ConnectedAccountProvider,+} from 'twenty-shared/types';++import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';++import { 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 { runCalendarChannelListFetch } from 'test/integration/utils/run-calendar-channel-list-fetch.util';++const HANDLE = '[email protected]';++const EXPIRED_CREDENTIALS_AT = new Date(Date.now() - 56 * 60 * 1000);++describe('Microsoft calendar token refresh failure (integration)', () => {+ const microsoft = setupMicrosoftMock({ handle: HANDLE });++ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;++ beforeAll(async () => {+ channel = await connectMessagingAccount({+ provider: ConnectedAccountProvider.MICROSOFT,+ handle: HANDLE,+ });+ }, 120000);++ afterAll(async () => {+ await channel?.cleanup().catch(() => undefined);+ });++ it('fails the channel as insufficient-permissions when the refresh token is declined', async () => {+ // resolveTokens short-circuits on a still-valid access token, so the refresh+ // token is only consulted once lastCredentialsRefreshedAt is stale.+ await getCoreRepository<ConnectedAccountEntity>(+ ConnectedAccountEntity,+ ).update(+ { id: channel.connectedAccountId },+ { lastCredentialsRefreshedAt: EXPIRED_CREDENTIALS_AT },+ );++ microsoft.declineTokenRefresh();++ 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);+});diff --git a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.ts b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.tsindex 32024726adc..f1418fe5725 100644--- a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.ts+++ b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.ts@@ -2,8 +2,11 @@ import { http, HttpResponse } from 'msw';import { type MswHandler } from 'test/integration/utils/http-mock.util';+export const MICROSOFT_TOKEN_URL =+ 'https://login.microsoftonline.com/common/oauth2/v2.0/token';+export const microsoftAuthHandlers = (handle: string): MswHandler[] => [- http.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', () =>+ http.post(MICROSOFT_TOKEN_URL, () =>HttpResponse.json({token_type: 'Bearer',access_token: 'mock-access-token',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.tsindex 143834bd6b0..e678b0cb0c1 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@@ -2,7 +2,10 @@ 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';+import {+ MICROSOFT_TOKEN_URL,+ microsoftAuthHandlers,+} from 'test/integration/microsoft/mocks/microsoft-auth-handlers.util';import { microsoftCalendarEventsHandlers } from 'test/integration/microsoft/mocks/microsoft-calendar-events-handlers.util';import { microsoftMailboxHandlers } from 'test/integration/microsoft/mocks/microsoft-mailbox-handlers.util';import {@@ -34,6 +37,7 @@ export type MicrosoftMock = {failSubscriptionRenewal: () => void;failMessageDelta: (failure: MicrosoftGraphFailure) => void;failCalendarDelta: (failure: MicrosoftGraphFailure) => void;+ declineTokenRefresh: () => void;};export type MicrosoftGraphFailure = {@@ -186,5 +190,18 @@ export const setupMicrosoftMock = ({microsoftGraphErrorResponse(failure),),),+ declineTokenRefresh: () =>+ httpMock.use(+ http.post(MICROSOFT_TOKEN_URL, () =>+ HttpResponse.json(+ {+ error: 'invalid_grant',+ error_description:+ 'AADSTS50173: The provided grant has expired due to it being revoked',+ },+ { status: 400 },+ ),+ ),+ ),};};