Skip to content

The open alternative to Salesforce, designed for AI.

fix(email-tool): resolve the default sender through the caller entitlement filter (#25908)

Etienne5000352c3a02
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts
index d2974180039..2bfcd54d2bb 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts
@@ -266,6 +266,7 @@ export class ActionToolProvider implements ToolProvider {
workspaceId: context.workspaceId,
userId: context.userId,
userWorkspaceId: context.userWorkspaceId,
+ callerType: context.authContext?.type,
threadId: context.threadId,
onCodeExecutionUpdate: context.onCodeExecutionUpdate,
});
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
index 24773c631ef..5ff9d56ea77 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
@@ -10,14 +10,13 @@ import {
} from 'twenty-shared/types';
import {
canConnectedAccountPerformEmailOperation,
- getEmailProvidersForOperation,
isDefined,
- isNonEmptyArray,
isValidUuid,
} from 'twenty-shared/utils';
import { In, IsNull, LessThanOrEqual, type Repository } from 'typeorm';
import { z } from 'zod';
+import { type WorkspaceAuthContextType } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { FileService } from 'src/engine/core-modules/file/services/file.service';
import { compileOutboundEmailContent } from 'src/engine/core-modules/email/utils/compile-outbound-email-content.util';
@@ -32,6 +31,8 @@ import { EmailComposerResult } from 'src/engine/core-modules/tool/tools/email-to
import { parseCommaSeparatedEmails } from 'src/engine/core-modules/tool/tools/email-tool/utils/parse-comma-separated-emails.util';
import { selectConnectedAccountIdForCaller } from 'src/engine/core-modules/tool/tools/email-tool/utils/select-connected-account-id-for-caller.util';
import { type ToolExecutionContext } from 'src/engine/core-modules/tool/types/tool-execution-context.type';
+import { ConnectedAccountMetadataService } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.service';
+import { isCallerBypassingAccountVisibility } from 'src/engine/metadata-modules/connected-account/utils/is-caller-bypassing-account-visibility.util';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
@@ -58,6 +59,7 @@ export class EmailComposerService {
@InjectWorkspaceScopedRepository(FileEntity)
private readonly fileRepository: WorkspaceScopedRepository<FileEntity>,
private readonly fileService: FileService,
+ private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,
) {}
private async getConnectedAccountOrThrow({
@@ -115,55 +117,41 @@ export class EmailComposerService {
workspaceId,
userWorkspaceId,
operation,
+ callerType,
}: {
workspaceId: string;
userWorkspaceId?: string;
operation: EmailOperation;
+ callerType?: WorkspaceAuthContextType;
}): Promise<string> {
- const authContext = buildSystemAuthContext(workspaceId);
-
- return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const mailboxes = await this.connectedAccountRepository.find({
- where: {
+ const usableMailboxes = isCallerBypassingAccountVisibility(callerType)
+ ? await this.connectedAccountMetadataService.findWorkspaceMailboxes({
workspaceId,
- archivedAt: IsNull(),
- provider: In(getEmailProvidersForOperation(operation)),
- },
- order: { createdAt: 'ASC', id: 'ASC' },
- });
-
- const usableMailboxes = mailboxes.filter((connectedAccount) =>
- canConnectedAccountPerformEmailOperation({
- connectedAccount,
operation,
- }),
- );
-
- if (!isNonEmptyArray(usableMailboxes)) {
- throw new EmailToolException(
- `No connected account in this workspace can ${operation.toLowerCase()} email`,
- EmailToolExceptionCode.NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT,
- );
- }
-
- if (!isDefined(userWorkspaceId)) {
- return usableMailboxes[0].id;
- }
+ })
+ : await this.connectedAccountMetadataService.findMailboxesUsableByCaller({
+ workspaceId,
+ userWorkspaceId,
+ operation,
+ });
- const connectedAccountId = selectConnectedAccountIdForCaller({
- connectedAccounts: usableMailboxes,
- userWorkspaceId,
- });
+ const connectedAccountId = isDefined(userWorkspaceId)
+ ? selectConnectedAccountIdForCaller({
+ connectedAccounts: usableMailboxes,
+ userWorkspaceId,
+ })
+ : usableMailboxes[0]?.id;
- if (!isDefined(connectedAccountId)) {
- throw new EmailToolException(
- `No connected account available for user workspace '${userWorkspaceId}' that can ${operation.toLowerCase()} email`,
- EmailToolExceptionCode.NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT,
- );
- }
+ if (!isDefined(connectedAccountId)) {
+ throw new EmailToolException(
+ isDefined(userWorkspaceId)
+ ? `No connected account available for user workspace '${userWorkspaceId}' that can ${operation.toLowerCase()} email`
+ : `No connected account in this workspace can ${operation.toLowerCase()} email`,
+ EmailToolExceptionCode.NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT,
+ );
+ }
- return connectedAccountId;
- }, authContext);
+ return connectedAccountId;
}
private normalizeRecipients(parameters: ComposeEmailParams): {
@@ -365,7 +353,7 @@ export class EmailComposerService {
context: ToolExecutionContext;
operation: EmailOperation;
}): Promise<EmailComposerResult> {
- const { workspaceId, userWorkspaceId } = context;
+ const { workspaceId, userWorkspaceId, callerType } = context;
const { subject, body, files, inReplyTo, fromHandle } = parameters;
let { connectedAccountId } = parameters;
@@ -408,6 +396,7 @@ export class EmailComposerService {
workspaceId,
userWorkspaceId,
operation,
+ callerType,
});
}
diff --git a/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts b/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts
index aed3c2a2a8b..0857e1ea20d 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts
@@ -1,9 +1,11 @@
+import { type WorkspaceAuthContextType } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { type CodeExecutionStreamEmitter } from 'src/engine/core-modules/tool-provider/interfaces/code-execution-stream-emitter.type';
export type ToolExecutionContext = {
workspaceId: string;
userId?: string;
userWorkspaceId?: string;
+ callerType?: WorkspaceAuthContextType;
threadId?: string;
onCodeExecutionUpdate?: CodeExecutionStreamEmitter;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts
index fc30aa45c0a..697ea1d5800 100644
--- a/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts
@@ -50,13 +50,11 @@ export class ConnectedAccountMetadataService {
private readonly workspaceEventEmitter: WorkspaceEventEmitter,
) {}
- async findMailboxesUsableByCaller({
+ async findWorkspaceMailboxes({
workspaceId,
- userWorkspaceId,
operation,
}: {
workspaceId: string;
- userWorkspaceId?: string;
operation: EmailOperation;
}): Promise<ConnectedAccountUsableByCaller[]> {
const connectedAccounts = await this.repository.find({
@@ -78,21 +76,36 @@ export class ConnectedAccountMetadataService {
},
});
- return connectedAccounts
- .filter((connectedAccount) =>
- canConnectedAccountPerformEmailOperation({
- connectedAccount,
- operation,
- }),
- )
- .filter((connectedAccount) =>
- isDefined(userWorkspaceId)
- ? isConnectedAccountUsableByCaller({
- connectedAccount,
- userWorkspaceId,
- })
- : connectedAccount.visibility === 'workspace',
- );
+ return connectedAccounts.filter((connectedAccount) =>
+ canConnectedAccountPerformEmailOperation({
+ connectedAccount,
+ operation,
+ }),
+ );
+ }
+
+ async findMailboxesUsableByCaller({
+ workspaceId,
+ userWorkspaceId,
+ operation,
+ }: {
+ workspaceId: string;
+ userWorkspaceId?: string;
+ operation: EmailOperation;
+ }): Promise<ConnectedAccountUsableByCaller[]> {
+ const mailboxes = await this.findWorkspaceMailboxes({
+ workspaceId,
+ operation,
+ });
+
+ return mailboxes.filter((connectedAccount) =>
+ isDefined(userWorkspaceId)
+ ? isConnectedAccountUsableByCaller({
+ connectedAccount,
+ userWorkspaceId,
+ })
+ : connectedAccount.visibility === 'workspace',
+ );
}
async findUsableByCaller({
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/__tests__/is-caller-bypassing-account-visibility.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/__tests__/is-caller-bypassing-account-visibility.util.spec.ts
new file mode 100644
index 00000000000..86fd32cd0f6
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/__tests__/is-caller-bypassing-account-visibility.util.spec.ts
@@ -0,0 +1,21 @@
+import { isCallerBypassingAccountVisibility } from 'src/engine/metadata-modules/connected-account/utils/is-caller-bypassing-account-visibility.util';
+
+describe('isCallerBypassingAccountVisibility', () => {
+ it.each(['application', 'system'] as const)(
+ 'accepts a %s run, the workspace acts on itself',
+ (callerType) => {
+ expect(isCallerBypassingAccountVisibility(callerType)).toBe(true);
+ },
+ );
+
+ it.each(['user', 'apiKey', 'pendingActivationUser'] as const)(
+ 'rejects a %s caller, it is held to account visibility',
+ (callerType) => {
+ expect(isCallerBypassingAccountVisibility(callerType)).toBe(false);
+ },
+ );
+
+ it('rejects an unidentified caller', () => {
+ expect(isCallerBypassingAccountVisibility(undefined)).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/is-caller-bypassing-account-visibility.util.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/is-caller-bypassing-account-visibility.util.ts
new file mode 100644
index 00000000000..f353eeecec5
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/is-caller-bypassing-account-visibility.util.ts
@@ -0,0 +1,13 @@
+import { type WorkspaceAuthContextType } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+
+export const isCallerBypassingAccountVisibility = (
+ callerType?: WorkspaceAuthContextType,
+): boolean => {
+ switch (callerType) {
+ case 'application':
+ case 'system':
+ return true;
+ default:
+ return false;
+ }
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts
index fb3f95248a3..7ce8f556024 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts
@@ -80,6 +80,7 @@ export abstract class EmailWorkflowActionBase extends ToolBackedWorkflowAction<W
return {
workspaceId: runInfo.workspaceId,
+ callerType: authContext.type,
...getUserFromAuthContext(authContext),
};
}
diff --git a/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts b/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts
index e4c663d9753..4616f598990 100644
--- a/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts
+++ b/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts
@@ -329,7 +329,7 @@ describe('EmailComposerService connected account resolution (integration)', () =
}
});
- it('skips an older SSO connection when there is no caller (workflow run)', async () => {
+ it('skips an older SSO connection on a run that no user started', async () => {
const oidcConnectedAccountId = '20202020-0000-4000-8000-0000000000a3';
await insertNonMailboxConnectedAccount({
@@ -344,7 +344,7 @@ describe('EmailComposerService connected account resolution (integration)', () =
const result = await service.composeEmail({
parameters: baseParams,
- context: { workspaceId: WORKSPACE_ID },
+ context: { workspaceId: WORKSPACE_ID, callerType: 'application' },
operation: EmailOperation.SEND,
});
@@ -412,13 +412,13 @@ describe('EmailComposerService connected account resolution (integration)', () =
}
});
- it('takes the first workspace account when there is no caller (workflow run)', async () => {
+ it('takes the first workspace account on a run that no user started', async () => {
const firstWorkspaceConnectedAccountId =
await getFirstWorkspaceConnectedAccountId();
const result = await service.composeEmail({
parameters: baseParams,
- context: { workspaceId: WORKSPACE_ID },
+ context: { workspaceId: WORKSPACE_ID, callerType: 'application' },
operation: EmailOperation.SEND,
});
@@ -427,5 +427,53 @@ describe('EmailComposerService connected account resolution (integration)', () =
firstWorkspaceConnectedAccountId,
);
});
+
+ it('refuses an unidentified caller when no account is shared with the workspace', async () => {
+ const sharedConnectedAccountIds =
+ await getWorkspaceSharedConnectedAccountIds();
+
+ for (const connectedAccountId of sharedConnectedAccountIds) {
+ await setVisibility(connectedAccountId, 'user');
+ }
+
+ try {
+ await expect(
+ service.composeEmail({
+ parameters: baseParams,
+ context: { workspaceId: WORKSPACE_ID },
+ operation: EmailOperation.SEND,
+ }),
+ ).rejects.toThrow(
+ 'No connected account in this workspace can send email',
+ );
+ } finally {
+ for (const connectedAccountId of sharedConnectedAccountIds) {
+ await setVisibility(connectedAccountId, 'workspace');
+ }
+ }
+ });
+
+ it('serves an unidentified caller the account shared with the workspace', async () => {
+ const { visibility } = await readConnectedAccountState(
+ JONY_CONNECTED_ACCOUNT_ID,
+ );
+
+ await setVisibility(JONY_CONNECTED_ACCOUNT_ID, 'workspace');
+
+ try {
+ const result = await service.composeEmail({
+ parameters: baseParams,
+ context: { workspaceId: WORKSPACE_ID },
+ operation: EmailOperation.SEND,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.success && result.data.connectedAccount.id).toBe(
+ JONY_CONNECTED_ACCOUNT_ID,
+ );
+ } finally {
+ await setVisibility(JONY_CONNECTED_ACCOUNT_ID, visibility);
+ }
+ });
});
});