Skip to content

The open alternative to Salesforce, designed for AI.

fix(server): reject empty filter on bulk mutations to prevent unbounded delete/update (#24746)

Charles Bochet1f98653cc8d5
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
index 32aec8b8d8f..5dbc76b33c3 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
@@ -22,6 +22,7 @@ import {
} from 'src/engine/api/common/common-query-runners/errors/common-query-runner.exception';
import { STANDARD_ERROR_MESSAGE } from 'src/engine/api/common/common-query-runners/errors/standard-error-message.constant';
import { buildMutationQueryBuilderV2 } from 'src/engine/api/common/common-query-runners/utils/build-mutation-query-builder-v2.util';
+import { isRecordFilterEmpty } from 'src/engine/api/common/common-query-runners/utils/is-record-filter-empty.util';
import { CommonResultGettersService } from 'src/engine/api/common/common-result-getters/common-result-getters.service';
import { CommonBaseQueryRunnerContext } from 'src/engine/api/common/types/common-base-query-runner-context.type';
import { CommonExtendedQueryRunnerContext } from 'src/engine/api/common/types/common-extended-query-runner-context.type';
@@ -423,6 +424,14 @@ export abstract class CommonBaseQueryRunnerService<
const { flatObjectMetadata, commonQueryParser } = queryRunnerContext;
const alias = flatObjectMetadata.nameSingular;
+ if (isRecordFilterEmpty(filter)) {
+ throw new CommonQueryRunnerException(
+ 'A non-empty filter is required for a bulk mutation',
+ CommonQueryRunnerExceptionCode.INVALID_ARGS_FILTER,
+ { userFriendlyMessage: STANDARD_ERROR_MESSAGE },
+ );
+ }
+
const writeRepository = this.getWriteRepository(queryRunnerContext);
const resolvedData =
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/utils/__tests__/is-record-filter-empty.util.spec.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/utils/__tests__/is-record-filter-empty.util.spec.ts
new file mode 100644
index 00000000000..a8ac529dd85
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/utils/__tests__/is-record-filter-empty.util.spec.ts
@@ -0,0 +1,53 @@
+import { type ObjectRecordFilter } from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
+
+import { isRecordFilterEmpty } from 'src/engine/api/common/common-query-runners/utils/is-record-filter-empty.util';
+
+const asFilter = (filter: unknown) => filter as Partial<ObjectRecordFilter>;
+
+describe('isRecordFilterEmpty', () => {
+ it('should treat a filter with no keys as empty', () => {
+ expect(isRecordFilterEmpty({})).toBe(true);
+ });
+
+ it('should treat an empty "and" group as empty', () => {
+ expect(isRecordFilterEmpty(asFilter({ and: [] }))).toBe(true);
+ });
+
+ it('should treat an empty "or" group as empty', () => {
+ expect(isRecordFilterEmpty(asFilter({ or: [] }))).toBe(true);
+ });
+
+ it('should treat a "not" wrapping an empty filter as empty', () => {
+ expect(isRecordFilterEmpty(asFilter({ not: {} }))).toBe(true);
+ });
+
+ it('should treat a group whose every element is empty as empty', () => {
+ expect(isRecordFilterEmpty(asFilter({ and: [{}, { or: [] }] }))).toBe(true);
+ });
+
+ it('should not treat an id condition as empty', () => {
+ expect(
+ isRecordFilterEmpty(
+ asFilter({ id: { in: ['20202020-0000-0000-0000-000000000000'] } }),
+ ),
+ ).toBe(false);
+ });
+
+ it('should not treat a field condition as empty', () => {
+ expect(isRecordFilterEmpty(asFilter({ name: { eq: 'Twenty' } }))).toBe(
+ false,
+ );
+ });
+
+ it('should not treat a group holding a real condition as empty', () => {
+ expect(
+ isRecordFilterEmpty(asFilter({ and: [{}, { name: { eq: 'Twenty' } }] })),
+ ).toBe(false);
+ });
+
+ it('should not treat a "not" wrapping a real condition as empty', () => {
+ expect(
+ isRecordFilterEmpty(asFilter({ not: { name: { eq: 'Twenty' } } })),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/utils/is-record-filter-empty.util.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/utils/is-record-filter-empty.util.ts
new file mode 100644
index 00000000000..5d6d4c65505
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/utils/is-record-filter-empty.util.ts
@@ -0,0 +1,33 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ObjectRecordFilter } from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
+
+type RecordFilter = Partial<ObjectRecordFilter>;
+
+export const isRecordFilterEmpty = (filter: RecordFilter): boolean => {
+ const filterEntries = Object.entries(filter);
+
+ if (filterEntries.length === 0) {
+ return true;
+ }
+
+ return filterEntries.every(([filterKey, filterValue]) => {
+ if (filterKey === 'and' || filterKey === 'or') {
+ const subFilters: RecordFilter[] = isDefined(filterValue)
+ ? filterValue
+ : [];
+
+ return subFilters.every(isRecordFilterEmpty);
+ }
+
+ if (filterKey === 'not') {
+ const negatedFilter: RecordFilter = isDefined(filterValue)
+ ? filterValue
+ : {};
+
+ return isRecordFilterEmpty(negatedFilter);
+ }
+
+ return false;
+ });
+};
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/services/delete-many-records.service.ts b/packages/twenty-server/src/engine/core-modules/record-crud/services/delete-many-records.service.ts
index 3966a0a90de..c0e342d01f4 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/services/delete-many-records.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/services/delete-many-records.service.ts
@@ -8,9 +8,11 @@ import {
import { CommonApiContextBuilderService } from 'src/engine/core-modules/record-crud/services/common-api-context-builder.service';
import { type DeleteManyRecordsParams } from 'src/engine/core-modules/record-crud/types/delete-many-records-params.type';
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
-import { isDefined, isEmptyObject } from 'twenty-shared/utils';
+import { isDefined } from 'twenty-shared/utils';
import { canObjectBeManagedByAutomation } from 'twenty-shared/workflow';
+import { isRecordFilterEmpty } from 'src/engine/api/common/common-query-runners/utils/is-record-filter-empty.util';
+
@Injectable()
export class DeleteManyRecordsService {
private readonly logger = new Logger(DeleteManyRecordsService.name);
@@ -23,7 +25,7 @@ export class DeleteManyRecordsService {
async execute(params: DeleteManyRecordsParams): Promise<ToolOutput> {
const { objectName, filter, authContext, rolePermissionConfig } = params;
- if (!isDefined(filter) || isEmptyObject(filter)) {
+ if (!isDefined(filter) || isRecordFilterEmpty(filter)) {
return {
success: false,
message: `Failed to delete records from ${objectName}`,
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/services/update-many-records.service.ts b/packages/twenty-server/src/engine/core-modules/record-crud/services/update-many-records.service.ts
index 61ccab7c162..342ccd0e9ec 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/services/update-many-records.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/services/update-many-records.service.ts
@@ -1,8 +1,10 @@
import { Injectable, Logger } from '@nestjs/common';
+import { isDefined } from 'twenty-shared/utils';
import { canObjectBeManagedByAutomation } from 'twenty-shared/workflow';
import { CommonUpdateManyQueryRunnerService } from 'src/engine/api/common/common-query-runners/common-update-many-query-runner.service';
+import { isRecordFilterEmpty } from 'src/engine/api/common/common-query-runners/utils/is-record-filter-empty.util';
import {
RecordCrudException,
RecordCrudExceptionCode,
@@ -26,6 +28,15 @@ export class UpdateManyRecordsService {
const { objectName, filter, data, authContext, rolePermissionConfig } =
params;
+ if (!isDefined(filter) || isRecordFilterEmpty(filter)) {
+ return {
+ success: false,
+ message: `Failed to update records in ${objectName}`,
+ error:
+ 'Filter must not be empty — updating without a filter is not allowed',
+ };
+ }
+
try {
const {
queryRunnerContext,
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/types/delete-many-records-params.type.ts b/packages/twenty-server/src/engine/core-modules/record-crud/types/delete-many-records-params.type.ts
index 2276c72394d..e4dfe9898af 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/types/delete-many-records-params.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/types/delete-many-records-params.type.ts
@@ -1,9 +1,11 @@
+import { type ObjectRecordFilter } from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
+
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
export type DeleteManyRecordsParams = {
objectName: string;
- filter: Record<string, unknown>;
+ filter: Partial<ObjectRecordFilter>;
authContext: WorkspaceAuthContext;
rolePermissionConfig?: RolePermissionConfig;
};
diff --git a/packages/twenty-server/test/integration/graphql/suites/inputs-validation/filter-validation/empty-filter-mutation-validation.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/inputs-validation/filter-validation/empty-filter-mutation-validation.integration-spec.ts
new file mode 100644
index 00000000000..abe325238db
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/inputs-validation/filter-validation/empty-filter-mutation-validation.integration-spec.ts
@@ -0,0 +1,110 @@
+import { destroyManyObjectsMetadata } from 'test/integration/graphql/suites/inputs-validation/utils/destroy-many-objects-metadata';
+import { setupTestObjectsWithAllFieldTypes } from 'test/integration/graphql/suites/inputs-validation/utils/setup-test-objects-with-all-field-types.util';
+import { deleteManyOperationFactory } from 'test/integration/graphql/utils/delete-many-operation-factory.util';
+import { destroyManyOperationFactory } from 'test/integration/graphql/utils/destroy-many-operation-factory.util';
+import { makeGraphqlAPIRequestWithApiKey } from 'test/integration/graphql/utils/make-graphql-api-request-with-api-key.util';
+import { restoreManyOperationFactory } from 'test/integration/graphql/utils/restore-many-operation-factory.util';
+import { updateManyOperationFactory } from 'test/integration/graphql/utils/update-many-operation-factory.util';
+
+import { CommonQueryRunnerExceptionCode } from 'src/engine/api/common/common-query-runners/errors/common-query-runner.exception';
+
+describe('Empty filter bulk mutation validation', () => {
+ let objectMetadataId: string;
+ let objectMetadataSingularName: string;
+ let objectMetadataPluralName: string;
+ let targetObjectMetadata1Id: string;
+ let targetObjectMetadata2Id: string;
+
+ const expectEmptyFilterRejection = (response: {
+ body: { errors?: any[] };
+ }) => {
+ expect(response.body.errors).toBeDefined();
+ expect(response.body.errors?.[0].extensions.subCode).toBe(
+ CommonQueryRunnerExceptionCode.INVALID_ARGS_FILTER,
+ );
+ };
+
+ beforeAll(async () => {
+ const setupTest = await setupTestObjectsWithAllFieldTypes();
+
+ objectMetadataId = setupTest.objectMetadataId;
+ objectMetadataSingularName = setupTest.objectMetadataSingularName;
+ objectMetadataPluralName = setupTest.objectMetadataPluralName;
+ targetObjectMetadata1Id = setupTest.targetObjectMetadata1Id;
+ targetObjectMetadata2Id = setupTest.targetObjectMetadata2Id;
+ });
+
+ afterAll(async () => {
+ await destroyManyObjectsMetadata([
+ objectMetadataId,
+ targetObjectMetadata1Id,
+ targetObjectMetadata2Id,
+ ]);
+ });
+
+ it('should reject destroyMany with an empty filter', async () => {
+ const graphqlOperation = destroyManyOperationFactory({
+ objectMetadataSingularName,
+ objectMetadataPluralName,
+ gqlFields: 'id',
+ filter: {},
+ });
+
+ const response = await makeGraphqlAPIRequestWithApiKey(graphqlOperation);
+
+ expectEmptyFilterRejection(response);
+ });
+
+ it('should reject deleteMany with an empty filter', async () => {
+ const graphqlOperation = deleteManyOperationFactory({
+ objectMetadataSingularName,
+ objectMetadataPluralName,
+ gqlFields: 'id',
+ filter: {},
+ });
+
+ const response = await makeGraphqlAPIRequestWithApiKey(graphqlOperation);
+
+ expectEmptyFilterRejection(response);
+ });
+
+ it('should reject updateMany with an empty filter', async () => {
+ const graphqlOperation = updateManyOperationFactory({
+ objectMetadataSingularName,
+ objectMetadataPluralName,
+ gqlFields: 'id',
+ data: { textField: 'updated' },
+ filter: {},
+ });
+
+ const response = await makeGraphqlAPIRequestWithApiKey(graphqlOperation);
+
+ expectEmptyFilterRejection(response);
+ });
+
+ it('should reject restoreMany with an empty filter', async () => {
+ const graphqlOperation = restoreManyOperationFactory({
+ objectMetadataSingularName,
+ objectMetadataPluralName,
+ gqlFields: 'id',
+ filter: {},
+ });
+
+ const response = await makeGraphqlAPIRequestWithApiKey(graphqlOperation);
+
+ expectEmptyFilterRejection(response);
+ });
+
+ it('should reject destroyMany with a nested empty logical filter', async () => {
+ const graphqlOperation = destroyManyOperationFactory({
+ objectMetadataSingularName,
+ objectMetadataPluralName,
+ gqlFields: 'id',
+ filter: { and: [] },
+ });
+
+ const response = await makeGraphqlAPIRequestWithApiKey(graphqlOperation);
+
+ expectEmptyFilterRejection(response);
+ });
+});