Skip to content

The open alternative to Salesforce, designed for AI.

fix(front): recover from a session cookie the server does not accept (#24275)

Félix Malfait22267f788050
diff --git a/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts b/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts
index 188c679d7cf..f27c6a1fb36 100644
--- a/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts
+++ b/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts
@@ -46,15 +46,38 @@ const RENEWED_TOKEN_PAIR: AuthTokenPair = {
refreshToken: { token: 'newRefreshToken', expiresAt: '' },
};
+// Mirrors persistence: a replay re-reads the pair renewal just stored, so the
+// mock must move with it or an assertion on the replay header proves nothing.
+let storedTokenPair: AuthTokenPair | undefined = CURRENT_TOKEN_PAIR;
+
const UNAUTHENTICATED_RESPONSE = JSON.stringify({
data: {},
errors: [{ extensions: { code: 'UNAUTHENTICATED' } }],
});
+const FORBIDDEN_RESOURCE_RESPONSE = JSON.stringify({
+ data: { trackAnalytics: null },
+ errors: [
+ { message: 'Forbidden resource', extensions: { code: 'FORBIDDEN' } },
+ ],
+});
+
+const PERMISSION_DENIED_RESPONSE = JSON.stringify({
+ data: { trackAnalytics: null },
+ errors: [
+ {
+ message: 'Entity performing the request does not have permission',
+ extensions: { code: 'FORBIDDEN' },
+ },
+ ],
+});
+
const mockOnError = jest.fn();
const mockOnNetworkError = jest.fn();
const mockOnPayloadTooLarge = jest.fn();
-const mockOnTokenPairChange = jest.fn();
+const mockOnTokenPairChange = jest.fn((tokenPair: AuthTokenPair) => {
+ storedTokenPair = tokenPair;
+});
const mockOnUnauthenticatedError = jest.fn();
const mockWorkspaceMember = {
@@ -123,13 +146,14 @@ const createMockOptions = (): Options => ({
appVersion: '1.0.0',
});
-const makeRequest = async () => {
+const makeRequestWithContext = async (context?: Record<string, unknown>) => {
const options = createMockOptions();
const apolloFactory = new ApolloFactory(options);
const client = apolloFactory.getClient();
await client.mutate({
+ context,
mutation: gql`
mutation TrackAnalytics(
$type: AnalyticsType!
@@ -150,12 +174,18 @@ const makeRequest = async () => {
});
};
+const makeRequest = async () => makeRequestWithContext();
+
describe('ApolloFactory', () => {
beforeEach(() => {
jest.clearAllMocks();
fetchMock.resetMocks();
jest.mocked(renewToken).mockReset().mockResolvedValue(RENEWED_TOKEN_PAIR);
- jest.mocked(getTokenPair).mockReset().mockReturnValue(CURRENT_TOKEN_PAIR);
+ storedTokenPair = CURRENT_TOKEN_PAIR;
+ jest
+ .mocked(getTokenPair)
+ .mockReset()
+ .mockImplementation(() => storedTokenPair);
jotaiStore.set(isCookieAuthActiveState.atom, false);
});
@@ -418,7 +448,7 @@ describe('ApolloFactory', () => {
>;
expect(readHeader(retryHeaders, 'authorization')).toBe(
- `Bearer ${CURRENT_TOKEN_PAIR.accessOrWorkspaceAgnosticToken.token}`,
+ `Bearer ${RENEWED_TOKEN_PAIR.accessOrWorkspaceAgnosticToken.token}`,
);
});
@@ -433,5 +463,92 @@ describe('ApolloFactory', () => {
expect(jotaiStore.get(isCookieAuthActiveState.atom)).toBe(false);
expect(renewToken).toHaveBeenCalled();
});
+
+ // A server that never read the session cookie -- an old pod mid-rollout, or
+ // a cookie the browser no longer holds -- leaves the request with no
+ // credential at all, which the guards refuse as FORBIDDEN.
+ it('should renew the retained token pair and replay when a credential-less request is refused', async () => {
+ setCookieAuthActive();
+ fetchMock
+ .mockResponseOnce(FORBIDDEN_RESOURCE_RESPONSE)
+ .mockResponseOnce(JSON.stringify({ data: { trackAnalytics: null } }));
+
+ await makeRequest();
+
+ expect(jotaiStore.get(isCookieAuthActiveState.atom)).toBe(false);
+ expect(renewToken).toHaveBeenCalledTimes(1);
+ expect(mockOnTokenPairChange).toHaveBeenCalledWith(RENEWED_TOKEN_PAIR);
+ expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();
+
+ const retryHeaders = fetchMock.mock.calls[1]?.[1]?.headers as Record<
+ string,
+ string
+ >;
+
+ expect(readHeader(retryHeaders, 'authorization')).toBe(
+ `Bearer ${RENEWED_TOKEN_PAIR.accessOrWorkspaceAgnosticToken.token}`,
+ );
+ });
+
+ it('should attempt the credential-less fallback only once per operation', async () => {
+ setCookieAuthActive();
+ fetchMock.mockResponse(FORBIDDEN_RESOURCE_RESPONSE);
+
+ await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(renewToken).toHaveBeenCalledTimes(1);
+ expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();
+ });
+
+ it('should sign out when the refresh token is rejected during the fallback', async () => {
+ setCookieAuthActive();
+ jest.mocked(renewToken).mockRejectedValue(
+ new CombinedGraphQLErrors(
+ {
+ data: null,
+ errors: [{ message: 'x', extensions: { code: 'UNAUTHENTICATED' } }],
+ },
+ [{ message: 'x', extensions: { code: 'UNAUTHENTICATED' } }],
+ ),
+ );
+ fetchMock.mockResponse(FORBIDDEN_RESOURCE_RESPONSE);
+
+ await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);
+
+ expect(mockOnUnauthenticatedError).toHaveBeenCalled();
+ });
+
+ it('should leave a permission denial alone', async () => {
+ setCookieAuthActive();
+ fetchMock.mockResponse(PERMISSION_DENIED_RESPONSE);
+
+ await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(jotaiStore.get(isCookieAuthActiveState.atom)).toBe(true);
+ expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();
+ });
+
+ it('should not fall back on a credential-less refusal while authenticating by token', async () => {
+ fetchMock.mockResponse(FORBIDDEN_RESOURCE_RESPONSE);
+
+ await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();
+ });
+
+ it('should not fall back on a credential-less refusal for the cookie session probe', async () => {
+ setCookieAuthActive();
+ fetchMock.mockResponse(FORBIDDEN_RESOURCE_RESPONSE);
+
+ await expect(
+ makeRequestWithContext({ skipAuthToken: true }),
+ ).rejects.toBeInstanceOf(CombinedGraphQLErrors);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(jotaiStore.get(isCookieAuthActiveState.atom)).toBe(true);
+ });
});
});
diff --git a/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts b/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts
index 0a47a6eea25..5f3fe8c6f00 100644
--- a/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts
+++ b/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts
@@ -23,6 +23,7 @@ import { type ApolloManager } from '@/apollo/types/apolloManager.interface';
import { getIsCookieAuthActive } from '@/apollo/utils/getIsCookieAuthActive';
import { getTokenPair } from '@/apollo/utils/getTokenPair';
import { setIsCookieAuthActive } from '@/apollo/utils/setIsCookieAuthActive';
+import { isMissingCredentialGraphQLError } from '@/apollo/utils/isMissingCredentialGraphQLError';
import { isUnauthenticatedGraphQLError } from '@/apollo/utils/isUnauthenticatedGraphQLError';
import { loggerLink } from '@/apollo/utils/loggerLink';
import { StreamingRestLink } from '@/apollo/utils/streamingRestLink';
@@ -209,6 +210,14 @@ export class ApolloFactory implements ApolloManager {
}
};
+ const canFallBackFromCookieAuth = (
+ operation: ApolloLink.Operation,
+ ): boolean =>
+ getIsCookieAuthActive() &&
+ operation.getContext().skipAuthToken !== true &&
+ operation.getContext().hasAttemptedCookieAuthFallback !== true &&
+ isDefined(getTokenPair()?.refreshToken?.token);
+
const handleTokenRenewal = (
operation: ApolloLink.Operation,
forward: ApolloLink.ForwardFunction,
@@ -226,11 +235,7 @@ export class ApolloFactory implements ApolloManager {
// rollback. Fall back to the retained token pair instead of signing the
// user out. Attempted once per operation so a genuinely expired token
// still reaches the renewal path below.
- if (
- getIsCookieAuthActive() &&
- operation.getContext().hasAttemptedCookieAuthFallback !== true &&
- isDefined(getTokenPair()?.refreshToken?.token)
- ) {
+ if (canFallBackFromCookieAuth(operation)) {
setIsCookieAuthActive(false);
operation.setContext({ hasAttemptedCookieAuthFallback: true });
// Deactivation is sticky for the rest of the mount by design. Both
@@ -352,6 +357,21 @@ export class ApolloFactory implements ApolloManager {
return handleTokenRenewal(operation, forward, error);
}
+ // Goes through handleTokenRenewal rather than replaying directly:
+ // ErrorLink subscribes a replay straight to the original observer,
+ // so an UNAUTHENTICATED on it never re-enters this handler.
+ if (
+ isMissingCredentialGraphQLError(graphQLError) &&
+ canFallBackFromCookieAuth(operation)
+ ) {
+ // oxlint-disable-next-line no-console
+ console.log(
+ 'Session cookie was not accepted, falling back to the token pair',
+ );
+
+ return handleTokenRenewal(operation, forward, error);
+ }
+
switch (graphQLError?.extensions?.code) {
case 'APP_VERSION_MISMATCH': {
onAppVersionMismatch?.(
diff --git a/packages/twenty-front/src/modules/apollo/utils/isMissingCredentialGraphQLError.ts b/packages/twenty-front/src/modules/apollo/utils/isMissingCredentialGraphQLError.ts
new file mode 100644
index 00000000000..7933e6a4ba5
--- /dev/null
+++ b/packages/twenty-front/src/modules/apollo/utils/isMissingCredentialGraphQLError.ts
@@ -0,0 +1,10 @@
+import { type GraphQLFormattedError } from 'graphql';
+
+// Matched on the message, not the code alone: a permission denial is also
+// FORBIDDEN but carries the message its exception set, whereas "Forbidden
+// resource" is Nest's default for a guard rejecting an unhydrated request.
+export const isMissingCredentialGraphQLError = (
+ graphQLError: GraphQLFormattedError,
+): boolean =>
+ graphQLError.extensions?.code === 'FORBIDDEN' &&
+ graphQLError.message === 'Forbidden resource';