Skip to content

The open alternative to Salesforce, designed for AI.

Require the application role to cover every agent role (#26413)

Abdul Rahmanba2533ac74c1
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index 36590aa5dc3..2043ca924ae 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -76,6 +76,7 @@ When adding AI behavior:
- Keep instructions grounded in available app data and tools.
- State when the agent should ask for missing workspace or record context.
- Avoid exposing raw IDs, timestamps, or nested API output to end users when a readable answer is possible.
+- A `defineAgent` `roleUniversalIdentifier` must reference a role the app defines, and the application role (`defineApplicationRole` or `defaultRoleUniversalIdentifier`) must cover every permission that agent role grants. The build and `yarn twenty apply` fail otherwise, listing the excess grants.
## Connection Providers
diff --git a/packages/twenty-apps/fixtures/minimal-app/application.config.ts b/packages/twenty-apps/fixtures/minimal-app/application.config.ts
index 7a6f7439cc1..36d1e753952 100644
--- a/packages/twenty-apps/fixtures/minimal-app/application.config.ts
+++ b/packages/twenty-apps/fixtures/minimal-app/application.config.ts
@@ -4,5 +4,5 @@ export default defineApplication({
universalIdentifier: 'e1e2e3e4-e5e6-4000-8000-000000000001',
displayName: 'Root App',
description: 'An app with all entities at root level',
- defaultRoleUniversalIdentifier: 'e1e2e3e4-e5e6-4000-8000-000000000002',
+ defaultRoleUniversalIdentifier: 'e1e2e3e4-e5e6-4000-8000-000000000040',
});
diff --git a/packages/twenty-apps/public/slack/src/roles/default-function.role.ts b/packages/twenty-apps/public/slack/src/roles/default-function.role.ts
index 4169264f68a..643135fec65 100644
--- a/packages/twenty-apps/public/slack/src/roles/default-function.role.ts
+++ b/packages/twenty-apps/public/slack/src/roles/default-function.role.ts
@@ -15,7 +15,7 @@ export default defineApplicationRole({
universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
label: 'Twenty Slack tools role',
description:
- 'Tools only forward requests to Slack using the configured connected account. Tracks assistant requests, links Slack accounts to workspace members (which needs read access on workspace members for the email match), keeps per-channel rules for the assistant, reads CRM records to render record link previews in Slack, and runs the assistant agent; write access to the CRM is granted separately through the role assigned to the agent.',
+ 'Everything the Slack app can do in the CRM. Tools only forward requests to Slack using the configured connected account. Tracks assistant requests, links Slack accounts to workspace members (which needs read access on workspace members for the email match), keeps per-channel rules for the assistant, reads CRM records to render record link previews in Slack, and runs the assistant agent, which creates, updates and soft-deletes people, companies, opportunities, notes and tasks through the narrower Slack Assistant role.',
canReadAllObjectRecords: false,
canUpdateAllObjectRecords: false,
canSoftDeleteAllObjectRecords: false,
@@ -62,13 +62,15 @@ export default defineApplicationRole({
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.opportunity.universalIdentifier,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.note.universalIdentifier,
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.noteTarget.universalIdentifier,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.task.universalIdentifier,
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.taskTarget.universalIdentifier,
] as const
).map((objectUniversalIdentifier) => ({
objectUniversalIdentifier,
canReadObjectRecords: true,
- canUpdateObjectRecords: false,
- canSoftDeleteObjectRecords: false,
+ canUpdateObjectRecords: true,
+ canSoftDeleteObjectRecords: true,
canDestroyObjectRecords: false,
})),
],
diff --git a/packages/twenty-docs/developers/extend/apps/config/roles.mdx b/packages/twenty-docs/developers/extend/apps/config/roles.mdx
index 908461d07e0..8ca8e3007f7 100644
--- a/packages/twenty-docs/developers/extend/apps/config/roles.mdx
+++ b/packages/twenty-docs/developers/extend/apps/config/roles.mdx
@@ -212,7 +212,11 @@ Notes:
- Exactly **one** `defineApplicationRole(...)` is allowed per app — the manifest build will fail if it finds more than one.
- Use `defineRole()` (not `defineApplicationRole()`) for any **additional** roles your app ships.
-- Setting `defaultRoleUniversalIdentifier` explicitly on `defineApplication()` is still supported for backward compatibility, but is deprecated in favor of `defineApplicationRole()`.
+- Setting `defaultRoleUniversalIdentifier` explicitly on `defineApplication()` is still supported for backward compatibility, but is deprecated in favor of `defineApplicationRole()`. The identifier must match a role your app defines, or the build fails.
+
+### Agent roles
+
+The application role is what a workspace reviews when it installs your app, so it must cover everything the app itself can do. Any role you assign to an agent through `roleUniversalIdentifier` on `defineAgent()` must not grant more than the application role: no object action, field access, permission flag or row-level scope the application role lacks. If it does, the build fails with an error listing the excess grants. Roles your app ships for workspace members or API keys are not held to this rule, since the app never runs with them.
## Best practices
diff --git a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
index 5b8a2fe739f..a4281a31422 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
@@ -65,6 +65,7 @@ Key points:
- `icon` (optional) sets the icon displayed in the UI.
- `modelId` (optional) overrides the default AI model used by the agent.
- `responseFormat` (optional) controls the shape of the agent's output. Defaults to `{ type: 'text' }` for free-form text. Use `{ type: 'json', schema }` to force structured JSON output.
+- `roleUniversalIdentifier` (optional) binds the agent to a role your app defines. That role must not grant more than the application role, or the build fails; see [Agent roles](/developers/extend/apps/config/roles#agent-roles).
By default an agent returns free-form text. To get structured output, set `responseFormat` to `{ type: 'json' }` and provide a `schema`:
diff --git a/packages/twenty-sdk/src/cli/__tests__/apps/minimal-app/__integration__/app-dev/expected-manifest.ts b/packages/twenty-sdk/src/cli/__tests__/apps/minimal-app/__integration__/app-dev/expected-manifest.ts
index 9230b9f0a3b..67e2b79d423 100644
--- a/packages/twenty-sdk/src/cli/__tests__/apps/minimal-app/__integration__/app-dev/expected-manifest.ts
+++ b/packages/twenty-sdk/src/cli/__tests__/apps/minimal-app/__integration__/app-dev/expected-manifest.ts
@@ -11,7 +11,7 @@ export const EXPECTED_MANIFEST: Manifest = {
displayName: 'Root App',
description: 'An app with all entities at root level',
galleryImages: [],
- defaultRoleUniversalIdentifier: 'e1e2e3e4-e5e6-4000-8000-000000000002',
+ defaultRoleUniversalIdentifier: 'e1e2e3e4-e5e6-4000-8000-000000000040',
packageJsonChecksum: '[checksum]',
yarnLockChecksum: '[checksum]',
requiredServerVersionRange: null,
diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts
index fbe81024244..552e8e50f81 100644
--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts
+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts
@@ -11,6 +11,7 @@ import { fromRoleConfigToRoleManifest } from '@/cli/utilities/build/manifest/uti
import { getDefaultFieldsInObjectFields } from '@/cli/utilities/build/manifest/utils/get-default-fields-in-object-fields';
import { extractFrontComponentSharedDependencies } from '@/cli/utilities/build/manifest/utils/extract-front-component-shared-dependencies';
import { validateConditionalAvailabilityUsage } from '@/cli/utilities/build/manifest/utils/validate-conditional-availability-usage';
+import { validateAgentRolesWithinApplicationRole } from '@/cli/utilities/build/manifest/utils/validate-agent-roles-within-application-role';
import { validateViewFilterOperands } from '@/cli/utilities/build/manifest/utils/validate-view-filter-operands';
import { getEngineVersionRange } from '@/cli/utilities/version/get-engine-version-range';
import { type ApplicationConfig, type LogicFunctionConfig } from '@/sdk/define';
@@ -671,6 +672,21 @@ export const buildManifest = async (
}),
);
+ if (
+ isDefined(applicationConfig) &&
+ isDefined(resolvedDefaultRoleUniversalIdentifier)
+ ) {
+ errors.push(
+ ...validateAgentRolesWithinApplicationRole({
+ agents,
+ roles,
+ objects,
+ permissionFlags,
+ defaultRoleUniversalIdentifier: resolvedDefaultRoleUniversalIdentifier,
+ }),
+ );
+ }
+
const application: ApplicationManifest | undefined =
applicationConfig && resolvedDefaultRoleUniversalIdentifier
? (() => {
diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/utils/__tests__/validate-agent-roles-within-application-role.spec.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/utils/__tests__/validate-agent-roles-within-application-role.spec.ts
new file mode 100644
index 00000000000..f9c0ac3625b
--- /dev/null
+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/utils/__tests__/validate-agent-roles-within-application-role.spec.ts
@@ -0,0 +1,217 @@
+import { validateAgentRolesWithinApplicationRole } from '@/cli/utilities/build/manifest/utils/validate-agent-roles-within-application-role';
+import {
+ type AgentManifest,
+ type RoleManifest,
+} from 'twenty-shared/application';
+import { SystemPermissionFlag } from 'twenty-shared/constants';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+
+const APPLICATION_ROLE_UNIVERSAL_IDENTIFIER = 'application-role';
+const AGENT_ROLE_UNIVERSAL_IDENTIFIER = 'agent-role';
+const CUSTOM_OBJECT_UNIVERSAL_IDENTIFIER = 'custom-object';
+const PERSON_UNIVERSAL_IDENTIFIER = STANDARD_OBJECTS.person.universalIdentifier;
+
+const buildRole = (overrides: Partial<RoleManifest> = {}): RoleManifest => ({
+ universalIdentifier: AGENT_ROLE_UNIVERSAL_IDENTIFIER,
+ label: 'Agent role',
+ ...overrides,
+});
+
+const applicationRole = buildRole({
+ universalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ label: 'Application role',
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: PERSON_UNIVERSAL_IDENTIFIER,
+ canReadObjectRecords: true,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
+});
+
+const buildAgent = (overrides: Partial<AgentManifest> = {}): AgentManifest => ({
+ universalIdentifier: 'agent',
+ name: 'assistant',
+ label: 'Assistant',
+ prompt: 'Help.',
+ roleUniversalIdentifier: AGENT_ROLE_UNIVERSAL_IDENTIFIER,
+ ...overrides,
+});
+
+const customObject = {
+ universalIdentifier: CUSTOM_OBJECT_UNIVERSAL_IDENTIFIER,
+ nameSingular: 'ticket',
+};
+
+describe('validateAgentRolesWithinApplicationRole', () => {
+ it('accepts an agent role the application role covers', () => {
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [buildAgent()],
+ roles: [
+ applicationRole,
+ buildRole({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: PERSON_UNIVERSAL_IDENTIFIER,
+ canReadObjectRecords: true,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
+ }),
+ ],
+ objects: [],
+ permissionFlags: [],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([]);
+ });
+
+ it('ignores agents without a role and agents on the application role', () => {
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [
+ buildAgent({ roleUniversalIdentifier: undefined }),
+ buildAgent({
+ roleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ }),
+ ],
+ roles: [applicationRole],
+ objects: [],
+ permissionFlags: [],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([]);
+ });
+
+ it('reports every grant an agent role has beyond the application role', () => {
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [buildAgent(), buildAgent({ name: 'second-assistant' })],
+ roles: [
+ applicationRole,
+ buildRole({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: PERSON_UNIVERSAL_IDENTIFIER,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ },
+ {
+ objectUniversalIdentifier: CUSTOM_OBJECT_UNIVERSAL_IDENTIFIER,
+ canReadObjectRecords: true,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag.AI,
+ SystemPermissionFlag.WORKFLOWS,
+ ],
+ }),
+ ],
+ objects: [customObject],
+ permissionFlags: [],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([
+ 'Role "Agent role" used by agent "assistant", "second-assistant" grants more than the application role "Application role": permission flag WORKFLOWS, update person records, read ticket records. The application role must cover every permission an agent role grants.',
+ ]);
+ });
+
+ it('treats a custom permission flag without a permission type as a tool flag, like the server does', () => {
+ const customToolFlagUniversalIdentifier = 'custom-tool-flag';
+
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [buildAgent()],
+ roles: [
+ buildRole({
+ universalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ label: 'Application role',
+ canAccessAllTools: true,
+ }),
+ buildRole({
+ permissionFlagUniversalIdentifiers: [
+ customToolFlagUniversalIdentifier,
+ ],
+ }),
+ ],
+ objects: [],
+ permissionFlags: [
+ {
+ universalIdentifier: customToolFlagUniversalIdentifier,
+ key: 'CUSTOM_TOOL',
+ },
+ ],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([]);
+ });
+
+ it('reports a custom settings flag that access to all tools does not cover', () => {
+ const customSettingsFlagUniversalIdentifier = 'custom-settings-flag';
+
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [buildAgent()],
+ roles: [
+ buildRole({
+ universalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ label: 'Application role',
+ canAccessAllTools: true,
+ }),
+ buildRole({
+ permissionFlagUniversalIdentifiers: [
+ customSettingsFlagUniversalIdentifier,
+ ],
+ }),
+ ],
+ objects: [],
+ permissionFlags: [
+ {
+ universalIdentifier: customSettingsFlagUniversalIdentifier,
+ key: 'CUSTOM_SETTINGS',
+ permissionType: 'settings',
+ },
+ ],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([
+ 'Role "Agent role" used by agent "assistant" grants more than the application role "Application role": permission flag CUSTOM_SETTINGS. The application role must cover every permission an agent role grants.',
+ ]);
+ });
+
+ it('reports an agent role that is not defined by the application', () => {
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [buildAgent({ roleUniversalIdentifier: 'missing-role' })],
+ roles: [applicationRole],
+ objects: [],
+ permissionFlags: [],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([
+ 'Agent "assistant" references role "missing-role", which is not defined by this application.',
+ ]);
+ });
+
+ it('reports a missing application role and still checks agent role references', () => {
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [
+ buildAgent(),
+ buildAgent({
+ name: 'lost-assistant',
+ roleUniversalIdentifier: 'missing-role',
+ }),
+ ],
+ roles: [buildRole({ canReadAllObjectRecords: true })],
+ objects: [],
+ permissionFlags: [],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([
+ 'Application default role "application-role" is not defined by this application.',
+ 'Agent "lost-assistant" references role "missing-role", which is not defined by this application.',
+ ]);
+ });
+});
diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/utils/validate-agent-roles-within-application-role.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/utils/validate-agent-roles-within-application-role.ts
new file mode 100644
index 00000000000..c5ac19079e5
--- /dev/null
+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/utils/validate-agent-roles-within-application-role.ts
@@ -0,0 +1,245 @@
+import {
+ type AgentManifest,
+ getRoleManifestGrantsNotCoveredBy,
+ type ObjectManifest,
+ type PermissionFlagManifest,
+ type RoleManifest,
+ type RoleManifestGrant,
+} from 'twenty-shared/application';
+import { SystemPermissionFlag } from 'twenty-shared/constants';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { isDefined } from 'twenty-shared/utils';
+
+type ObjectDescriptor = Pick<
+ ObjectManifest,
+ 'universalIdentifier' | 'nameSingular'
+>;
+
+type PermissionFlagDescriptor = Pick<
+ PermissionFlagManifest,
+ 'universalIdentifier' | 'key' | 'permissionType'
+>;
+
+type AgentNamesByRoleUniversalIdentifier = Map<string, string[]>;
+
+const OBJECT_ACTION_LABELS = {
+ canReadObjectRecords: 'read',
+ canUpdateObjectRecords: 'update',
+ canSoftDeleteObjectRecords: 'soft-delete',
+ canDestroyObjectRecords: 'destroy',
+} as const;
+
+const SYSTEM_PERMISSION_FLAG_KEY_BY_UNIVERSAL_IDENTIFIER = Object.fromEntries(
+ Object.entries(SystemPermissionFlag).map(([key, universalIdentifier]) => [
+ universalIdentifier,
+ key,
+ ]),
+);
+
+const STANDARD_OBJECT_NAME_BY_UNIVERSAL_IDENTIFIER = Object.fromEntries(
+ Object.entries(STANDARD_OBJECTS).map(([name, { universalIdentifier }]) => [
+ universalIdentifier,
+ name,
+ ]),
+);
+
+const describeGrant = ({
+ grant,
+ objects,
+ permissionFlags,
+}: {
+ grant: RoleManifestGrant;
+ objects: ObjectDescriptor[];
+ permissionFlags: PermissionFlagDescriptor[];
+}): string => {
+ const describeObject = (objectUniversalIdentifier: string) =>
+ objects.find(
+ (object) => object.universalIdentifier === objectUniversalIdentifier,
+ )?.nameSingular ??
+ STANDARD_OBJECT_NAME_BY_UNIVERSAL_IDENTIFIER[objectUniversalIdentifier] ??
+ objectUniversalIdentifier;
+
+ switch (grant.type) {
+ case 'ALL_OBJECT_RECORDS':
+ return `${OBJECT_ACTION_LABELS[grant.action]} all object records`;
+ case 'ALL_SETTINGS':
+ return 'update all settings';
+ case 'ALL_TOOLS':
+ return 'access all tools';
+ case 'PERMISSION_FLAG': {
+ const flagKey =
+ permissionFlags.find(
+ (flag) =>
+ flag.universalIdentifier ===
+ grant.permissionFlagUniversalIdentifier,
+ )?.key ??
+ SYSTEM_PERMISSION_FLAG_KEY_BY_UNIVERSAL_IDENTIFIER[
+ grant.permissionFlagUniversalIdentifier
+ ] ??
+ grant.permissionFlagUniversalIdentifier;
+
+ return `permission flag ${flagKey}`;
+ }
+ case 'OBJECT_RECORDS':
+ return `${OBJECT_ACTION_LABELS[grant.action]} ${describeObject(grant.objectUniversalIdentifier)} records`;
+ case 'FIELD_VALUE':
+ return `${grant.action === 'canReadFieldValue' ? 'read' : 'update'} field ${grant.fieldUniversalIdentifier} of ${describeObject(grant.objectUniversalIdentifier)}`;
+ case 'ROW_LEVEL_RESTRICTION':
+ return `${describeObject(grant.objectUniversalIdentifier)} records without the row-level restriction`;
+ }
+};
+
+const describeAgentList = (agentNames: string[]): string =>
+ agentNames.map((name) => `"${name}"`).join(', ');
+
+const groupAgentNamesByRoleUniversalIdentifier = ({
+ agents,
+ defaultRoleUniversalIdentifier,
+}: {
+ agents: AgentManifest[];
+ defaultRoleUniversalIdentifier: string;
+}): AgentNamesByRoleUniversalIdentifier => {
+ const agentNamesByRoleUniversalIdentifier: AgentNamesByRoleUniversalIdentifier =
+ new Map();
+
+ for (const agent of agents) {
+ if (
+ !isDefined(agent.roleUniversalIdentifier) ||
+ agent.roleUniversalIdentifier === defaultRoleUniversalIdentifier
+ ) {
+ continue;
+ }
+
+ agentNamesByRoleUniversalIdentifier.set(agent.roleUniversalIdentifier, [
+ ...(agentNamesByRoleUniversalIdentifier.get(
+ agent.roleUniversalIdentifier,
+ ) ?? []),
+ agent.name,
+ ]);
+ }
+
+ return agentNamesByRoleUniversalIdentifier;
+};
+
+const validateApplicationDefaultRoleIsDefined = ({
+ applicationRole,
+ defaultRoleUniversalIdentifier,
+}: {
+ applicationRole: RoleManifest | undefined;
+ defaultRoleUniversalIdentifier: string;
+}): string[] =>
+ isDefined(applicationRole)
+ ? []
+ : [
+ `Application default role "${defaultRoleUniversalIdentifier}" is not defined by this application.`,
+ ];
+
+const validateAgentRolesAreDefined = ({
+ agentNamesByRoleUniversalIdentifier,
+ roles,
+}: {
+ agentNamesByRoleUniversalIdentifier: AgentNamesByRoleUniversalIdentifier;
+ roles: RoleManifest[];
+}): string[] =>
+ [...agentNamesByRoleUniversalIdentifier]
+ .filter(
+ ([roleUniversalIdentifier]) =>
+ !roles.some(
+ (role) => role.universalIdentifier === roleUniversalIdentifier,
+ ),
+ )
+ .map(
+ ([roleUniversalIdentifier, agentNames]) =>
+ `Agent ${describeAgentList(agentNames)} references role "${roleUniversalIdentifier}", which is not defined by this application.`,
+ );
+
+const validateAgentRolesAreCoveredByApplicationRole = ({
+ agentNamesByRoleUniversalIdentifier,
+ applicationRole,
+ roles,
+ objects,
+ permissionFlags,
+}: {
+ agentNamesByRoleUniversalIdentifier: AgentNamesByRoleUniversalIdentifier;
+ applicationRole: RoleManifest;
+ roles: RoleManifest[];
+ objects: ObjectDescriptor[];
+ permissionFlags: PermissionFlagDescriptor[];
+}): string[] => {
+ const toolPermissionFlagUniversalIdentifiers = permissionFlags
+ .filter((flag) => (flag.permissionType ?? 'tool') === 'tool')
+ .map((flag) => flag.universalIdentifier);
+
+ return [...agentNamesByRoleUniversalIdentifier].flatMap(
+ ([roleUniversalIdentifier, agentNames]) => {
+ const agentRole = roles.find(
+ (role) => role.universalIdentifier === roleUniversalIdentifier,
+ );
+
+ if (!isDefined(agentRole)) {
+ return [];
+ }
+
+ const uncoveredGrants = getRoleManifestGrantsNotCoveredBy({
+ role: agentRole,
+ superset: applicationRole,
+ toolPermissionFlagUniversalIdentifiers,
+ });
+
+ if (uncoveredGrants.length === 0) {
+ return [];
+ }
+
+ const grantList = uncoveredGrants
+ .map((grant) => describeGrant({ grant, objects, permissionFlags }))
+ .join(', ');
+
+ return [
+ `Role "${agentRole.label}" used by agent ${describeAgentList(agentNames)} grants more than the application role "${applicationRole.label}": ${grantList}. The application role must cover every permission an agent role grants.`,
+ ];
+ },
+ );
+};
+
+export const validateAgentRolesWithinApplicationRole = ({
+ agents,
+ roles,
+ objects,
+ permissionFlags,
+ defaultRoleUniversalIdentifier,
+}: {
+ agents: AgentManifest[];
+ roles: RoleManifest[];
+ objects: ObjectDescriptor[];
+ permissionFlags: PermissionFlagDescriptor[];
+ defaultRoleUniversalIdentifier: string;
+}): string[] => {
+ const applicationRole = roles.find(
+ (role) => role.universalIdentifier === defaultRoleUniversalIdentifier,
+ );
+ const agentNamesByRoleUniversalIdentifier =
+ groupAgentNamesByRoleUniversalIdentifier({
+ agents,
+ defaultRoleUniversalIdentifier,
+ });
+
+ return [
+ ...validateApplicationDefaultRoleIsDefined({
+ applicationRole,
+ defaultRoleUniversalIdentifier,
+ }),
+ ...validateAgentRolesAreDefined({
+ agentNamesByRoleUniversalIdentifier,
+ roles,
+ }),
+ ...(isDefined(applicationRole)
+ ? validateAgentRolesAreCoveredByApplicationRole({
+ agentNamesByRoleUniversalIdentifier,
+ applicationRole,
+ roles,
+ objects,
+ permissionFlags,
+ })
+ : []),
+ ];
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/permission-flag/constants/standard-permission-flag-definitions.constant.ts b/packages/twenty-server/src/engine/metadata-modules/permission-flag/constants/standard-permission-flag-definitions.constant.ts
index cac467ee024..7302629ddf2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/permission-flag/constants/standard-permission-flag-definitions.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/permission-flag/constants/standard-permission-flag-definitions.constant.ts
@@ -1,10 +1,10 @@
import {
PermissionFlagType,
SystemPermissionFlag,
+ TOOL_PERMISSION_FLAGS,
} from 'twenty-shared/constants';
import { type PermissionFlagPermissionType } from 'src/engine/metadata-modules/permission-flag/constants/permission-flag-permission-type.constant';
-import { TOOL_PERMISSION_FLAGS } from 'src/engine/metadata-modules/permissions/constants/tool-permission-flags';
export type StandardPermissionFlagDefinition = {
key: PermissionFlagType;
diff --git a/packages/twenty-server/src/engine/metadata-modules/permissions/constants/tool-permission-flags.ts b/packages/twenty-server/src/engine/metadata-modules/permissions/constants/tool-permission-flags.ts
deleted file mode 100644
index 126a3cf1630..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/permissions/constants/tool-permission-flags.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export const TOOL_PERMISSION_FLAGS = [
- 'AI',
- 'VIEWS',
- 'UPLOAD_FILE',
- 'DOWNLOAD_FILE',
- 'SEND_EMAIL_TOOL',
- 'CREATE_CALENDAR_EVENT_TOOL',
- 'HTTP_REQUEST_TOOL',
- 'IMPORT_CSV',
- 'EXPORT_CSV',
- 'CONNECTED_ACCOUNTS',
- 'PROFILE_INFORMATION',
- 'CODE_INTERPRETER_TOOL',
-];
diff --git a/packages/twenty-server/src/engine/metadata-modules/permissions/permissions.service.ts b/packages/twenty-server/src/engine/metadata-modules/permissions/permissions.service.ts
index 30902ecaa50..c20979c0aa5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/permissions/permissions.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/permissions/permissions.service.ts
@@ -4,6 +4,7 @@ import { msg } from '@lingui/core/macro';
import {
PermissionFlagType,
SystemPermissionFlag,
+ TOOL_PERMISSION_FLAGS,
} from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
@@ -16,7 +17,6 @@ import {
import { type FlatRolePermissionFlagMaps } from 'src/engine/metadata-modules/flat-role-permission-flag/types/flat-role-permission-flag-maps.type';
import { type FlatRole } from 'src/engine/metadata-modules/flat-role/types/flat-role.type';
import { flatRoleHasPermissionFlag } from 'src/engine/metadata-modules/flat-role/utils/flat-role-has-permission-flag.util';
-import { TOOL_PERMISSION_FLAGS } from 'src/engine/metadata-modules/permissions/constants/tool-permission-flags';
import {
PermissionsException,
PermissionsExceptionCode,
@@ -50,7 +50,7 @@ export class PermissionsService {
private readonly applicationRepository: WorkspaceScopedRepository<ApplicationEntity>,
) {}
- private isToolPermission(feature: string) {
+ private isToolPermission(feature: PermissionFlagType) {
return TOOL_PERMISSION_FLAGS.includes(feature);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/permissions/utils/resolve-user-workspace-ids-with-permission-flag.util.ts b/packages/twenty-server/src/engine/metadata-modules/permissions/utils/resolve-user-workspace-ids-with-permission-flag.util.ts
index 9fcfa9e6c67..42da058952e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/permissions/utils/resolve-user-workspace-ids-with-permission-flag.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/permissions/utils/resolve-user-workspace-ids-with-permission-flag.util.ts
@@ -1,5 +1,8 @@
import { isNonEmptyString } from '@sniptt/guards';
-import { type PermissionFlagType } from 'twenty-shared/constants';
+import {
+ type PermissionFlagType,
+ TOOL_PERMISSION_FLAGS,
+} from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
import { type FlatRolePermissionFlagMaps } from 'src/engine/metadata-modules/flat-role-permission-flag/types/flat-role-permission-flag-maps.type';
@@ -8,7 +11,6 @@ import { type FlatRoleMaps } from 'src/engine/metadata-modules/flat-role/types/f
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { type FlatRole } from 'src/engine/metadata-modules/flat-role/types/flat-role.type';
import { flatRoleHasPermissionFlag } from 'src/engine/metadata-modules/flat-role/utils/flat-role-has-permission-flag.util';
-import { TOOL_PERMISSION_FLAGS } from 'src/engine/metadata-modules/permissions/constants/tool-permission-flags';
export const resolveUserWorkspaceIdsWithPermissionFlag = ({
permissionFlag,
diff --git a/packages/twenty-shared/src/application/__tests__/getRoleManifestGrantsNotCoveredBy.test.ts b/packages/twenty-shared/src/application/__tests__/getRoleManifestGrantsNotCoveredBy.test.ts
new file mode 100644
index 00000000000..418915737d0
--- /dev/null
+++ b/packages/twenty-shared/src/application/__tests__/getRoleManifestGrantsNotCoveredBy.test.ts
@@ -0,0 +1,350 @@
+import { type RoleManifest } from '@/application/roleManifestType';
+import { getRoleManifestGrantsNotCoveredBy } from '@/application/utils/getRoleManifestGrantsNotCoveredBy';
+import { SystemPermissionFlag } from '@/constants';
+import {
+ RowLevelPermissionPredicateGroupLogicalOperator,
+ RowLevelPermissionPredicateOperand,
+} from '@/types';
+
+const PERSON = 'object-person';
+const COMPANY = 'object-company';
+const EMAIL_FIELD = 'field-email';
+
+const buildRole = (overrides: Partial<RoleManifest> = {}): RoleManifest => ({
+ universalIdentifier: 'role',
+ label: 'Role',
+ ...overrides,
+});
+
+describe('getRoleManifestGrantsNotCoveredBy', () => {
+ it('returns nothing when the superset covers the role', () => {
+ const role = buildRole({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: PERSON,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
+ });
+ const superset = buildRole({
+ canReadAllObjectRecords: true,
+ objectPermissions: [
+ { objectUniversalIdentifier: PERSON, canUpdateObjectRecords: true },
+ ],
+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
+ });
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([]);
+ });
+
+ it('reports role-level flags the superset lacks', () => {
+ const role = buildRole({
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ canUpdateAllSettings: true,
+ canAccessAllTools: true,
+ });
+ const superset = buildRole({ canReadAllObjectRecords: true });
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([
+ { type: 'ALL_OBJECT_RECORDS', action: 'canUpdateObjectRecords' },
+ { type: 'ALL_SETTINGS' },
+ { type: 'ALL_TOOLS' },
+ ]);
+ });
+
+ it('reports per-object actions the superset lacks', () => {
+ const role = buildRole({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: PERSON,
+ canReadObjectRecords: true,
+ canSoftDeleteObjectRecords: true,
+ },
+ { objectUniversalIdentifier: COMPANY, canReadObjectRecords: true },
+ ],
+ });
+ const superset = buildRole({
+ objectPermissions: [
+ { objectUniversalIdentifier: PERSON, canReadObjectRecords: true },
+ ],
+ });
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([
+ {
+ type: 'OBJECT_RECORDS',
+ objectUniversalIdentifier: PERSON,
+ action: 'canSoftDeleteObjectRecords',
+ },
+ {
+ type: 'OBJECT_RECORDS',
+ objectUniversalIdentifier: COMPANY,
+ action: 'canReadObjectRecords',
+ },
+ ]);
+ });
+
+ it('reports an object the superset denies while the role reaches it through a role-level flag', () => {
+ const role = buildRole({ canReadAllObjectRecords: true });
+ const superset = buildRole({
+ canReadAllObjectRecords: true,
+ objectPermissions: [
+ { objectUniversalIdentifier: PERSON, canReadObjectRecords: false },
+ ],
+ });
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([
+ {
+ type: 'OBJECT_RECORDS',
+ objectUniversalIdentifier: PERSON,
+ action: 'canReadObjectRecords',
+ },
+ ]);
+ });
+
+ it('covers a tool flag through canAccessAllTools and a settings flag through canUpdateAllSettings', () => {
+ const role = buildRole({
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag.AI,
+ SystemPermissionFlag.DATA_MODEL,
+ 'custom-tool-flag',
+ ],
+ });
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset: buildRole({
+ canAccessAllTools: true,
+ canUpdateAllSettings: true,
+ }),
+ toolPermissionFlagUniversalIdentifiers: ['custom-tool-flag'],
+ }),
+ ).toEqual([]);
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset: buildRole({ canAccessAllTools: true }),
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([
+ {
+ type: 'PERMISSION_FLAG',
+ permissionFlagUniversalIdentifier: SystemPermissionFlag.DATA_MODEL,
+ },
+ {
+ type: 'PERMISSION_FLAG',
+ permissionFlagUniversalIdentifier: 'custom-tool-flag',
+ },
+ ]);
+ });
+
+ it('reports a field the superset restricts while the role reads it', () => {
+ const role = buildRole({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: PERSON,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ },
+ ],
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: PERSON,
+ fieldUniversalIdentifier: EMAIL_FIELD,
+ canUpdateFieldValue: false,
+ },
+ ],
+ });
+ const superset = buildRole({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: PERSON,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ },
+ ],
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: PERSON,
+ fieldUniversalIdentifier: EMAIL_FIELD,
+ canReadFieldValue: false,
+ canUpdateFieldValue: false,
+ },
+ ],
+ });
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([
+ {
+ type: 'FIELD_VALUE',
+ objectUniversalIdentifier: PERSON,
+ fieldUniversalIdentifier: EMAIL_FIELD,
+ action: 'canReadFieldValue',
+ },
+ ]);
+ });
+
+ describe('row-level restrictions', () => {
+ const readablePerson = {
+ objectUniversalIdentifier: PERSON,
+ canReadObjectRecords: true,
+ };
+
+ const buildRestrictedRole = ({
+ universalIdentifier,
+ operand,
+ logicalOperator = RowLevelPermissionPredicateGroupLogicalOperator.AND,
+ value,
+ }: {
+ universalIdentifier: string;
+ operand: RowLevelPermissionPredicateOperand;
+ logicalOperator?: RowLevelPermissionPredicateGroupLogicalOperator;
+ value?: string;
+ }) =>
+ buildRole({
+ universalIdentifier,
+ objectPermissions: [readablePerson],
+ rowLevelPermissionPredicateGroups: [
+ {
+ universalIdentifier: `${universalIdentifier}-group`,
+ objectUniversalIdentifier: PERSON,
+ logicalOperator,
+ },
+ ],
+ rowLevelPermissionPredicates: [
+ {
+ universalIdentifier: `${universalIdentifier}-predicate`,
+ objectUniversalIdentifier: PERSON,
+ fieldUniversalIdentifier: EMAIL_FIELD,
+ operand,
+ value,
+ predicateGroupUniversalIdentifier: `${universalIdentifier}-group`,
+ },
+ ],
+ });
+
+ const superset = buildRestrictedRole({
+ universalIdentifier: 'superset',
+ operand: RowLevelPermissionPredicateOperand.IS_NOT_EMPTY,
+ });
+
+ it('reports an object the superset narrows while the role reaches it unnarrowed', () => {
+ const role = buildRole({ objectPermissions: [readablePerson] });
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([
+ { type: 'ROW_LEVEL_RESTRICTION', objectUniversalIdentifier: PERSON },
+ ]);
+ });
+
+ it('accepts the same restriction under different identifiers', () => {
+ const role = buildRestrictedRole({
+ universalIdentifier: 'role',
+ operand: RowLevelPermissionPredicateOperand.IS_NOT_EMPTY,
+ });
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([]);
+ });
+
+ it('reports a restriction that differs by operand or value', () => {
+ const differentOperand = buildRestrictedRole({
+ universalIdentifier: 'role',
+ operand: RowLevelPermissionPredicateOperand.IS_EMPTY,
+ });
+ const differentValue = buildRestrictedRole({
+ universalIdentifier: 'role',
+ operand: RowLevelPermissionPredicateOperand.IS_NOT_EMPTY,
+ value: 'x',
+ });
+
+ for (const role of [differentOperand, differentValue]) {
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([
+ { type: 'ROW_LEVEL_RESTRICTION', objectUniversalIdentifier: PERSON },
+ ]);
+ }
+ });
+
+ it('reports a restriction whose group nests differently', () => {
+ const role = buildRestrictedRole({
+ universalIdentifier: 'role',
+ operand: RowLevelPermissionPredicateOperand.IS_NOT_EMPTY,
+ logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator.OR,
+ });
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([
+ { type: 'ROW_LEVEL_RESTRICTION', objectUniversalIdentifier: PERSON },
+ ]);
+ });
+
+ it('accepts a role that narrows an object the superset leaves open', () => {
+ const role = buildRestrictedRole({
+ universalIdentifier: 'role',
+ operand: RowLevelPermissionPredicateOperand.IS_NOT_EMPTY,
+ });
+
+ expect(
+ getRoleManifestGrantsNotCoveredBy({
+ role,
+ superset: buildRole({ objectPermissions: [readablePerson] }),
+ toolPermissionFlagUniversalIdentifiers: [],
+ }),
+ ).toEqual([]);
+ });
+ });
+});
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index 492ed153f11..a4e3555417b 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -175,6 +175,8 @@ export type { OAuthConnectionProviderConfig } from './oauthConnectionProviderCon
export type { OAuthProviderTokenRequestContentType } from './oauthProviderTokenRequestContentType.type';
export type { ObjectFieldManifest } from './objectFieldManifest.type';
export type { ObjectManifest } from './objectManifestType';
+export type { ObjectPermissionAction } from './objectPermissionActionType';
+export { OBJECT_PERMISSION_ACTIONS } from './objectPermissionActionType';
export type {
PageLayoutWidgetManifest,
StandalonePageLayoutWidgetManifest,
@@ -187,6 +189,7 @@ export type {
} from './permissionFlagManifestType';
export type { PostInstallLogicFunctionApplicationManifest } from './postInstallLogicFunctionApplicationType';
export type { PreInstallLogicFunctionApplicationManifest } from './preInstallLogicFunctionApplicationType';
+export type { RoleManifestGrant } from './roleManifestGrantType';
export type {
ObjectPermissionManifest,
FieldPermissionManifest,
@@ -233,6 +236,13 @@ export {
serializeApplicationVariableValue,
deserializeApplicationVariableValue,
} from './utils/applicationVariableValueSerialization';
+export type { EffectiveObjectPermissions } from './utils/getEffectiveObjectPermissionsFromRoleManifest';
+export {
+ ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION,
+ getEffectiveObjectPermissionsFromRoleManifest,
+} from './utils/getEffectiveObjectPermissionsFromRoleManifest';
+export { getRoleManifestGrantsNotCoveredBy } from './utils/getRoleManifestGrantsNotCoveredBy';
+export { getRowLevelRestrictionSignature } from './utils/getRowLevelRestrictionSignature';
export {
RESERVED_SETTINGS_MENU_ITEM_TITLES,
isReservedSettingsMenuItemTitle,
diff --git a/packages/twenty-shared/src/application/objectPermissionActionType.ts b/packages/twenty-shared/src/application/objectPermissionActionType.ts
new file mode 100644
index 00000000000..fd3a1663d3b
--- /dev/null
+++ b/packages/twenty-shared/src/application/objectPermissionActionType.ts
@@ -0,0 +1,8 @@
+export const OBJECT_PERMISSION_ACTIONS = [
+ 'canReadObjectRecords',
+ 'canUpdateObjectRecords',
+ 'canSoftDeleteObjectRecords',
+ 'canDestroyObjectRecords',
+] as const;
+
+export type ObjectPermissionAction = (typeof OBJECT_PERMISSION_ACTIONS)[number];
diff --git a/packages/twenty-shared/src/application/roleManifestGrantType.ts b/packages/twenty-shared/src/application/roleManifestGrantType.ts
new file mode 100644
index 00000000000..ec660e914e5
--- /dev/null
+++ b/packages/twenty-shared/src/application/roleManifestGrantType.ts
@@ -0,0 +1,32 @@
+import { type ObjectPermissionAction } from '@/application/objectPermissionActionType';
+
+export type RoleManifestGrant =
+ | {
+ type: 'ALL_OBJECT_RECORDS';
+ action: ObjectPermissionAction;
+ }
+ | {
+ type: 'ALL_SETTINGS';
+ }
+ | {
+ type: 'ALL_TOOLS';
+ }
+ | {
+ type: 'PERMISSION_FLAG';
+ permissionFlagUniversalIdentifier: string;
+ }
+ | {
+ type: 'OBJECT_RECORDS';
+ objectUniversalIdentifier: string;
+ action: ObjectPermissionAction;
+ }
+ | {
+ type: 'FIELD_VALUE';
+ objectUniversalIdentifier: string;
+ fieldUniversalIdentifier: string;
+ action: 'canReadFieldValue' | 'canUpdateFieldValue';
+ }
+ | {
+ type: 'ROW_LEVEL_RESTRICTION';
+ objectUniversalIdentifier: string;
+ };
diff --git a/packages/twenty-shared/src/application/utils/getEffectiveObjectPermissionsFromRoleManifest.ts b/packages/twenty-shared/src/application/utils/getEffectiveObjectPermissionsFromRoleManifest.ts
new file mode 100644
index 00000000000..22b2ec20a9f
--- /dev/null
+++ b/packages/twenty-shared/src/application/utils/getEffectiveObjectPermissionsFromRoleManifest.ts
@@ -0,0 +1,52 @@
+import { type ObjectPermissionAction } from '@/application/objectPermissionActionType';
+import { type RoleManifest } from '@/application/roleManifestType';
+
+export type EffectiveObjectPermissions = Record<
+ ObjectPermissionAction,
+ boolean
+>;
+
+export const ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION = {
+ canReadObjectRecords: 'canReadAllObjectRecords',
+ canUpdateObjectRecords: 'canUpdateAllObjectRecords',
+ canSoftDeleteObjectRecords: 'canSoftDeleteAllObjectRecords',
+ canDestroyObjectRecords: 'canDestroyAllObjectRecords',
+} as const satisfies Record<ObjectPermissionAction, keyof RoleManifest>;
+
+export const getEffectiveObjectPermissionsFromRoleManifest = ({
+ role,
+ objectUniversalIdentifier,
+}: {
+ role: RoleManifest;
+ objectUniversalIdentifier: string;
+}): EffectiveObjectPermissions => {
+ const objectPermission = role.objectPermissions?.find(
+ (permission) =>
+ permission.objectUniversalIdentifier === objectUniversalIdentifier,
+ );
+
+ return {
+ canReadObjectRecords:
+ objectPermission?.canReadObjectRecords ??
+ role[ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION.canReadObjectRecords] ??
+ false,
+ canUpdateObjectRecords:
+ objectPermission?.canUpdateObjectRecords ??
+ role[
+ ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION.canUpdateObjectRecords
+ ] ??
+ false,
+ canSoftDeleteObjectRecords:
+ objectPermission?.canSoftDeleteObjectRecords ??
+ role[
+ ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION.canSoftDeleteObjectRecords
+ ] ??
+ false,
+ canDestroyObjectRecords:
+ objectPermission?.canDestroyObjectRecords ??
+ role[
+ ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION.canDestroyObjectRecords
+ ] ??
+ false,
+ };
+};
diff --git a/packages/twenty-shared/src/application/utils/getRoleManifestGrantsNotCoveredBy.ts b/packages/twenty-shared/src/application/utils/getRoleManifestGrantsNotCoveredBy.ts
new file mode 100644
index 00000000000..6c9b5520964
--- /dev/null
+++ b/packages/twenty-shared/src/application/utils/getRoleManifestGrantsNotCoveredBy.ts
@@ -0,0 +1,227 @@
+import { OBJECT_PERMISSION_ACTIONS } from '@/application/objectPermissionActionType';
+import { type RoleManifestGrant } from '@/application/roleManifestGrantType';
+import { type RoleManifest } from '@/application/roleManifestType';
+import {
+ getEffectiveObjectPermissionsFromRoleManifest,
+ ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION,
+} from '@/application/utils/getEffectiveObjectPermissionsFromRoleManifest';
+import { getRowLevelRestrictionSignature } from '@/application/utils/getRowLevelRestrictionSignature';
+import { SystemPermissionFlag } from '@/constants/SystemPermissionFlag';
+import { TOOL_PERMISSION_FLAGS } from '@/constants/ToolPermissionFlags';
+
+const SYSTEM_TOOL_PERMISSION_FLAG_UNIVERSAL_IDENTIFIERS =
+ TOOL_PERMISSION_FLAGS.map((flag) => SystemPermissionFlag[flag]);
+
+const haveSameRowLevelRestriction = ({
+ roleSignature,
+ supersetSignature,
+}: {
+ roleSignature: string[];
+ supersetSignature: string[];
+}): boolean =>
+ roleSignature.length === supersetSignature.length &&
+ roleSignature.every(
+ (predicateSignature, index) =>
+ predicateSignature === supersetSignature[index],
+ );
+
+const getRoleLevelGrantsNotCoveredBy = ({
+ role,
+ superset,
+}: {
+ role: RoleManifest;
+ superset: RoleManifest;
+}): RoleManifestGrant[] => [
+ ...OBJECT_PERMISSION_ACTIONS.filter((action) => {
+ const roleLevelFlag = ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION[action];
+
+ return role[roleLevelFlag] && !superset[roleLevelFlag];
+ }).map<RoleManifestGrant>((action) => ({
+ type: 'ALL_OBJECT_RECORDS',
+ action,
+ })),
+ ...(role.canUpdateAllSettings && !superset.canUpdateAllSettings
+ ? [{ type: 'ALL_SETTINGS' } as const]
+ : []),
+ ...(role.canAccessAllTools && !superset.canAccessAllTools
+ ? [{ type: 'ALL_TOOLS' } as const]
+ : []),
+];
+
+const getPermissionFlagGrantsNotCoveredBy = ({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers,
+}: {
+ role: RoleManifest;
+ superset: RoleManifest;
+ toolPermissionFlagUniversalIdentifiers: string[];
+}): RoleManifestGrant[] => {
+ const toolFlagUniversalIdentifiers = new Set([
+ ...SYSTEM_TOOL_PERMISSION_FLAG_UNIVERSAL_IDENTIFIERS,
+ ...toolPermissionFlagUniversalIdentifiers,
+ ]);
+ const supersetFlagUniversalIdentifiers = new Set(
+ superset.permissionFlagUniversalIdentifiers ?? [],
+ );
+
+ return [...new Set(role.permissionFlagUniversalIdentifiers ?? [])]
+ .filter((permissionFlagUniversalIdentifier) => {
+ const isCoveredByRoleLevelFlag = toolFlagUniversalIdentifiers.has(
+ permissionFlagUniversalIdentifier,
+ )
+ ? superset.canAccessAllTools
+ : superset.canUpdateAllSettings;
+
+ return (
+ !isCoveredByRoleLevelFlag &&
+ !supersetFlagUniversalIdentifiers.has(permissionFlagUniversalIdentifier)
+ );
+ })
+ .map((permissionFlagUniversalIdentifier) => ({
+ type: 'PERMISSION_FLAG',
+ permissionFlagUniversalIdentifier,
+ }));
+};
+
+const getObjectGrantsNotCoveredBy = ({
+ role,
+ superset,
+}: {
+ role: RoleManifest;
+ superset: RoleManifest;
+}): RoleManifestGrant[] => {
+ const objectUniversalIdentifiers = new Set([
+ ...[
+ ...(role.objectPermissions ?? []),
+ ...(superset.objectPermissions ?? []),
+ ].map((permission) => permission.objectUniversalIdentifier),
+ ...(superset.rowLevelPermissionPredicates ?? []).map(
+ (predicate) => predicate.objectUniversalIdentifier,
+ ),
+ ]);
+
+ return [...objectUniversalIdentifiers].flatMap(
+ (objectUniversalIdentifier): RoleManifestGrant[] => {
+ const roleEffectivePermissions =
+ getEffectiveObjectPermissionsFromRoleManifest({
+ role,
+ objectUniversalIdentifier,
+ });
+ const supersetEffectivePermissions =
+ getEffectiveObjectPermissionsFromRoleManifest({
+ role: superset,
+ objectUniversalIdentifier,
+ });
+
+ const objectRecordGrants = OBJECT_PERMISSION_ACTIONS.filter(
+ (action) =>
+ roleEffectivePermissions[action] &&
+ !supersetEffectivePermissions[action],
+ ).map<RoleManifestGrant>((action) => ({
+ type: 'OBJECT_RECORDS',
+ objectUniversalIdentifier,
+ action,
+ }));
+
+ const roleReachesObject = OBJECT_PERMISSION_ACTIONS.some(
+ (action) => roleEffectivePermissions[action],
+ );
+ const supersetSignature = getRowLevelRestrictionSignature({
+ role: superset,
+ objectUniversalIdentifier,
+ });
+ const roleSignature = getRowLevelRestrictionSignature({
+ role,
+ objectUniversalIdentifier,
+ });
+
+ const escapesRowLevelRestriction =
+ roleReachesObject &&
+ supersetSignature.length > 0 &&
+ !haveSameRowLevelRestriction({ roleSignature, supersetSignature });
+
+ return escapesRowLevelRestriction
+ ? [
+ ...objectRecordGrants,
+ { type: 'ROW_LEVEL_RESTRICTION', objectUniversalIdentifier },
+ ]
+ : objectRecordGrants;
+ },
+ );
+};
+
+const getFieldGrantsNotCoveredBy = ({
+ role,
+ superset,
+}: {
+ role: RoleManifest;
+ superset: RoleManifest;
+}): RoleManifestGrant[] =>
+ (superset.fieldPermissions ?? []).flatMap(
+ (supersetFieldPermission): RoleManifestGrant[] => {
+ const { objectUniversalIdentifier, fieldUniversalIdentifier } =
+ supersetFieldPermission;
+ const roleEffectivePermissions =
+ getEffectiveObjectPermissionsFromRoleManifest({
+ role,
+ objectUniversalIdentifier,
+ });
+ const roleFieldPermission = role.fieldPermissions?.find(
+ (permission) =>
+ permission.objectUniversalIdentifier === objectUniversalIdentifier &&
+ permission.fieldUniversalIdentifier === fieldUniversalIdentifier,
+ );
+
+ const escapesReadRestriction =
+ supersetFieldPermission.canReadFieldValue === false &&
+ roleEffectivePermissions.canReadObjectRecords &&
+ roleFieldPermission?.canReadFieldValue !== false;
+ const escapesUpdateRestriction =
+ supersetFieldPermission.canUpdateFieldValue === false &&
+ roleEffectivePermissions.canUpdateObjectRecords &&
+ roleFieldPermission?.canUpdateFieldValue !== false;
+
+ return [
+ ...(escapesReadRestriction
+ ? ([
+ {
+ type: 'FIELD_VALUE',
+ objectUniversalIdentifier,
+ fieldUniversalIdentifier,
+ action: 'canReadFieldValue',
+ },
+ ] as const)
+ : []),
+ ...(escapesUpdateRestriction
+ ? ([
+ {
+ type: 'FIELD_VALUE',
+ objectUniversalIdentifier,
+ fieldUniversalIdentifier,
+ action: 'canUpdateFieldValue',
+ },
+ ] as const)
+ : []),
+ ];
+ },
+ );
+
+export const getRoleManifestGrantsNotCoveredBy = ({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers,
+}: {
+ role: RoleManifest;
+ superset: RoleManifest;
+ toolPermissionFlagUniversalIdentifiers: string[];
+}): RoleManifestGrant[] => [
+ ...getRoleLevelGrantsNotCoveredBy({ role, superset }),
+ ...getPermissionFlagGrantsNotCoveredBy({
+ role,
+ superset,
+ toolPermissionFlagUniversalIdentifiers,
+ }),
+ ...getObjectGrantsNotCoveredBy({ role, superset }),
+ ...getFieldGrantsNotCoveredBy({ role, superset }),
+];
diff --git a/packages/twenty-shared/src/application/utils/getRowLevelRestrictionSignature.ts b/packages/twenty-shared/src/application/utils/getRowLevelRestrictionSignature.ts
new file mode 100644
index 00000000000..1c563e28e25
--- /dev/null
+++ b/packages/twenty-shared/src/application/utils/getRowLevelRestrictionSignature.ts
@@ -0,0 +1,92 @@
+import {
+ type RoleManifest,
+ type RowLevelPermissionPredicateGroupManifest,
+} from '@/application/roleManifestType';
+import { isPlainObject } from '@/utils/typeguard/isPlainObject';
+import { isDefined } from '@/utils/validation/isDefined';
+
+const stringifyWithSortedKeys = (value: unknown): string =>
+ JSON.stringify(value, (_key, nestedValue) =>
+ isPlainObject(nestedValue)
+ ? Object.fromEntries(
+ Object.entries(nestedValue).sort(([leftKey], [rightKey]) =>
+ leftKey.localeCompare(rightKey),
+ ),
+ )
+ : nestedValue,
+ );
+
+const getGroupOperatorPath = ({
+ groupsByUniversalIdentifier,
+ predicateGroupUniversalIdentifier,
+}: {
+ groupsByUniversalIdentifier: Map<
+ string,
+ RowLevelPermissionPredicateGroupManifest
+ >;
+ predicateGroupUniversalIdentifier: string | null | undefined;
+}): string[] => {
+ const operatorPath: string[] = [];
+ const visitedGroupUniversalIdentifiers = new Set<string>();
+ let currentGroupUniversalIdentifier = predicateGroupUniversalIdentifier;
+
+ while (
+ isDefined(currentGroupUniversalIdentifier) &&
+ !visitedGroupUniversalIdentifiers.has(currentGroupUniversalIdentifier)
+ ) {
+ visitedGroupUniversalIdentifiers.add(currentGroupUniversalIdentifier);
+
+ const group = groupsByUniversalIdentifier.get(
+ currentGroupUniversalIdentifier,
+ );
+
+ if (!isDefined(group)) {
+ break;
+ }
+
+ operatorPath.push(group.logicalOperator);
+ currentGroupUniversalIdentifier =
+ group.parentPredicateGroupUniversalIdentifier;
+ }
+
+ return operatorPath;
+};
+
+export const getRowLevelRestrictionSignature = ({
+ role,
+ objectUniversalIdentifier,
+}: {
+ role: RoleManifest;
+ objectUniversalIdentifier: string;
+}): string[] => {
+ const groupsByUniversalIdentifier = new Map(
+ (role.rowLevelPermissionPredicateGroups ?? []).map((group) => [
+ group.universalIdentifier,
+ group,
+ ]),
+ );
+
+ return (role.rowLevelPermissionPredicates ?? [])
+ .filter(
+ (predicate) =>
+ predicate.objectUniversalIdentifier === objectUniversalIdentifier,
+ )
+ .map((predicate) =>
+ stringifyWithSortedKeys({
+ fieldUniversalIdentifier: predicate.fieldUniversalIdentifier,
+ subFieldName: predicate.subFieldName ?? null,
+ operand: predicate.operand,
+ value: predicate.value ?? null,
+ workspaceMemberFieldUniversalIdentifier:
+ predicate.workspaceMemberFieldUniversalIdentifier ?? null,
+ workspaceMemberSubFieldName:
+ predicate.workspaceMemberSubFieldName ?? null,
+ groupOperatorPath: getGroupOperatorPath({
+ groupsByUniversalIdentifier,
+ predicateGroupUniversalIdentifier:
+ predicate.predicateGroupUniversalIdentifier,
+ }),
+ }),
+ )
+ .sort();
+};
diff --git a/packages/twenty-shared/src/constants/ToolPermissionFlags.ts b/packages/twenty-shared/src/constants/ToolPermissionFlags.ts
new file mode 100644
index 00000000000..6600d03fdf1
--- /dev/null
+++ b/packages/twenty-shared/src/constants/ToolPermissionFlags.ts
@@ -0,0 +1,16 @@
+import { PermissionFlagType } from './PermissionFlagType';
+
+export const TOOL_PERMISSION_FLAGS: readonly PermissionFlagType[] = [
+ PermissionFlagType.AI,
+ PermissionFlagType.VIEWS,
+ PermissionFlagType.UPLOAD_FILE,
+ PermissionFlagType.DOWNLOAD_FILE,
+ PermissionFlagType.SEND_EMAIL_TOOL,
+ PermissionFlagType.CREATE_CALENDAR_EVENT_TOOL,
+ PermissionFlagType.HTTP_REQUEST_TOOL,
+ PermissionFlagType.IMPORT_CSV,
+ PermissionFlagType.EXPORT_CSV,
+ PermissionFlagType.CONNECTED_ACCOUNTS,
+ PermissionFlagType.PROFILE_INFORMATION,
+ PermissionFlagType.CODE_INTERPRETER_TOOL,
+];
diff --git a/packages/twenty-shared/src/constants/index.ts b/packages/twenty-shared/src/constants/index.ts
index 60461c4c65f..ed86b42846a 100644
--- a/packages/twenty-shared/src/constants/index.ts
+++ b/packages/twenty-shared/src/constants/index.ts
@@ -77,6 +77,7 @@ export { STANDARD_OBJECT_RECORDS_UNDER_OBJECT_RECORDS_PERMISSIONS } from './Stan
export { SUBDOMAIN_PATTERN } from './SubdomainPattern';
export { SystemPermissionFlag } from './SystemPermissionFlag';
export { TAG_COLORS } from './TagColors';
+export { TOOL_PERMISSION_FLAGS } from './ToolPermissionFlags';
export { TWENTY_COMPANIES_BASE_URL } from './TwentyCompaniesBaseUrl';
export { TWENTY_ICONS_BASE_URL } from './TwentyIconsBaseUrl';
export { UI_SCALE_VALUES } from './UiScaleValues';