The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Resend requests rejected because a sign-in superseded their session (#28784)
Charles Bochetb682ae535e4b
diff --git a/packages/twenty-front/src/modules/apollo/services/ApolloFactory.ts b/packages/twenty-front/src/modules/apollo/services/ApolloFactory.tsindex 6ef0ffbdb1b..2486066ad45 100644--- a/packages/twenty-front/src/modules/apollo/services/ApolloFactory.ts+++ b/packages/twenty-front/src/modules/apollo/services/ApolloFactory.ts@@ -17,6 +17,7 @@ import { logDebug } from '~/utils/logDebug';import { REST_API_BASE_URL } from '@/apollo/constants/RestApiBaseUrl';import { type ApolloManager } from '@/apollo/types/ApolloManager';+import { isSessionSupersededGraphQLError } from '@/apollo/utils/isSessionSupersededGraphQLError';import { isUnauthenticatedGraphQLError } from '@/apollo/utils/isUnauthenticatedGraphQLError';import { loggerLink } from '@/apollo/utils/loggerLink';import { StreamingRestLink } from '@/apollo/utils/streamingRestLink';@@ -194,7 +195,23 @@ export class ApolloFactory implements ApolloManager {});};+ const supersededSessionRetryLink = new ErrorLink(+ ({ error, operation, forward }) => {+ if (+ this.isSupersededSessionRejection(error) &&+ !operation.getContext().skipRetry &&+ isDefined(getSessionGeneration())+ ) {+ return forward(operation);+ }+ },+ );+const errorLink = new ErrorLink(({ error, operation }) => {+ if (this.isSupersededSessionRejection(error)) {+ return;+ }+const requestSessionGeneration =operation.getContext().sessionGeneration;// Missing context must keep sign-out behavior if the link chain changes.@@ -275,6 +292,7 @@ export class ApolloFactory implements ApolloManager {// Cast because third-party links (apollo-link-rest, apollo-upload-client) reference their own ApolloLink type.const links = [+ supersededSessionRetryLink,errorLink,authLink,...(extraLinks || []),@@ -316,6 +334,13 @@ export class ApolloFactory implements ApolloManager {return ServerError.is(error) && error.statusCode === 401;}+ private isSupersededSessionRejection(error: ErrorLike): boolean {+ return (+ CombinedGraphQLErrors.is(error) &&+ error.errors.some(isSessionSupersededGraphQLError)+ );+ }+private isPayloadTooLargeError(error: ErrorLike): boolean {return ServerError.is(error) && error.statusCode === 413;}diff --git a/packages/twenty-front/src/modules/apollo/services/__tests__/ApolloFactory.test.ts b/packages/twenty-front/src/modules/apollo/services/__tests__/ApolloFactory.test.tsindex 5d5f511a9a2..697a401a63c 100644--- a/packages/twenty-front/src/modules/apollo/services/__tests__/ApolloFactory.test.ts+++ b/packages/twenty-front/src/modules/apollo/services/__tests__/ApolloFactory.test.ts@@ -24,6 +24,13 @@ const UNAUTHENTICATED_RESPONSE = JSON.stringify({errors: [{ extensions: { code: 'UNAUTHENTICATED' } }],});+const SESSION_SUPERSEDED_RESPONSE = JSON.stringify({+ data: {},+ errors: [+ { extensions: { code: 'UNAUTHENTICATED', subCode: 'SESSION_SUPERSEDED' } },+ ],+});+const PERMISSION_DENIED_RESPONSE = JSON.stringify({data: { trackAnalytics: null },errors: [@@ -315,39 +322,88 @@ describe('ApolloFactory', () => {expect(fetchMock).toHaveBeenCalledTimes(1);});- it('should ignore an unauthenticated response from an older session', async () => {- let markRequestStarted!: () => void;- const requestStarted = new Promise<void>((resolve) => {- markRequestStarted = resolve;- });- let releaseResponse!: (response: { body: string }) => void;- const pendingResponse = new Promise<{ body: string }>((resolve) => {- releaseResponse = resolve;- });+ const makeSupersededRequest = ({+ retriedResponse,+ context,+ }: {+ retriedResponse: string;+ context?: Record<string, unknown>;+ }) => {+ fetchMock.mockResponseOnce(SESSION_SUPERSEDED_RESPONSE);+ fetchMock.mockResponseOnce(retriedResponse);- fetchMock.mockResponse(() => {- markRequestStarted();+ return makeRequestWithContext(context);+ };++ it('should resend a request rejected because a sign-in superseded its session', async () => {+ rotateSessionGeneration();- return pendingResponse;+ await makeSupersededRequest({+ retriedResponse: JSON.stringify({+ data: { trackAnalytics: { success: true } },+ }),});+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();+ });++ it('should sign out when the resent request is rejected as unauthenticated', async () => {+ rotateSessionGeneration();++ await expect(+ makeSupersededRequest({ retriedResponse: UNAUTHENTICATED_RESPONSE }),+ ).rejects.toBeInstanceOf(CombinedGraphQLErrors);++ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(mockOnUnauthenticatedError).toHaveBeenCalledTimes(1);+ });++ it('should not sign out when the resent request is superseded again', async () => {rotateSessionGeneration();- const requestSessionGeneration = getSessionGeneration();- const request = makeRequest();- expect(requestSessionGeneration).not.toBeNull();+ await expect(+ makeSupersededRequest({ retriedResponse: SESSION_SUPERSEDED_RESPONSE }),+ ).rejects.toBeInstanceOf(CombinedGraphQLErrors);- await requestStarted;+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();+ });++ it('should neither resend nor sign out on a superseded request that must not be retried', async () => {rotateSessionGeneration();- expect(getSessionGeneration()).not.toBe(requestSessionGeneration);+ await expect(+ makeSupersededRequest({+ retriedResponse: UNAUTHENTICATED_RESPONSE,+ context: { skipRetry: true },+ }),+ ).rejects.toBeInstanceOf(CombinedGraphQLErrors);++ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();+ });- releaseResponse({ body: UNAUTHENTICATED_RESPONSE });+ it('should not resend a superseded request after sign out', async () => {+ clearSessionGeneration();- await expect(request).rejects.toBeInstanceOf(CombinedGraphQLErrors);+ await expect(+ makeSupersededRequest({ retriedResponse: UNAUTHENTICATED_RESPONSE }),+ ).rejects.toBeInstanceOf(CombinedGraphQLErrors);++ expect(fetchMock).toHaveBeenCalledTimes(1);expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();});+ it('should not resend a request rejected for another reason', async () => {+ rotateSessionGeneration();+ fetchMock.mockResponseOnce(UNAUTHENTICATED_RESPONSE);++ await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);++ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+it('should leave a permission denial alone', async () => {fetchMock.mockResponse(PERMISSION_DENIED_RESPONSE);diff --git a/packages/twenty-front/src/modules/apollo/utils/isSessionSupersededGraphQLError.ts b/packages/twenty-front/src/modules/apollo/utils/isSessionSupersededGraphQLError.tsnew file mode 100644index 00000000000..26035d226f0--- /dev/null+++ b/packages/twenty-front/src/modules/apollo/utils/isSessionSupersededGraphQLError.ts@@ -0,0 +1,5 @@+import { type GraphQLFormattedError } from 'graphql';++export const isSessionSupersededGraphQLError = (+ graphQLError: Pick<GraphQLFormattedError, 'extensions'>,+): boolean => graphQLError.extensions?.subCode === 'SESSION_SUPERSEDED';diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.exception.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.exception.tsindex bcb27c6f65f..a9f61432e43 100644--- a/packages/twenty-server/src/engine/core-modules/auth/auth.exception.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.exception.ts@@ -20,6 +20,7 @@ export const AuthExceptionCode = appendCommonExceptionCode({FORBIDDEN_EXCEPTION: 'FORBIDDEN_EXCEPTION',INSUFFICIENT_SCOPES: 'INSUFFICIENT_SCOPES',UNAUTHENTICATED: 'UNAUTHENTICATED',+ SESSION_SUPERSEDED: 'SESSION_SUPERSEDED',APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED:'APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED',INVALID_DATA: 'INVALID_DATA',@@ -62,6 +63,7 @@ const getAuthExceptionUserFriendlyMessage = (case AuthExceptionCode.INSUFFICIENT_SCOPES:return msg`Insufficient permissions.`;case AuthExceptionCode.UNAUTHENTICATED:+ case AuthExceptionCode.SESSION_SUPERSEDED:case AuthExceptionCode.APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED:return msg`You must be authenticated to perform this action.`;case AuthExceptionCode.OAUTH_ACCESS_DENIED:@@ -123,6 +125,7 @@ const getAuthExceptionStatusCode = (case AuthExceptionCode.TWO_FACTOR_AUTHENTICATION_VERIFICATION_REQUIRED:case AuthExceptionCode.INVALID_DATA:case AuthExceptionCode.UNAUTHENTICATED:+ case AuthExceptionCode.SESSION_SUPERSEDED:case AuthExceptionCode.APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED:case AuthExceptionCode.USER_NOT_FOUND:case AuthExceptionCode.WORKSPACE_NOT_FOUND:diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/auth-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/auth-graphql-api-exception-handler.util.tsindex ff8e930b7b6..87c6b00a127 100644--- a/packages/twenty-server/src/engine/core-modules/auth/utils/auth-graphql-api-exception-handler.util.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/auth-graphql-api-exception-handler.util.ts@@ -49,6 +49,7 @@ export const authGraphqlApiExceptionHandler = (exception: AuthException) => {userFriendlyMessage: exception.userFriendlyMessage,});case AuthExceptionCode.UNAUTHENTICATED:+ case AuthExceptionCode.SESSION_SUPERSEDED:case AuthExceptionCode.APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED:throw new AuthenticationError(exception.message, {userFriendlyMessage: msg`You must be authenticated to perform this action.`,diff --git a/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.ts b/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.tsindex df5f84e617a..91e62a7db3c 100644--- a/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.ts+++ b/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.ts@@ -124,7 +124,8 @@ export class UserSessionService {} catch (error) {if (!(error instanceof AuthException) ||- error.code !== AuthExceptionCode.UNAUTHENTICATED+ (error.code !== AuthExceptionCode.UNAUTHENTICATED &&+ error.code !== AuthExceptionCode.SESSION_SUPERSEDED)) {throw error;}@@ -356,6 +357,13 @@ export class UserSessionService {const session = await this.userSessionRepository.findOneBy({ tokenHash });+ if (session?.revokedReason === UserSessionRevokedReason.Superseded) {+ throw new AuthException(+ 'Session was replaced by a newer sign-in.',+ AuthExceptionCode.SESSION_SUPERSEDED,+ );+ }+if (!isDefined(session) || !this.isSessionActive(session)) {throw buildInvalidSessionException();}diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-creation.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-creation.integration-spec.tsindex 530fc703550..628182be09a 100644--- a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-creation.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-creation.integration-spec.ts@@ -2,9 +2,12 @@ import { getCoreRepository } from 'test/integration/utils/get-core-repository.utimport {extractSessionCookie,+ hasClearingCookie,normalizeSessionCookieForSnapshot,+ postMetadataOperationWithHeaders,signInWithCookieCapture,} from 'test/integration/graphql/suites/auth/user-sessions/utils/sign-in-with-cookie-capture.util';+import { currentUserIdentityQueryFactory } from 'test/integration/graphql/suites/auth/user-sessions/utils/user-session-operations.util';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';import { UserSessionEntity } from 'src/engine/core-modules/user-session/user-session.entity';@@ -152,4 +155,17 @@ describe('successful user session creation on auth exchanges (integration)', ()expect(newSession).not.toBeNull();expect(newSession?.revokedAt).toBeNull();});++ it('should reject the superseded session as superseded without clearing the cookie', async () => {+ const response = await postMetadataOperationWithHeaders(+ currentUserIdentityQueryFactory(),+ { originHeader: ALLOWED_ORIGIN, cookieHeader: firstSessionCookieHeader },+ );++ expect(response.body.errors?.[0]?.extensions).toMatchObject({+ code: 'UNAUTHENTICATED',+ subCode: 'SESSION_SUPERSEDED',+ });+ expect(hasClearingCookie(response)).toBe(false);+ });});