The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(permissions): keep row access conditions outside user WHERE expressions (#27105)
Félix Malfaitec299bd5db97
diff --git a/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-joins.spec.ts b/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-joins.spec.tsindex 6e6718b1c90..c359216733c 100644--- a/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-joins.spec.ts+++ b/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-joins.spec.ts@@ -253,16 +253,7 @@ describe('WorkspaceSelectQueryBuilder joins', () => {);});- it('should clear applied row-level markers when where() replaces the WHERE', () => {- const { queryBuilder } = buildQueryBuilder();-- queryBuilder.markRowLevelPermissionApplied('person');- queryBuilder.where('"person"."id" = :id', { id: 1 });-- expect(queryBuilder.markRowLevelPermissionApplied('person')).toBe(true);- });-- it('should keep joined row-level markers when where() replaces the WHERE', () => {+ it('should keep applied row-level markers when where() replaces the WHERE', () => {const { queryBuilder } = buildQueryBuilder();queryBuilder.leftJoin('person.company', 'company');@@ -270,7 +261,7 @@ describe('WorkspaceSelectQueryBuilder joins', () => {queryBuilder.markRowLevelPermissionApplied('company');queryBuilder.where('"person"."id" = :id', { id: 1 });- expect(queryBuilder.markRowLevelPermissionApplied('person')).toBe(true);+ expect(queryBuilder.markRowLevelPermissionApplied('person')).toBe(false);expect(queryBuilder.markRowLevelPermissionApplied('company')).toBe(false);});});diff --git a/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-row-access.spec.ts b/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-row-access.spec.tsnew file mode 100644index 00000000000..6e218b2a637--- /dev/null+++ b/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-row-access.spec.ts@@ -0,0 +1,145 @@+import {+ applyRowAccessCondition,+ buildQueryBuilder,+} from 'src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-test-shapes.util';++const GUARDED_OR_CHAIN =+ '(("person"."id" = :a) OR ("person"."id" = :b)) AND ("person"."companyId" = :rowAccessCompanyId)';++const countOccurrences = (text: string, searched: string): number =>+ text.split(searched).length - 1;++const buildRowAccessQueryBuilder = () => {+ const built = buildQueryBuilder({ onBeforeExecute: applyRowAccessCondition });++ built.queryBuilder.setFindOptions({ select: { id: true } });++ return built;+};++describe('WorkspaceSelectQueryBuilder row access conditions', () => {+ it('should not let an orWhere bypass the row access condition', async () => {+ const { queryBuilder, executedStatements } = buildRowAccessQueryBuilder();++ await queryBuilder+ .where('"person"."id" = :a', { a: 1 })+ .orWhere('"person"."id" = :b', { b: 2 })+ .getMany();++ expect(executedStatements[0].text).toContain(+ 'WHERE ((("person"."id" = $1) OR ("person"."id" = $2)) AND ("person"."companyId" = $3)) AND "person"."deletedAt" IS NULL',+ );+ expect(executedStatements[0].values).toEqual([1, 2, 'company-1']);+ });++ it('should keep an orWhere added after the policy was applied inside the guarded expression', () => {+ const { queryBuilder } = buildRowAccessQueryBuilder();++ queryBuilder+ .where('"person"."id" = :a', { a: 1 })+ .applyRowLevelPermissions()+ .orWhere('"person"."id" = :b', { b: 2 });++ expect(queryBuilder.getQuery()).toContain(GUARDED_OR_CHAIN);+ });++ it('should guard a count', async () => {+ const { queryBuilder, executedStatements } = buildRowAccessQueryBuilder();++ await queryBuilder+ .where('"person"."id" = :a', { a: 1 })+ .orWhere('"person"."id" = :b', { b: 2 })+ .getCount();++ expect(executedStatements[0].text).toContain(+ '(("person"."id" = $1) OR ("person"."id" = $2)) AND ("person"."companyId" = $3)',+ );+ });++ it('should guard a mutation built from the select builder', () => {+ const { queryBuilder } = buildRowAccessQueryBuilder();++ const mutationQueryBuilder = queryBuilder+ .where('"person"."id" = :a', { a: 1 })+ .orWhere('"person"."id" = :b', { b: 2 })+ .applyRowLevelPermissions()+ .delete();++ expect(mutationQueryBuilder.getQuery()).toBe(+ `DELETE FROM "workspace_1wgvd1injqtife6y4rvfbu3h5"."person" AS "person" WHERE ${GUARDED_OR_CHAIN}`,+ );+ });++ it('should carry the row access condition onto a clone without applying it twice', async () => {+ const { queryBuilder, executedStatements } = buildRowAccessQueryBuilder();++ queryBuilder+ .where('"person"."id" = :a', { a: 1 })+ .applyRowLevelPermissions();++ await queryBuilder+ .clone()+ .orWhere('"person"."id" = :b', { b: 2 })+ .getMany();++ expect(executedStatements[0].text).toContain(+ '(("person"."id" = $1) OR ("person"."id" = $2)) AND ("person"."companyId" = $3)',+ );+ expect(+ countOccurrences(executedStatements[0].text, '"person"."companyId"'),+ ).toBe(1);+ });++ it('should keep the row access condition exactly once after where() replaces the WHERE', async () => {+ const { queryBuilder, executedStatements } = buildRowAccessQueryBuilder();++ await queryBuilder.where('"person"."id" = :a', { a: 1 }).getMany();+ await queryBuilder+ .where('"person"."id" = :b', { b: 2 })+ .orWhere('"person"."id" = :c', { c: 3 })+ .getMany();++ expect(executedStatements[1].text).toContain(+ '(("person"."id" = $1) OR ("person"."id" = $2)) AND ("person"."companyId" = $3)',+ );+ expect(+ countOccurrences(executedStatements[1].text, '"person"."companyId"'),+ ).toBe(1);+ });++ it('should keep the row access condition on a mutation built after where() replaces the WHERE', () => {+ const { queryBuilder } = buildRowAccessQueryBuilder();++ const mutationQueryBuilder = queryBuilder+ .applyRowLevelPermissions()+ .where('"person"."id" = :a', { a: 1 })+ .orWhere('"person"."id" = :b', { b: 2 })+ .delete();++ expect(mutationQueryBuilder.getQuery()).toBe(+ `DELETE FROM "workspace_1wgvd1injqtife6y4rvfbu3h5"."person" AS "person" WHERE ${GUARDED_OR_CHAIN}`,+ );+ });++ it('should carry the row access condition into a builder that copies the where clauses', () => {+ const { queryBuilder } = buildRowAccessQueryBuilder();+ const { queryBuilder: snapshotQueryBuilder } = buildQueryBuilder();++ queryBuilder+ .where('"person"."id" = :a', { a: 1 })+ .orWhere('"person"."id" = :b', { b: 2 })+ .applyRowLevelPermissions();++ snapshotQueryBuilder+ .setFindOptions({ select: { id: true } })+ .withDeleted()+ .copyWhereFrom(queryBuilder);++ expect(snapshotQueryBuilder.getQuery()).toContain(+ `WHERE ${GUARDED_OR_CHAIN}`,+ );+ expect(snapshotQueryBuilder.getParameters()).toMatchObject({+ rowAccessCompanyId: 'company-1',+ });+ });+});diff --git a/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-test-shapes.util.ts b/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-test-shapes.util.tsindex ecac2867a17..81112950452 100644--- a/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-test-shapes.util.ts+++ b/packages/twenty-server/src/engine/twenty-orm/query-builder/__tests__/workspace-select-query-builder-test-shapes.util.ts@@ -83,12 +83,29 @@ export const personTableShape: WorkspaceTableShape = {hasDeletedAtColumn: true,};+export const ROW_ACCESS_CONDITION =+ '"person"."companyId" = :rowAccessCompanyId';++export const applyRowAccessCondition = (+ queryBuilder: WorkspaceSelectQueryBuilder,+): void => {+ if (!queryBuilder.markRowLevelPermissionApplied(queryBuilder.alias)) {+ return;+ }++ queryBuilder.addRowAccessCondition(ROW_ACCESS_CONDITION, {+ rowAccessCompanyId: 'company-1',+ });+};+export const buildQueryBuilder = ({rows = [],tableShape = personTableShape,+ onBeforeExecute = () => undefined,}: {rows?: Record<string, unknown>[];tableShape?: WorkspaceTableShape;+ onBeforeExecute?: (queryBuilder: WorkspaceSelectQueryBuilder) => void;} = {}) => {const executedStatements: CompiledStatement[] = [];@@ -103,7 +120,7 @@ export const buildQueryBuilder = ({},objectRecordsPermissions: {},tableShapeByObjectMetadataId: () => companyTableShape,- onBeforeExecute: () => undefined,+ onBeforeExecute,formatResult: (records) => records as never,});diff --git a/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-mutation-query-builder.ts b/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-mutation-query-builder.tsindex d9da1da30f8..48569e1651c 100644--- a/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-mutation-query-builder.ts+++ b/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-mutation-query-builder.ts@@ -42,6 +42,7 @@ export class WorkspaceMutationQueryBuilder {private readonly context: MutationQueryBuilderContext;private readonly kind: MutationKind;private readonly whereClauses: WhereClause[];+ private readonly rowAccessConditions: string[];private readonly includeDeleted: boolean;private parameters: Record<string, unknown>;private setRecord: Record<string, unknown> = {};@@ -52,6 +53,7 @@ export class WorkspaceMutationQueryBuilder {kind,context,whereClauses,+ rowAccessConditions,includeDeleted,parameters,}: {@@ -59,6 +61,7 @@ export class WorkspaceMutationQueryBuilder {kind: MutationKind;context: MutationQueryBuilderContext;whereClauses: WhereClause[];+ rowAccessConditions: string[];includeDeleted: boolean;parameters: Record<string, unknown>;}) {@@ -67,6 +70,7 @@ export class WorkspaceMutationQueryBuilder {this.context = context;this.tableShape = context.tableShape;this.whereClauses = [...whereClauses];+ this.rowAccessConditions = [...rowAccessConditions];this.includeDeleted = includeDeleted;this.parameters = { ...parameters };}@@ -124,6 +128,7 @@ export class WorkspaceMutationQueryBuilder {kind: this.kind,setClauses,whereClauses: this.whereClauses,+ rowAccessConditions: this.rowAccessConditions,includeDeleted: this.includeDeleted,returningColumns: this.returningColumns,});diff --git a/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts b/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.tsindex f5b1df8fad2..f92b15b3019 100644--- a/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts+++ b/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts@@ -83,6 +83,7 @@ export class WorkspaceSelectQueryBuilder implements WhereExpressionLike {private readonly context: QueryBuilderContext;private readonly whereClauses: WhereClause[] = [];+ private readonly rowAccessConditions: string[] = [];private readonly joinClauses: JoinClause[] = [];private readonly existsFilterClauses: ExistsFilterClause[] = [];private readonly extraSelectClauses: SelectClause[] = [];@@ -126,6 +127,7 @@ export class WorkspaceSelectQueryBuilder implements WhereExpressionLike {);cloned.whereClauses.push(...this.whereClauses);+ cloned.rowAccessConditions.push(...this.rowAccessConditions);cloned.existsFilterClauses.push(...this.existsFilterClauses.map((existsFilterClause) => ({...existsFilterClause,@@ -165,13 +167,13 @@ export class WorkspaceSelectQueryBuilder implements WhereExpressionLike {parameters?: Record<string, unknown>,): this {this.whereClauses.length = 0;- this.aliasesWithRowLevelPermissionApplied.delete(this.alias);return this.appendWhere('and', condition, parameters);}copyWhereFrom(source: WorkspaceSelectQueryBuilder): this {this.whereClauses.push(...source.whereClauses);+ this.rowAccessConditions.push(...source.rowAccessConditions);this.existsFilterClauses.push(...source.existsFilterClauses.map((existsFilterClause) => ({...existsFilterClause,@@ -197,6 +199,21 @@ export class WorkspaceSelectQueryBuilder implements WhereExpressionLike {return this.appendWhere('or', condition, parameters);}+ addRowAccessCondition(+ condition: string,+ parameters?: Record<string, unknown>,+ ): this {+ if (isDefined(parameters)) {+ this.setParameters(parameters);+ }++ if (condition.length > 0) {+ this.rowAccessConditions.push(condition);+ }++ return this;+ }+setParameters(parameters: Record<string, unknown>): this {for (const parameterName of Object.keys(parameters)) {if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {@@ -796,6 +813,7 @@ export class WorkspaceSelectQueryBuilder implements WhereExpressionLike {formatResult: this.context.formatResult,},whereClauses: this.whereClauses,+ rowAccessConditions: this.rowAccessConditions,includeDeleted: this.includeDeleted,parameters: this.parameters,});@@ -1268,6 +1286,7 @@ export class WorkspaceSelectQueryBuilder implements WhereExpressionLike {columnSelections: this.resolveColumnSelections(),joinClauses: this.joinClauses,whereClauses: this.whereClauses,+ rowAccessConditions: this.rowAccessConditions,existsFilterClauses: this.existsFilterClauses,groupByExpressions: this.groupByExpressions,orderByClauses: this.orderByClauses,diff --git a/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts b/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.tsindex 2b82f4859ed..e64487cf756 100644--- a/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts+++ b/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts@@ -2246,7 +2246,7 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {.where({ id: In(recordIds) }).withDeleted().select(['id'])- .andWhere(condition.sql, condition.parameters)+ .addRowAccessCondition(condition.sql, condition.parameters).getMany<ObjectRecord>({ noFormatting: true });return new Set(admittedRecords.map((record) => String(record.id)));@@ -2426,7 +2426,7 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {parameters: ObjectLiteral;}): void {if (alias === queryBuilder.alias) {- queryBuilder.andWhere(sql, parameters);+ queryBuilder.addRowAccessCondition(sql, parameters);return;}diff --git a/packages/twenty-server/src/engine/twenty-orm/sql/utils/__tests__/build-mutation-statement.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/sql/utils/__tests__/build-mutation-statement.util.spec.tsnew file mode 100644index 00000000000..4aa070b018d--- /dev/null+++ b/packages/twenty-server/src/engine/twenty-orm/sql/utils/__tests__/build-mutation-statement.util.spec.ts@@ -0,0 +1,103 @@+import { FieldMetadataType } from 'twenty-shared/types';++import {+ buildMutationStatement,+ type MutationStatementState,+} from 'src/engine/twenty-orm/sql/utils/build-mutation-statement.util';+import { type WorkspaceTableShape } from 'src/engine/twenty-orm/table-shape/types/workspace-table-shape.type';++const SCHEMA_NAME = 'workspace_1wgvd1injqtife6y4rvfbu3h5';++const buildColumn = (columnName: string) => ({+ columnName,+ fieldMetadataId: `field-${columnName}`,+ fieldName: columnName,+ fieldMetadataType: FieldMetadataType.TEXT,+});++const personTableShape: WorkspaceTableShape = {+ objectMetadataId: 'person-object-id',+ nameSingular: 'person',+ schemaName: SCHEMA_NAME,+ tableName: 'person',+ columnShapeByColumnName: {+ id: buildColumn('id'),+ jobTitle: buildColumn('jobTitle'),+ deletedAt: buildColumn('deletedAt'),+ },+ columnNames: ['id', 'jobTitle', 'deletedAt'],+ relationShapeByFieldName: {},+ hasDeletedAtColumn: true,+};++const buildState = (+ overrides: Partial<MutationStatementState> = {},+): MutationStatementState => ({+ alias: 'person',+ tableShape: personTableShape,+ kind: 'update',+ setClauses: [{ columnName: 'jobTitle', valueExpression: ':jobTitle' }],+ whereClauses: [+ { operator: 'and', sql: '("person"."id" = :a)' },+ { operator: 'or', sql: '("person"."id" = :b)' },+ ],+ rowAccessConditions: ['"person"."ownerId" = :ownerId'],+ includeDeleted: false,+ returningColumns: [],+ ...overrides,+});++describe('buildMutationStatement', () => {+ it('should keep row access conditions outside a user OR chain on an update', () => {+ expect(buildMutationStatement(buildState())).toBe(+ `UPDATE "${SCHEMA_NAME}"."person" AS "person" SET "jobTitle" = :jobTitle ` ++ 'WHERE (("person"."id" = :a) OR ("person"."id" = :b)) AND ("person"."ownerId" = :ownerId)',+ );+ });++ it('should keep row access conditions outside a user OR chain on a delete', () => {+ expect(+ buildMutationStatement(buildState({ kind: 'delete', setClauses: [] })),+ ).toBe(+ `DELETE FROM "${SCHEMA_NAME}"."person" AS "person" ` ++ 'WHERE (("person"."id" = :a) OR ("person"."id" = :b)) AND ("person"."ownerId" = :ownerId)',+ );+ });++ it('should keep the live-row predicate outside the guarded expression on a soft delete', () => {+ expect(+ buildMutationStatement(+ buildState({+ kind: 'soft-delete',+ setClauses: [+ { columnName: 'deletedAt', valueExpression: 'CURRENT_TIMESTAMP' },+ ],+ }),+ ),+ ).toContain(+ 'WHERE ((("person"."id" = :a) OR ("person"."id" = :b)) AND ("person"."ownerId" = :ownerId)) AND "person"."deletedAt" IS NULL',+ );+ });++ it('should render row access conditions alone when there is no user where', () => {+ expect(+ buildMutationStatement(+ buildState({ kind: 'delete', setClauses: [], whereClauses: [] }),+ ),+ ).toBe(+ `DELETE FROM "${SCHEMA_NAME}"."person" AS "person" ` ++ 'WHERE ("person"."ownerId" = :ownerId)',+ );+ });++ it('should render a user OR chain unchanged when there is no row access condition', () => {+ expect(+ buildMutationStatement(+ buildState({ kind: 'delete', setClauses: [], rowAccessConditions: [] }),+ ),+ ).toBe(+ `DELETE FROM "${SCHEMA_NAME}"."person" AS "person" ` ++ 'WHERE ("person"."id" = :a) OR ("person"."id" = :b)',+ );+ });+});diff --git a/packages/twenty-server/src/engine/twenty-orm/sql/utils/__tests__/build-select-statement.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/sql/utils/__tests__/build-select-statement.util.spec.tsnew file mode 100644index 00000000000..3a6bb3dde5e--- /dev/null+++ b/packages/twenty-server/src/engine/twenty-orm/sql/utils/__tests__/build-select-statement.util.spec.ts@@ -0,0 +1,128 @@+import { FieldMetadataType } from 'twenty-shared/types';++import {+ buildCountStatement,+ buildSelectStatement,+ type SelectStatementState,+} from 'src/engine/twenty-orm/sql/utils/build-select-statement.util';+import { type WorkspaceTableShape } from 'src/engine/twenty-orm/table-shape/types/workspace-table-shape.type';++const SCHEMA_NAME = 'workspace_1wgvd1injqtife6y4rvfbu3h5';++const buildColumn = (columnName: string) => ({+ columnName,+ fieldMetadataId: `field-${columnName}`,+ fieldName: columnName,+ fieldMetadataType: FieldMetadataType.TEXT,+});++const personTableShape: WorkspaceTableShape = {+ objectMetadataId: 'person-object-id',+ nameSingular: 'person',+ schemaName: SCHEMA_NAME,+ tableName: 'person',+ columnShapeByColumnName: {+ id: buildColumn('id'),+ deletedAt: buildColumn('deletedAt'),+ },+ columnNames: ['id', 'deletedAt'],+ relationShapeByFieldName: {},+ hasDeletedAtColumn: true,+};++const buildState = (+ overrides: Partial<SelectStatementState> = {},+): SelectStatementState => ({+ alias: 'person',+ tableShape: personTableShape,+ findOptions: { select: { id: true } },+ extraSelectClauses: [],+ columnSelections: [],+ joinClauses: [],+ whereClauses: [],+ rowAccessConditions: [],+ existsFilterClauses: [],+ groupByExpressions: [],+ orderByClauses: [],+ distinctOnExpressions: [],+ includeDeleted: false,+ allowPlainToManyJoins: false,+ ...overrides,+});++const OR_CHAIN_WHERE_CLAUSES: SelectStatementState['whereClauses'] = [+ { operator: 'and', sql: '("person"."id" = :a)' },+ { operator: 'or', sql: '("person"."id" = :b)' },+];++const ROW_ACCESS_CONDITION = '"person"."ownerId" = :ownerId';++describe('buildSelectStatement', () => {+ it('should keep row access conditions outside a user OR chain', () => {+ const sql = buildSelectStatement(+ buildState({+ whereClauses: OR_CHAIN_WHERE_CLAUSES,+ rowAccessConditions: [ROW_ACCESS_CONDITION],+ includeDeleted: true,+ }),+ );++ expect(sql).toBe(+ `SELECT "person"."id" AS "person_id" FROM "${SCHEMA_NAME}"."person" AS "person" ` ++ 'WHERE (("person"."id" = :a) OR ("person"."id" = :b)) AND ("person"."ownerId" = :ownerId)',+ );+ });++ it('should keep the soft-delete predicate outside both the user expression and row access conditions', () => {+ const sql = buildSelectStatement(+ buildState({+ whereClauses: OR_CHAIN_WHERE_CLAUSES,+ rowAccessConditions: [ROW_ACCESS_CONDITION],+ }),+ );++ expect(sql).toContain(+ 'WHERE ((("person"."id" = :a) OR ("person"."id" = :b)) AND ("person"."ownerId" = :ownerId)) AND "person"."deletedAt" IS NULL',+ );+ });++ it('should AND every row access condition', () => {+ const sql = buildSelectStatement(+ buildState({+ whereClauses: OR_CHAIN_WHERE_CLAUSES,+ rowAccessConditions: [ROW_ACCESS_CONDITION, 'EXISTS (SELECT 1) OR 1=1'],+ includeDeleted: true,+ }),+ );++ expect(sql).toContain(+ 'WHERE (("person"."id" = :a) OR ("person"."id" = :b)) AND ("person"."ownerId" = :ownerId) AND (EXISTS (SELECT 1) OR 1=1)',+ );+ });++ it('should render row access conditions alone when there is no user where', () => {+ const sql = buildSelectStatement(+ buildState({+ rowAccessConditions: [ROW_ACCESS_CONDITION],+ includeDeleted: true,+ }),+ );++ expect(sql).toContain('WHERE ("person"."ownerId" = :ownerId)');+ });++ it('should keep row access conditions outside a user OR chain in a count', () => {+ const sql = buildCountStatement(+ buildState({+ whereClauses: OR_CHAIN_WHERE_CLAUSES,+ rowAccessConditions: [ROW_ACCESS_CONDITION],+ includeDeleted: true,+ }),+ );++ expect(sql).toBe(+ `SELECT COUNT(1) AS "count" FROM "${SCHEMA_NAME}"."person" AS "person" ` ++ 'WHERE (("person"."id" = :a) OR ("person"."id" = :b)) AND ("person"."ownerId" = :ownerId)',+ );+ });+});diff --git a/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-mutation-statement.util.ts b/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-mutation-statement.util.tsindex 5638c59dca0..e39e4a7feab 100644--- a/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-mutation-statement.util.ts+++ b/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-mutation-statement.util.ts@@ -6,7 +6,7 @@ import {import { buildColumnResultAlias } from 'src/engine/twenty-orm/sql/utils/build-column-result-alias.util';import {quoteColumn,- renderUserWhereExpression,+ renderWhereExpressionWithRowAccess,type WhereClause,} from 'src/engine/twenty-orm/sql/utils/build-select-statement.util';import { type WorkspaceTableShape } from 'src/engine/twenty-orm/table-shape/types/workspace-table-shape.type';@@ -24,6 +24,7 @@ export type MutationStatementState = {kind: MutationKind;setClauses: SetClause[];whereClauses: WhereClause[];+ rowAccessConditions: string[];includeDeleted: boolean;returningColumns: string[];};@@ -57,20 +58,23 @@ const buildSetClause = (state: MutationStatementState): string =>.join(', ')}`;const buildWhereExpression = (state: MutationStatementState): string => {- const userExpression = renderUserWhereExpression(state.whereClauses);+ const filterExpression = renderWhereExpressionWithRowAccess({+ whereClauses: state.whereClauses,+ rowAccessConditions: state.rowAccessConditions,+ });const shouldSkipTrashedRows =state.kind === 'soft-delete' &&!state.includeDeleted &&state.tableShape.hasDeletedAtColumn;if (!shouldSkipTrashedRows) {- return userExpression;+ return filterExpression;}const liveRowPredicate = `${quoteColumn(state.alias, 'deletedAt')} IS NULL`;- return userExpression.length > 0- ? `(${userExpression}) AND ${liveRowPredicate}`+ return filterExpression.length > 0+ ? `(${filterExpression}) AND ${liveRowPredicate}`: liveRowPredicate;};diff --git a/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-select-statement.util.ts b/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-select-statement.util.tsindex 24a515bd0a6..93bd390cc37 100644--- a/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-select-statement.util.ts+++ b/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-select-statement.util.ts@@ -74,6 +74,7 @@ export type SelectStatementState = {columnSelections: ColumnSelection[];joinClauses: JoinClause[];whereClauses: WhereClause[];+ rowAccessConditions: string[];existsFilterClauses: ExistsFilterClause[];groupByExpressions: string[];orderByClauses: OrderByClause[];@@ -288,9 +289,7 @@ export const buildProjection = (return { expressions, mainAliasColumnNames };};-export const renderUserWhereExpression = (- whereClauses: WhereClause[],-): string =>+const renderUserWhereExpression = (whereClauses: WhereClause[]): string =>whereClauses.map((clause, index) =>index === 0@@ -299,6 +298,30 @@ export const renderUserWhereExpression = ().join(' ');+// Row access conditions stay outside the user expression so an OR in it can+// never bypass them+export const renderWhereExpressionWithRowAccess = ({+ whereClauses,+ rowAccessConditions,+}: {+ whereClauses: WhereClause[];+ rowAccessConditions: string[];+}): string => {+ const userExpression = renderUserWhereExpression(whereClauses);++ if (rowAccessConditions.length === 0) {+ return userExpression;+ }++ const rowAccessExpression = rowAccessConditions+ .map((rowAccessCondition) => `(${rowAccessCondition})`)+ .join(' AND ');++ return userExpression.length > 0+ ? `(${userExpression}) AND ${rowAccessExpression}`+ : rowAccessExpression;+};+const renderExistsFilter = (existsFilterClause: ExistsFilterClause,includeDeleted: boolean,@@ -357,18 +380,21 @@ export const buildWhereExpression = (substituteExistsFilters?: boolean;} = {},): string => {- const renderedWhereClauses = quoteQualifiedAliasReferences(- renderUserWhereExpression(state.whereClauses),+ const renderedWhereExpression = quoteQualifiedAliasReferences(+ renderWhereExpressionWithRowAccess({+ whereClauses: state.whereClauses,+ rowAccessConditions: state.rowAccessConditions,+ }),collectStatementAliases(state),);- const userExpression = substituteExistsFilters+ const filterExpression = substituteExistsFilters? substituteExistsFilterTokens({- expression: renderedWhereClauses,+ expression: renderedWhereExpression,existsFilterClauses: state.existsFilterClauses,includeDeleted: state.includeDeleted,})- : renderedWhereClauses;+ : renderedWhereExpression;const shouldAddSoftDeletePredicate =includeSoftDeletePredicate &&@@ -376,16 +402,16 @@ export const buildWhereExpression = (state.tableShape.hasDeletedAtColumn;if (!shouldAddSoftDeletePredicate) {- return userExpression;+ return filterExpression;}const softDeletePredicate = `${quoteColumn(state.alias, 'deletedAt')} IS NULL`;- if (userExpression.length === 0) {+ if (filterExpression.length === 0) {return softDeletePredicate;}- return `(${userExpression}) AND ${softDeletePredicate}`;+ return `(${filterExpression}) AND ${softDeletePredicate}`;};export const buildFromClause = (state: SelectStatementState): string =>