Files
twenty/packages/twenty-server/test/integration/metadata/suites/role/failing-role-update.integration-spec.ts
T
Félix Malfait 012d819557 OAuth Client — Unified ApplicationRegistration, OAuth server, and frontend (#18267)
## Summary

Consolidates three separate PRs (#18260, #18261, #18262) into a single
unified branch with all review feedback addressed:

### New features
- **ApplicationRegistration entity** — server-level registration for
OAuth apps with encrypted server variables
- **OAuth 2.0 server** — authorization code, client credentials, refresh
token grants with PKCE support
- **OAuth discovery endpoint** —
`.well-known/oauth-authorization-server` metadata
- **Frontend UI** — app registration details page with credential
management, redirect URI editing, and server variable configuration
- **CLI integration** — `twenty dev` auto-registers apps and stores
OAuth credentials locally
- **Authorize consent screen** — OAuth consent page at `/authorize`
showing requested scopes

### Review feedback addressed

**Renames (PR #18260):**
- `appRegistration` → `applicationRegistration` (entity, tables, files,
imports, GraphQL types)
- `appRegistrationVariable` → `applicationRegistrationVariable`
- `clientId` → `oAuthClientId`, `clientSecretHash` →
`oAuthClientSecretHash`, `redirectUris` → `oAuthRedirectUris`, `scopes`
→ `oAuthScopes`

**Security fixes (PR #18261):**
- Fixed redirect URI validation bypass when `oAuthRedirectUris` is an
empty array
- Fixed workspace isolation in `clientCredentialsGrant` — now uses
`find()` with explicit handling for multiple installations
- Added error logging in refresh token `catch` block instead of silently
swallowing

**Code quality (PR #18262):**
- Split `VersionDistributionEntry` into its own file (one export per
file)
- Split GraphQL queries and mutations into individual files with a
shared fragment
- Removed unused `OAuth` entry from `AuthProviderEnum`
- Added loading state to `handleRotateSecret`
- Removed 27 narration-style comments from test files
- Added proper guards (`PublicEndpointGuard`, `NoPermissionGuard`) to
controllers and resolvers

## Test plan

- [ ] Verify `twenty dev` registers an app and stores OAuth credentials
- [ ] Test OAuth authorization code flow end-to-end (authorize → token →
API call)
- [ ] Test client credentials grant
- [ ] Verify redirect URI validation rejects requests when no URIs are
registered
- [ ] Verify app registration detail page renders correctly
- [ ] Test secret rotation with loading state
- [ ] Verify server variable editing and saving
- [ ] Run `npx nx database:reset twenty-server` to validate migration

Closes #18260, #18261, #18262


Made with [Cursor](https://cursor.com)

---------

Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
2026-02-28 14:07:49 +01:00

272 lines
7.6 KiB
TypeScript

import { faker } from '@faker-js/faker';
import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';
import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';
import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';
import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
import { updateOneRole } from 'test/integration/metadata/suites/role/utils/update-one-role.util';
import {
eachTestingContextFilter,
type EachTestingContext,
} from 'twenty-shared/testing';
import { type UpdateRolePayload } from 'src/engine/metadata-modules/role/dtos/update-role.input';
type TestContext = {
input: (testSetup: TestSetup) => {
idToUpdate: string;
updatePayload: UpdateRolePayload;
};
};
type TestSetup = {
testRoleId: string;
existingRoleLabelForDuplicate: string;
nonEditableRoleId: string;
};
type GlobalTestContext = {
existingRoleLabelForDuplicate: string;
nonEditableRoleId: string;
};
const globalTestContext: GlobalTestContext = {
existingRoleLabelForDuplicate: 'Existing Role For Duplicate Test',
nonEditableRoleId: '',
};
type UpdateOneRoleTestingContext = EachTestingContext<TestContext>[];
describe('Role update should fail', () => {
let testRoleId: string;
let existingRoleIdForDuplicate: string;
beforeAll(async () => {
// Get a non-editable system role (Admin) for testing
const adminRole = await findOneRoleByLabel({ label: 'Admin' });
globalTestContext.nonEditableRoleId = adminRole.id;
// Create a role that will be used to test duplicate label validation
const { data: duplicateData } = await createOneRole({
expectToFail: false,
input: {
label: globalTestContext.existingRoleLabelForDuplicate,
canUpdateAllSettings: false,
canAccessAllTools: false,
canReadAllObjectRecords: true,
canUpdateAllObjectRecords: false,
canSoftDeleteAllObjectRecords: false,
canDestroyAllObjectRecords: false,
},
});
existingRoleIdForDuplicate = duplicateData.createOneRole.id;
});
beforeEach(async () => {
// Create a role for each test
const { data } = await createOneRole({
expectToFail: false,
input: {
label: 'Test Role To Update',
description: 'Original description',
icon: 'IconSettings',
canUpdateAllSettings: false,
canAccessAllTools: false,
canReadAllObjectRecords: true,
canUpdateAllObjectRecords: false,
canSoftDeleteAllObjectRecords: false,
canDestroyAllObjectRecords: false,
canBeAssignedToUsers: true,
canBeAssignedToAgents: false,
canBeAssignedToApiKeys: false,
},
});
testRoleId = data.createOneRole.id;
});
afterEach(async () => {
await deleteOneRole({
expectToFail: false,
input: { idToDelete: testRoleId },
});
});
afterAll(async () => {
await deleteOneRole({
expectToFail: false,
input: { idToDelete: existingRoleIdForDuplicate },
});
});
describe('updating role with existing write permissions', () => {
let roleWithWritePermissionsId: string;
beforeEach(async () => {
// Create a role with read=true and write=true
const { data } = await createOneRole({
expectToFail: false,
input: {
label: 'Role With Write Permissions',
description: 'Role with write permissions for update tests',
canUpdateAllSettings: false,
canAccessAllTools: false,
canReadAllObjectRecords: true,
canUpdateAllObjectRecords: true,
canSoftDeleteAllObjectRecords: true,
canDestroyAllObjectRecords: true,
},
});
roleWithWritePermissionsId = data.createOneRole.id;
});
afterEach(async () => {
await deleteOneRole({
expectToFail: false,
input: { idToDelete: roleWithWritePermissionsId },
});
});
it('should fail when updating only canReadAllObjectRecords to false while role has existing write permissions', async () => {
const { errors } = await updateOneRole({
expectToFail: true,
input: {
idToUpdate: roleWithWritePermissionsId,
updatePayload: {
canReadAllObjectRecords: false,
},
},
});
expectOneNotInternalServerErrorSnapshot({
errors,
});
});
});
const failingRoleUpdateTestCases: UpdateOneRoleTestingContext = [
{
title: 'when updating label to one that already exists',
context: {
input: (testSetup) => ({
idToUpdate: testSetup.testRoleId,
updatePayload: {
label: testSetup.existingRoleLabelForDuplicate,
},
}),
},
},
{
title: 'when updating a non-editable system role',
context: {
input: (testSetup) => ({
idToUpdate: testSetup.nonEditableRoleId,
updatePayload: {
label: 'new role label',
},
}),
},
},
// Read/Write permissions consistency tests
{
title:
'when updating canReadAllObjectRecords to false while canUpdateAllObjectRecords is true',
context: {
input: (testSetup) => ({
idToUpdate: testSetup.testRoleId,
updatePayload: {
canReadAllObjectRecords: false,
canUpdateAllObjectRecords: true,
},
}),
},
},
{
title:
'when updating canReadAllObjectRecords to false while canSoftDeleteAllObjectRecords is true',
context: {
input: (testSetup) => ({
idToUpdate: testSetup.testRoleId,
updatePayload: {
canReadAllObjectRecords: false,
canSoftDeleteAllObjectRecords: true,
},
}),
},
},
{
title:
'when updating canReadAllObjectRecords to false while canDestroyAllObjectRecords is true',
context: {
input: (testSetup) => ({
idToUpdate: testSetup.testRoleId,
updatePayload: {
canReadAllObjectRecords: false,
canDestroyAllObjectRecords: true,
},
}),
},
},
{
title:
'when updating to enable write permissions without read permission',
context: {
input: (testSetup) => ({
idToUpdate: testSetup.testRoleId,
updatePayload: {
canReadAllObjectRecords: false,
canUpdateAllObjectRecords: true,
canSoftDeleteAllObjectRecords: true,
},
}),
},
},
];
it.each(eachTestingContextFilter(failingRoleUpdateTestCases))(
'$title',
async ({ context }) => {
const testSetup: TestSetup = {
testRoleId,
existingRoleLabelForDuplicate:
globalTestContext.existingRoleLabelForDuplicate,
nonEditableRoleId: globalTestContext.nonEditableRoleId,
};
const { idToUpdate, updatePayload } = context.input(testSetup);
const { errors } = await updateOneRole({
expectToFail: true,
input: {
idToUpdate,
updatePayload,
},
});
expectOneNotInternalServerErrorSnapshot({
errors,
});
},
);
it('should fail when updating a non-existent role', async () => {
const nonExistentRoleId = faker.string.uuid();
const { errors } = await updateOneRole({
expectToFail: true,
input: {
idToUpdate: nonExistentRoleId,
updatePayload: {
label: 'Updated Label',
},
},
});
expectOneNotInternalServerErrorSnapshot({
errors,
});
});
});