fix(role): rebind API keys + agents before deleting their role (#20935)

## Customer-reported bug

A customer hit this when using the AI chat:

```json
{
  "message": "API key 760d4822-da40-4b3f-9031-40563d7ed6c9 has no role assigned",
  "extensions": {
    "code": "INTERNAL_SERVER_ERROR",
    "userFriendlyMessage": "This API key has no role assigned."
  }
}
```

Their integration authenticates via API key. Somewhere along the way,
the role bound to that API key was deleted, leaving the API key
authenticated but role-less. Any request that hits a permission check
(`getRoleIdForApiKeyId`) blows up.

## Root cause

In `RoleService.deleteManyRoles`, the pre-deletion cleanup
(`assignDefaultRoleToMembersWithRoleToDelete`) only rebinds **user
workspaces** to the workspace default role. API keys and agents pointing
at the role are ignored. Because `RoleTargetEntity.role` declares
`onDelete: 'CASCADE'`, the FK then drops the role_target rows for those
API keys / agents — but the API keys themselves stay in `api_key`, now
orphaned in `apiKeyRoleMap`.

A previous read-side workaround
([2767ddac44](https://github.com/twentyhq/twenty/commit/2767ddac44) —
make the `role` ResolveField nullable) handled the API-key-details page,
but did not address the write paths (`getRoleIdForApiKeyId`).

## Fix

- Rename `assignDefaultRoleToMembersWithRoleToDelete` →
`rebindTargetsOfRoleToDeleteToDefaultRole` and extend it to rebind API
keys (via `ApiKeyRoleService.assignRoleToApiKey`) and agents (via
`AiAgentRoleService.assignRoleToAgent`) in the same step, before the
role is deleted.
- If the workspace default role doesn't satisfy `canBeAssignedToApiKeys`
/ `canBeAssignedToAgents`, the inner `assignRoleTo*` validation throws.
We catch that and rethrow as a `PermissionsException` with a
role-deletion-context message and two new codes —
`ROLE_CANNOT_BE_ASSIGNED_TO_API_KEYS` /
`ROLE_CANNOT_BE_ASSIGNED_TO_AGENTS` — so the admin sees a clear
"reassign these first" prompt rather than a confusing inner error.

## Scope / non-goals

- **Already-orphaned API keys are not auto-healed.** The customer still
needs to reassign a role to their existing orphan API key via the UI
(Settings > API Keys > [the key] > role). A separate cleanup command for
existing orphans is a follow-up.
- I did not investigate *why* the customer's session was authenticated
via API key in the AI chat — that may be their integration setup. Worth
confirming with them separately.

## Test plan

- [ ] Workspace with default role `Admin` (which has
`canBeAssignedToApiKeys: true`): create an API key with a custom role,
delete the custom role → API key is rebound to Admin, requests keep
working.
- [ ] Workspace with default role `Member` (default, has
`canBeAssignedToApiKeys: false`): create an API key with a custom role,
delete the custom role → role deletion fails with the new
`ROLE_CANNOT_BE_ASSIGNED_TO_API_KEYS` error explaining the admin must
reassign first. API key + custom role are both unchanged.
- [ ] Same two scenarios for agents (`canBeAssignedToAgents`).
- [ ] Existing user-workspace rebind behavior is unchanged.
- [ ] Role deletion with no dependent API keys / agents still works.
This commit is contained in:
Félix Malfait
2026-05-27 10:54:02 +02:00
committed by GitHub
parent ac89d2ff56
commit 8cb88cabee
6 changed files with 158 additions and 5 deletions
@@ -1,6 +1,6 @@
import { settingsDraftRoleFamilyState } from '@/settings/roles/states/settingsDraftRoleFamilyState';
import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';
import { t } from '@lingui/core/macro';
import { plural, t } from '@lingui/core/macro';
type SettingsRoleSettingsDeleteRoleConfirmationModalSubtitleProps = {
roleId: string;
@@ -14,8 +14,51 @@ export const SettingsRoleSettingsDeleteRoleConfirmationModalSubtitle = ({
roleId,
);
const roleName = settingsDraftRole.label;
const memberCount = settingsDraftRole.workspaceMembers.length;
const apiKeyCount = settingsDraftRole.apiKeys.length;
const agentCount = settingsDraftRole.agents.length;
const segments: string[] = [];
if (memberCount > 0) {
segments.push(
plural(memberCount, {
one: `${memberCount} member`,
other: `${memberCount} members`,
}),
);
}
if (apiKeyCount > 0) {
segments.push(
plural(apiKeyCount, {
one: `${apiKeyCount} API key`,
other: `${apiKeyCount} API keys`,
}),
);
}
if (agentCount > 0) {
segments.push(
plural(agentCount, {
one: `${agentCount} agent`,
other: `${agentCount} agents`,
}),
);
}
if (segments.length === 0) {
return (
<>{t`Confirm deletion of ${roleName} role? This cannot be undone.`}</>
);
}
const reassignSubject =
segments.length === 1
? segments[0]
: `${segments.slice(0, -1).join(', ')} ${t`and`} ${segments.at(-1)}`;
return (
<>{t`Confirm deletion of ${roleName} role? This cannot be undone. All members will be reassigned to the default role.`}</>
<>{t`Confirm deletion of ${roleName} role? This cannot be undone. ${reassignSubject} will be reassigned to the default role.`}</>
);
};