Skip to content

The open alternative to Salesforce, designed for AI.

Fix record exports with CLI OAuth sessions (#27992)

Weikodcaeb3d8087a
diff --git a/packages/twenty-cli/src/transport/__tests__/subscription-errors.spec.ts b/packages/twenty-cli/src/transport/__tests__/subscription-errors.spec.ts
new file mode 100644
index 00000000000..8d7546e71f0
--- /dev/null
+++ b/packages/twenty-cli/src/transport/__tests__/subscription-errors.spec.ts
@@ -0,0 +1,171 @@
+import { afterEach, expect, it, vi } from 'vitest';
+
+import { startTestServer } from '@/__tests__/utils/start-test-server';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { subscribeGraphql } from '@/transport/graphql/subscribe-graphql';
+
+vi.mock('@/transport/constants/request-timeout-milliseconds.constant', () => ({
+ REQUEST_TIMEOUT_MILLISECONDS: 500,
+}));
+
+afterEach(() => vi.unstubAllEnvs());
+
+it.each([
+ {
+ status: 401,
+ contentType: 'text/event-stream',
+ body: '',
+ code: 'AUTH_REQUIRED',
+ message: undefined,
+ },
+ {
+ status: 200,
+ contentType: 'text/event-stream',
+ body: 'event: next\ndata: {"errors":[{"message":"Subscription denied."}]}\n\n',
+ code: 'GRAPHQL_ERROR',
+ message: 'Subscription denied.',
+ },
+ {
+ status: 401,
+ contentType: 'text/event-stream',
+ body: 'event: next\ndata: {invalid\n\n',
+ code: 'AUTH_REQUIRED',
+ message: undefined,
+ },
+ {
+ status: 403,
+ contentType: 'text/event-stream',
+ body: 'event: next\ndata: null\n\n',
+ code: 'PERMISSION_DENIED',
+ message: 'Access denied.',
+ },
+ {
+ status: 403,
+ contentType: 'text/event-stream',
+ body: 'event: unsupported\ndata: {}\n\n',
+ code: 'PERMISSION_DENIED',
+ message: 'Access denied.',
+ },
+ {
+ status: 500,
+ contentType: 'text/event-stream',
+ body: ':\n\nevent: next\ndata: {"errors":[{"message":"Sign in to export records."}]}\n\nevent: complete\n\n',
+ code: 'GRAPHQL_ERROR',
+ message: 'Sign in to export records.',
+ },
+ {
+ status: 403,
+ contentType: 'text/event-stream; charset=utf-8',
+ body: 'event: next\ndata: {"errors":[{"message":"Export permission required."}]}\n\n',
+ code: 'PERMISSION_DENIED',
+ message: 'Export permission required.',
+ },
+ {
+ status: 500,
+ contentType: 'text/event-stream',
+ body: 'event: complete\n\n',
+ code: 'HTTP_ERROR',
+ message: 'The server answered 500.',
+ },
+ {
+ status: 500,
+ contentType: 'text/event-stream',
+ body: 'event: next\ndata: {"data":{"logs":"unexpected success"}}\n\n',
+ code: 'HTTP_ERROR',
+ message: 'The server answered 500.',
+ },
+ {
+ status: 503,
+ contentType: 'application/json',
+ body: '{"message":"Service unavailable"}',
+ code: 'HTTP_ERROR',
+ message: 'The server answered 503: Service unavailable',
+ },
+])(
+ 'reports $status $contentType: $message',
+ async ({ status, contentType, body, code, message }) => {
+ for (const name of [
+ 'HTTP_PROXY',
+ 'HTTPS_PROXY',
+ 'http_proxy',
+ 'https_proxy',
+ ]) {
+ vi.stubEnv(name, undefined);
+ }
+ const server = await startTestServer((_request, response) => {
+ response.writeHead(status, { 'content-type': contentType });
+ response.end(body);
+ });
+ const onData = vi.fn(async () => {});
+ const onConnected = vi.fn(async () => {});
+ try {
+ await expect(
+ subscribeGraphql({
+ target: {
+ apiUrl: server.url,
+ bearerToken: 'test',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ },
+ signal: new AbortController().signal,
+ query: 'subscription { logs }',
+ variables: {},
+ onConnected,
+ onData,
+ }),
+ ).rejects.toMatchObject({
+ code,
+ message: message ?? `${server.url} rejected the credentials.`,
+ details: { status },
+ ...([401, 403].includes(status)
+ ? { exitCode: EXIT_CODE.AUTHENTICATION }
+ : {}),
+ });
+ expect(onData).not.toHaveBeenCalled();
+ expect(onConnected).toHaveBeenCalledTimes(status === 200 ? 1 : 0);
+ expect(server.requests).toHaveLength(1);
+ } finally {
+ await server.close();
+ }
+ },
+);
+
+it('times out an unsuccessful response that only sends heartbeat comments', async () => {
+ for (const name of [
+ 'HTTP_PROXY',
+ 'HTTPS_PROXY',
+ 'http_proxy',
+ 'https_proxy',
+ ]) {
+ vi.stubEnv(name, undefined);
+ }
+ const server = await startTestServer((_request, response) => {
+ response.writeHead(500, { 'content-type': 'text/event-stream' });
+ response.write(':\n\n');
+ const heartbeat = setInterval(() => response.write(':\n\n'), 100);
+ response.on('close', () => clearInterval(heartbeat));
+ });
+ const onData = vi.fn(async () => {});
+ const onConnected = vi.fn(async () => {});
+ try {
+ await expect(
+ subscribeGraphql({
+ target: {
+ apiUrl: server.url,
+ bearerToken: 'test',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ },
+ signal: new AbortController().signal,
+ query: 'subscription { logs }',
+ variables: {},
+ onConnected,
+ onData,
+ }),
+ ).rejects.toMatchObject({ code: 'TIMEOUT' });
+ expect(onConnected).not.toHaveBeenCalled();
+ expect(onData).not.toHaveBeenCalled();
+ } finally {
+ await server.close();
+ }
+});
diff --git a/packages/twenty-cli/src/transport/graphql/read-graphql-stream-error.ts b/packages/twenty-cli/src/transport/graphql/read-graphql-stream-error.ts
new file mode 100644
index 00000000000..b31a73130eb
--- /dev/null
+++ b/packages/twenty-cli/src/transport/graphql/read-graphql-stream-error.ts
@@ -0,0 +1,51 @@
+import { isNonEmptyArray } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createHttpStatusError } from '@/transport/create-http-status-error';
+import { createGraphqlError } from '@/transport/graphql/create-graphql-error';
+import { readEventStream } from '@/transport/graphql/read-event-stream';
+
+export const readGraphqlStreamError = async ({
+ response,
+ target,
+ signal,
+}: {
+ response: Response;
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ if (isDefined(response.body)) {
+ for await (const message of readEventStream({
+ body: response.body,
+ signal,
+ })) {
+ if (message.event !== 'next') {
+ break;
+ }
+ let payload: unknown;
+ try {
+ payload = JSON.parse(message.data);
+ } catch {
+ break;
+ }
+ if (isPlainObject(payload) && isNonEmptyArray(payload.errors)) {
+ return createGraphqlError({
+ errors: payload.errors,
+ data: payload.data,
+ status: response.status,
+ headers: response.headers,
+ target,
+ });
+ }
+ break;
+ }
+ }
+
+ return createHttpStatusError({
+ status: response.status,
+ headers: response.headers,
+ body: undefined,
+ target,
+ });
+};
diff --git a/packages/twenty-cli/src/transport/graphql/subscribe-graphql.ts b/packages/twenty-cli/src/transport/graphql/subscribe-graphql.ts
index 5eb6df2e5a0..3cf14d4e2a9 100644
--- a/packages/twenty-cli/src/transport/graphql/subscribe-graphql.ts
+++ b/packages/twenty-cli/src/transport/graphql/subscribe-graphql.ts
@@ -14,6 +14,7 @@ import { GRAPHQL_ENDPOINT_PATHS } from '@/transport/graphql/constants/graphql-en
import { createGraphqlError } from '@/transport/graphql/create-graphql-error';
import { parseGraphqlResponse } from '@/transport/graphql/parse-graphql-response';
import { readEventStream } from '@/transport/graphql/read-event-stream';
+import { readGraphqlStreamError } from '@/transport/graphql/read-graphql-stream-error';
import { readBoundedBody } from '@/transport/read-bounded-body';
import { resolveRequestUrl } from '@/transport/resolve-request-url';
@@ -71,7 +72,6 @@ export const subscribeGraphql = async ({
throw createRedirectError(response, url);
}
if (
- !response.ok ||
response.headers
.get('content-type')
?.split(';')[0]
@@ -91,6 +91,13 @@ export const subscribeGraphql = async ({
});
throw invalidStream('The server did not return a GraphQL event stream.');
}
+ if (!response.ok) {
+ throw await readGraphqlStreamError({
+ response,
+ target,
+ signal: requestSignal,
+ });
+ }
if (!isDefined(response.body)) {
throw invalidStream('The server returned an empty log stream.');
}
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/services/record-export.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/record-export/services/record-export.workspace-service.ts
index 2c08ec1494a..4e11ab57074 100644
--- a/packages/twenty-server/src/engine/core-modules/record-export/services/record-export.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-export/services/record-export.workspace-service.ts
@@ -54,10 +54,13 @@ import { isApiKeyRecordExportRequester } from 'src/engine/core-modules/record-ex
import { RecordExportException } from 'src/engine/core-modules/record-export/record-export.exception';
import { type RecordExportAuthContext } from 'src/engine/core-modules/record-export/types/record-export-auth-context.type';
import { type RecordExportColumn } from 'src/engine/core-modules/record-export/types/record-export-column.type';
+import { type RecordExportDownloadRequest } from 'src/engine/core-modules/record-export/types/record-export-download-request.type';
+import { type RecordExportSession } from 'src/engine/core-modules/record-export/types/record-export-session.type';
import { type RecordExportDownloadTokenJwtPayload } from 'src/engine/core-modules/record-export/types/record-export-download-token-jwt-payload.type';
import { type RecordExportParameters } from 'src/engine/core-modules/record-export/types/record-export-parameters.type';
import { type RecordExport } from 'src/engine/core-modules/record-export/types/record-export.type';
import { buildRecordExportColumns } from 'src/engine/core-modules/record-export/utils/build-record-export-columns.util';
+import { computeRecordExportPermissionsHash } from 'src/engine/core-modules/record-export/utils/compute-record-export-permissions-hash.util';
import { getRecordExportLocale } from 'src/engine/core-modules/record-export/utils/get-record-export-locale.util';
import { UserSessionCookieService } from 'src/engine/core-modules/user-session/services/user-session-cookie.service';
import { hashUserSessionToken } from 'src/engine/core-modules/user-session/utils/hash-user-session-token.util';
@@ -74,7 +77,6 @@ import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { type WorkspaceCacheOrDerivedCacheKeyName } from 'src/engine/workspace-cache/types/workspace-cache-key.type';
-import { combineCacheHashes } from 'src/engine/workspace-cache/utils/combine-cache-hashes.util';
export type RecordExportQueryContext = {
queryRunnerContext: CommonBaseQueryRunnerContext;
@@ -200,9 +202,12 @@ export class RecordExportWorkspaceService {
requestTokenHash: string;
}): Promise<RecordExport> {
const requester = await this.assertCanExport(authContext);
- const permissionsHash = await this.capturePermissionsHash(
- requester.workspace.id,
- );
+ const permissionsHash = await this.capturePermissionsHash({
+ workspaceId: requester.workspace.id,
+ applicationId: isUserAuthContext(requester)
+ ? requester.application?.id
+ : undefined,
+ });
const context = await this.buildContext({
parameters,
authContext: requester,
@@ -216,6 +221,7 @@ export class RecordExportWorkspaceService {
: {
userWorkspaceId: requester.userWorkspaceId,
workspaceMemberId: requester.workspaceMemberId,
+ applicationId: requester.application?.id,
}),
requestTokenHash,
permissionsHash,
@@ -331,11 +337,8 @@ export class RecordExportWorkspaceService {
}
async getDownloadPath(
- recordExport: RecordExportRequester &
- Pick<
- RecordExport,
- 'id' | 'requestTokenHash' | 'permissionsHash' | 'filename'
- >,
+ recordExport: RecordExportSession &
+ Pick<RecordExport, 'id' | 'permissionsHash' | 'filename'>,
): Promise<string> {
await this.resolveRequester(recordExport);
await this.assertPermissionsUnchanged(recordExport);
@@ -351,6 +354,7 @@ export class RecordExportWorkspaceService {
: {
userWorkspaceId: recordExport.userWorkspaceId,
workspaceMemberId: recordExport.workspaceMemberId,
+ applicationId: recordExport.applicationId,
}),
requestTokenHash: recordExport.requestTokenHash,
permissionsHash: recordExport.permissionsHash,
@@ -378,7 +382,17 @@ export class RecordExportWorkspaceService {
}> {
const payload = await this.verifyDownloadToken(id, token);
const recordExport = { ...payload, id };
- this.assertDownloader({ request, recordExport });
+ this.assertDownloader({
+ request: {
+ workspaceId: request.workspace?.id,
+ apiKeyId: request.apiKey?.id,
+ userWorkspaceId: request.userWorkspaceId,
+ workspaceMemberId: request.workspaceMemberId,
+ applicationId: request.application?.id,
+ requestTokenHash: this.getRequestTokenHashOrThrow(request),
+ },
+ recordExport,
+ });
await this.findOrThrow(recordExport);
const cleanup = () =>
this.cancel(recordExport).catch(() => {
@@ -485,9 +499,7 @@ export class RecordExportWorkspaceService {
): Promise<RecordExportAuthContext> {
if (
!isApiKeyAuthContext(authContext) &&
- (!isUserAuthContext(authContext) ||
- isDefined(authContext.application) ||
- isDefined(authContext.viaApplication))
+ (!isUserAuthContext(authContext) || isDefined(authContext.viaApplication))
) {
throw new ForbiddenException(t`Sign in to export records.`);
}
@@ -507,7 +519,9 @@ export class RecordExportWorkspaceService {
...(isApiKeyAuthContext(authContext)
? { apiKeyId: authContext.apiKey.id }
: { userWorkspaceId: authContext.userWorkspaceId }),
- applicationId: undefined,
+ applicationId: isUserAuthContext(authContext)
+ ? authContext.application?.id
+ : undefined,
setting: PermissionFlagType.EXPORT_CSV,
}))
) {
@@ -571,6 +585,24 @@ export class RecordExportWorkspaceService {
);
}
+ const { flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(
+ recordExport.workspaceId,
+ ['flatApplicationMaps'],
+ );
+ const application = isDefined(recordExport.applicationId)
+ ? flatApplicationMaps.byId[recordExport.applicationId]
+ : undefined;
+
+ if (
+ isDefined(recordExport.applicationId) &&
+ (!isDefined(application) || isDefined(application.deletedAt))
+ ) {
+ throw new ForbiddenException(
+ t`You do not have permission to export records.`,
+ );
+ }
+
return this.assertCanExport(
buildUserAuthContext({
workspace: fromWorkspaceEntityToFlat(userWorkspace.workspace),
@@ -578,6 +610,7 @@ export class RecordExportWorkspaceService {
userWorkspaceId: userWorkspace.id,
workspaceMember,
workspaceMemberId: workspaceMember.id,
+ application,
}),
);
}
@@ -729,18 +762,18 @@ export class RecordExportWorkspaceService {
request,
recordExport,
}: {
- request: Request;
- recordExport: RecordExportRequester &
- Pick<RecordExport, 'requestTokenHash'>;
+ request: RecordExportDownloadRequest;
+ recordExport: RecordExportSession;
}): void {
if (
- request.workspace?.id !== recordExport.workspaceId ||
+ request.workspaceId !== recordExport.workspaceId ||
(isApiKeyRecordExportRequester(recordExport)
- ? request.apiKey?.id !== recordExport.apiKeyId
- : isDefined(request.apiKey) ||
+ ? request.apiKeyId !== recordExport.apiKeyId
+ : isDefined(request.apiKeyId) ||
request.userWorkspaceId !== recordExport.userWorkspaceId ||
- request.workspaceMemberId !== recordExport.workspaceMemberId) ||
- this.getRequestTokenHashOrThrow(request) !== recordExport.requestTokenHash
+ request.workspaceMemberId !== recordExport.workspaceMemberId ||
+ request.applicationId !== recordExport.applicationId) ||
+ request.requestTokenHash !== recordExport.requestTokenHash
) {
throw new ForbiddenException(
t`This export belongs to another session. Please create a new export.`,
@@ -748,25 +781,41 @@ export class RecordExportWorkspaceService {
}
}
- async capturePermissionsHash(workspaceId: string): Promise<string> {
- const { hashes } =
- await this.workspaceCacheService.getOrRecomputeWithHashes(
+ async capturePermissionsHash({
+ workspaceId,
+ applicationId,
+ }: Pick<
+ RecordExportRequester,
+ 'workspaceId' | 'applicationId'
+ >): Promise<string> {
+ const permissionsHash =
+ await this.workspaceCacheService.getOrRecomputeCombinedHash(
workspaceId,
RECORD_EXPORT_PERMISSION_CACHE_KEYS,
);
- return combineCacheHashes(hashes, RECORD_EXPORT_PERMISSION_CACHE_KEYS);
+ if (!isDefined(applicationId)) {
+ return permissionsHash;
+ }
+
+ const { flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatApplicationMaps',
+ ]);
+ const application = flatApplicationMaps.byId[applicationId];
+
+ return computeRecordExportPermissionsHash({ permissionsHash, application });
}
async assertPermissionsUnchanged(
- recordExport: Pick<RecordExport, 'workspaceId' | 'permissionsHash'>,
+ recordExport: Pick<
+ RecordExport,
+ 'workspaceId' | 'applicationId' | 'permissionsHash'
+ >,
): Promise<void> {
if (
recordExport.permissionsHash !==
- (await this.workspaceCacheService.getOrRecomputeCombinedHash(
- recordExport.workspaceId,
- RECORD_EXPORT_PERMISSION_CACHE_KEYS,
- ))
+ (await this.capturePermissionsHash(recordExport))
) {
throw new ForbiddenException(
t`Access permissions have changed. Please create a new export.`,
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-download-request.type.ts b/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-download-request.type.ts
new file mode 100644
index 00000000000..8c1faddb9e8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-download-request.type.ts
@@ -0,0 +1,8 @@
+export type RecordExportDownloadRequest = {
+ workspaceId?: string;
+ apiKeyId?: string;
+ userWorkspaceId?: string;
+ workspaceMemberId?: string;
+ applicationId?: string;
+ requestTokenHash: string;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-download-token-jwt-payload.type.ts b/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-download-token-jwt-payload.type.ts
index c9d4e100401..10ec9b1a8d6 100644
--- a/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-download-token-jwt-payload.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-download-token-jwt-payload.type.ts
@@ -1,9 +1,9 @@
-import { type RecordExportRequester } from 'src/engine/core-modules/record-export/types/record-export-requester.type';
+import { type RecordExportSession } from 'src/engine/core-modules/record-export/types/record-export-session.type';
import { type FileTokenJwtPayload } from 'src/engine/core-modules/auth/types/file-token-jwt-payload.type';
import { type RecordExport } from 'src/engine/core-modules/record-export/types/record-export.type';
export type RecordExportDownloadTokenJwtPayload = FileTokenJwtPayload &
- RecordExportRequester &
- Pick<RecordExport, 'requestTokenHash' | 'permissionsHash' | 'filename'> & {
+ RecordExportSession &
+ Pick<RecordExport, 'permissionsHash' | 'filename'> & {
purpose: 'record-export';
};
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-requester.type.ts b/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-requester.type.ts
index 1da219b96d1..27577fd4422 100644
--- a/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-requester.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-requester.type.ts
@@ -5,6 +5,7 @@ import {
} from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
type RecordExportApiKeyRequester = {
+ applicationId?: never;
apiKeyId: ApiKeyWorkspaceAuthContext['apiKey']['id'];
userWorkspaceId?: never;
workspaceMemberId?: never;
@@ -15,6 +16,7 @@ type RecordExportUserRequester = Pick<
'userWorkspaceId' | 'workspaceMemberId'
> & {
apiKeyId?: never;
+ applicationId?: NonNullable<UserWorkspaceAuthContext['application']>['id'];
};
export type RecordExportRequester = {
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-session.type.ts b/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-session.type.ts
new file mode 100644
index 00000000000..1601181a24b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-export/types/record-export-session.type.ts
@@ -0,0 +1,5 @@
+import { type RecordExportRequester } from 'src/engine/core-modules/record-export/types/record-export-requester.type';
+
+export type RecordExportSession = RecordExportRequester & {
+ requestTokenHash: string;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/types/record-export.type.ts b/packages/twenty-server/src/engine/core-modules/record-export/types/record-export.type.ts
index 21115e56893..2faffb29706 100644
--- a/packages/twenty-server/src/engine/core-modules/record-export/types/record-export.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-export/types/record-export.type.ts
@@ -1,9 +1,8 @@
-import { type RecordExportRequester } from 'src/engine/core-modules/record-export/types/record-export-requester.type';
+import { type RecordExportSession } from 'src/engine/core-modules/record-export/types/record-export-session.type';
import { type RecordExportParameters } from 'src/engine/core-modules/record-export/types/record-export-parameters.type';
-export type RecordExport = RecordExportRequester & {
+export type RecordExport = RecordExportSession & {
id: string;
- requestTokenHash: string;
permissionsHash: string;
parameters: RecordExportParameters;
filename: string;
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/utils/__tests__/compute-record-export-permissions-hash.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-export/utils/__tests__/compute-record-export-permissions-hash.util.spec.ts
new file mode 100644
index 00000000000..7e971966def
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-export/utils/__tests__/compute-record-export-permissions-hash.util.spec.ts
@@ -0,0 +1,67 @@
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { computeRecordExportPermissionsHash } from 'src/engine/core-modules/record-export/utils/compute-record-export-permissions-hash.util';
+
+const application: Pick<FlatApplication, 'id' | 'defaultRoleId' | 'deletedAt'> =
+ {
+ id: 'application-id',
+ defaultRoleId: 'role-id',
+ deletedAt: null,
+ };
+const permissionsHash = 'workspace-permissions';
+
+const originalHash = computeRecordExportPermissionsHash({
+ permissionsHash,
+ application,
+});
+
+describe('computeRecordExportPermissionsHash', () => {
+ it('ignores application settings unrelated to permissions', () => {
+ const updatedApplication = { ...application, autoUpgrade: true };
+
+ expect(
+ computeRecordExportPermissionsHash({
+ permissionsHash,
+ application: updatedApplication,
+ }),
+ ).toBe(originalHash);
+ });
+
+ it('changes when workspace permissions change', () => {
+ expect(
+ computeRecordExportPermissionsHash({
+ permissionsHash: 'changed-workspace-permissions',
+ application,
+ }),
+ ).not.toBe(originalHash);
+ });
+
+ it.each([
+ {
+ name: 'identity changes',
+ application: { ...application, id: 'other-id' },
+ },
+ {
+ name: 'default role changes',
+ application: { ...application, defaultRoleId: 'other-role-id' },
+ },
+ {
+ name: 'default role is removed',
+ application: { ...application, defaultRoleId: null },
+ },
+ {
+ name: 'is deleted',
+ application: { ...application, deletedAt: new Date('2026-10-14') },
+ },
+ { name: 'is missing', application: undefined },
+ ])(
+ 'changes when the application $name',
+ ({ application: updatedApplication }) => {
+ expect(
+ computeRecordExportPermissionsHash({
+ permissionsHash,
+ application: updatedApplication,
+ }),
+ ).not.toBe(originalHash);
+ },
+ );
+});
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/utils/compute-record-export-permissions-hash.util.ts b/packages/twenty-server/src/engine/core-modules/record-export/utils/compute-record-export-permissions-hash.util.ts
new file mode 100644
index 00000000000..6b1f4531e06
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-export/utils/compute-record-export-permissions-hash.util.ts
@@ -0,0 +1,29 @@
+import { createHash } from 'crypto';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+
+export const computeRecordExportPermissionsHash = ({
+ permissionsHash,
+ application,
+}: {
+ permissionsHash: string;
+ application:
+ | Pick<FlatApplication, 'id' | 'defaultRoleId' | 'deletedAt'>
+ | undefined;
+}): string =>
+ createHash('sha256')
+ .update(
+ JSON.stringify({
+ permissionsHash,
+ application: isDefined(application)
+ ? {
+ id: application.id,
+ defaultRoleId: application.defaultRoleId,
+ deletedAt: application.deletedAt,
+ }
+ : null,
+ }),
+ )
+ .digest('hex');
diff --git a/packages/twenty-server/test/integration/record-export/record-export.integration-spec.ts b/packages/twenty-server/test/integration/record-export/record-export.integration-spec.ts
index e2006a0dabe..47a3390d5a6 100644
--- a/packages/twenty-server/test/integration/record-export/record-export.integration-spec.ts
+++ b/packages/twenty-server/test/integration/record-export/record-export.integration-spec.ts
@@ -1,3 +1,12 @@
+import { type ApplicationService } from 'src/engine/core-modules/application/application.service';
+import { loginAsTwentyCli } from 'test/integration/metadata/suites/application/utils/login-as-twenty-cli.util';
+import { findOneApplication } from 'test/integration/metadata/suites/application/utils/find-one-application.util';
+import { uninstallApplication } from 'test/integration/metadata/suites/application/utils/uninstall-application.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { TWENTY_CLI_APPLICATION_REGISTRATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-cli-application-registration.constant';
+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
import { type ApiKeyRoleService } from 'src/engine/core-modules/api-key/services/api-key-role.service';
import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
import { type ApiKeyService } from 'src/engine/core-modules/api-key/services/api-key.service';
@@ -70,6 +79,19 @@ const waitUntil = async (condition: () => Promise<boolean>) => {
};
describe('record export lifecycle (integration)', () => {
+ let cliToken: string;
+ let cliApplicationId: string;
+ const applicationCache = () =>
+ getAppProviderByClassName<WorkspaceCacheService>('WorkspaceCacheService');
+ const setApplicationRole = async (applicationRoleId: string | null) => {
+ await globalThis.testDataSource.query(
+ 'UPDATE core.application SET "defaultRoleId" = $1, "deletedAt" = NULL WHERE id = $2',
+ [applicationRoleId, cliApplicationId],
+ );
+ await applicationCache().invalidateAndRecompute(SEED_APPLE_WORKSPACE_ID, [
+ 'flatApplicationMaps',
+ ]);
+ };
let input: CreateRecordExportInput;
let exports: RecordExportWorkspaceService;
let cache: CacheStorageService;
@@ -280,6 +302,15 @@ describe('record export lifecycle (integration)', () => {
});
expect(result.errors).toBeUndefined();
roleId = result.data.createOneRole.id;
+ cliToken = await loginAsTwentyCli();
+ const applicationResult = await findOneApplication({
+ input: {
+ universalIdentifier:
+ TWENTY_CLI_APPLICATION_REGISTRATION.universalIdentifier,
+ },
+ gqlFields: 'id',
+ });
+ cliApplicationId = applicationResult.data.findOneApplication.id;
await updateWorkspaceMemberRole({
input: { roleId, workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY },
});
@@ -305,6 +336,9 @@ describe('record export lifecycle (integration)', () => {
await apiKeys().revoke(id, SEED_APPLE_WORKSPACE_ID);
}
apiKeyIds.clear();
+ if (isDefined(cliApplicationId)) {
+ await setApplicationRole(null);
+ }
if (isDefined(roleId)) {
await upsertRowLevelPermissionPredicates({
input: {
@@ -322,6 +356,13 @@ describe('record export lifecycle (integration)', () => {
});
afterAll(async () => {
+ if (isDefined(cliApplicationId)) {
+ await uninstallApplication({
+ universalIdentifier:
+ TWENTY_CLI_APPLICATION_REGISTRATION.universalIdentifier,
+ expectToFail: false,
+ });
+ }
await updateFeatureFlag({
featureFlag: FeatureFlagKey.IS_ASYNC_CSV_EXPORT_ENABLED,
value: wasAsyncCsvExportEnabled,
@@ -439,6 +480,176 @@ describe('record export lifecycle (integration)', () => {
);
});
+ it('exports and downloads with the real CLI OAuth login', async () => {
+ const ready = await exportToCompletion(
+ {
+ ...input,
+ filter: { id: { eq: companies[0].id } },
+ },
+ cliToken,
+ );
+ const payload = await authorization(ready);
+ expect(payload).toMatchObject({ applicationId: cliApplicationId });
+ const requester = await exports.resolveRequester(payload);
+ expect(requester).toMatchObject({
+ type: 'user',
+ application: { id: cliApplicationId },
+ });
+ for (const applicationId of [undefined, v4()]) {
+ expect(() =>
+ exports.assertDownloader({
+ recordExport: payload,
+ request: {
+ workspaceId: payload.workspaceId,
+ userWorkspaceId: payload.userWorkspaceId,
+ workspaceMemberId: payload.workspaceMemberId,
+ applicationId,
+ requestTokenHash: payload.requestTokenHash,
+ },
+ }),
+ ).toThrow('This export belongs to another session');
+ }
+ await download(ready, APPLE_JANE_ADMIN_ACCESS_TOKEN).expect(403);
+ const response = await download(ready).expect(200);
+ expect(response.text.replace(/^\uFEFF/, '')).toBe(
+ `Id,Name\n${companies[0].id},${companies[0].name}\n`,
+ );
+ });
+
+ it('preserves application row permissions in the export worker', async () => {
+ await setApplicationRole(roleId);
+ await upsertContainsRlsPredicate({
+ roleId,
+ objectNameSingular: 'company',
+ fieldName: 'name',
+ value: companies[0].name,
+ });
+ const ready = await exportToCompletion(input, cliToken);
+ const response = await download(ready).expect(200);
+ expect(response.text.replace(/^\uFEFF/, '')).toBe(
+ `Id,Name\n${companies[0].id},${companies[0].name}\n`,
+ );
+ });
+
+ it('rejects an OAuth export when its application cannot read the object', async () => {
+ await setApplicationRole(roleId);
+ await changeRole({ canReadAllObjectRecords: false });
+ await expect(exportToCompletion(input, cliToken)).rejects.toThrow(
+ 'The export failed. Please try again or export fewer records.',
+ );
+ });
+
+ it.each(['user', 'application'] as const)(
+ 'rejects an OAuth export when the %s lacks export permission',
+ async (principal) => {
+ const { applicationAccessToken } = await generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: cliApplicationId,
+ userId: USER_DATA_SEED_IDS[principal === 'user' ? 'JONY' : 'JANE'],
+ userWorkspaceId:
+ USER_WORKSPACE_DATA_SEED_IDS[principal === 'user' ? 'JONY' : 'JANE'],
+ });
+ if (principal === 'application') {
+ await setApplicationRole(roleId);
+ }
+ await changeRole({ canAccessAllTools: false });
+ const { events } = subscribe(input, applicationAccessToken.token);
+ await expect(nextExport(events)).rejects.toThrow(/permission/i);
+ },
+ );
+
+ it('still rejects an application token without a user', async () => {
+ const { applicationAccessToken } = await generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: cliApplicationId,
+ });
+ const { events } = subscribe(input, applicationAccessToken.token);
+ await expect(nextExport(events)).rejects.toThrow();
+ });
+
+ it.each(['user', 'apiKey', 'oauth'] as const)(
+ 'keeps a completed %s export after an application setting changes',
+ async (principal) => {
+ const token =
+ principal === 'oauth'
+ ? cliToken
+ : principal === 'apiKey'
+ ? (await createApiKey()).token
+ : APPLE_JANE_ADMIN_ACCESS_TOKEN;
+ const ready = await exportToCompletion(input, token);
+ const { flatApplicationMaps } = await applicationCache().getOrRecompute(
+ SEED_APPLE_WORKSPACE_ID,
+ ['flatApplicationMaps'],
+ );
+ const application = flatApplicationMaps.byId[cliApplicationId];
+ if (!isDefined(application)) {
+ throw new Error('CLI application not found');
+ }
+ const applications =
+ getAppProviderByClassName<ApplicationService>('ApplicationService');
+ await applications.update(cliApplicationId, {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ autoUpgrade: !application.autoUpgrade,
+ });
+ await download(ready).expect(200);
+ },
+ );
+
+ it('keeps an OAuth export after another application changes its role', async () => {
+ const { flatApplicationMaps } = await applicationCache().getOrRecompute(
+ SEED_APPLE_WORKSPACE_ID,
+ ['flatApplicationMaps'],
+ );
+ const otherApplication = Object.values(flatApplicationMaps.byId).find(
+ (application) =>
+ application?.universalIdentifier ===
+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ );
+ if (!isDefined(otherApplication)) {
+ throw new Error('Standard application not found');
+ }
+ const ready = await exportToCompletion(input, cliToken);
+ const applications =
+ getAppProviderByClassName<ApplicationService>('ApplicationService');
+ try {
+ await applications.update(otherApplication.id, {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ defaultRoleId: roleId,
+ });
+ await download(ready).expect(200);
+ } finally {
+ await applications.update(otherApplication.id, {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ defaultRoleId: otherApplication.defaultRoleId,
+ });
+ }
+ });
+
+ it('invalidates an OAuth export when its application role changes', async () => {
+ const ready = await exportToCompletion(input, cliToken);
+ await setApplicationRole(roleId);
+ await download(ready).expect(403);
+ });
+
+ it('rejects a deleted OAuth application when reconstructing the export requester', async () => {
+ const ready = await exportToCompletion(input, cliToken);
+ const payload = await authorization(ready);
+ await globalThis.testDataSource.query(
+ 'UPDATE core.application SET "deletedAt" = NOW() WHERE id = $1',
+ [cliApplicationId],
+ );
+ await applicationCache().invalidateAndRecompute(SEED_APPLE_WORKSPACE_ID, [
+ 'flatApplicationMaps',
+ ]);
+ await expect(exports.assertPermissionsUnchanged(payload)).rejects.toThrow(
+ 'Access permissions have changed.',
+ );
+ await expect(exports.resolveRequester(payload)).rejects.toThrow(
+ /permission/i,
+ );
+ await download(ready).expect(403);
+ });
+
it('rejects an API key without export permission', async () => {
const requester = await createApiKey();
await changeRole({ canAccessAllTools: false });
@@ -905,7 +1116,7 @@ describe('record export lifecycle (integration)', () => {
}
});
- it.each(['export', 'row'])(
+ it.each(['export', 'row', 'application'])(
'stops generation when %s permission changes between pages',
async (permission) => {
const readPage = query.readPage.bind(query);
@@ -924,12 +1135,19 @@ describe('record export lifecycle (integration)', () => {
}
return readPage(...args);
});
- const { events } = subscribe(input, APPLE_JONY_MEMBER_ACCESS_TOKEN);
+ const { events } = subscribe(
+ input,
+ permission === 'application'
+ ? cliToken
+ : APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
try {
let recordExport = await nextExport(events);
await pageStarted;
if (permission === 'export') {
await changeRole({ canAccessAllTools: false });
+ } else if (permission === 'application') {
+ await setApplicationRole(roleId);
} else {
await upsertContainsRlsPredicate({
roleId,