Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(server): a project role name is unique per platform (#15705)

lina-alomari9f5faea35935
diff --git a/brain/knowledge/platform-editions-ee/ee-projects-rbac.md b/brain/knowledge/platform-editions-ee/ee-projects-rbac.md
index ff4d35ffd19..a7505bee25b 100644
--- a/brain/knowledge/platform-editions-ee/ee-projects-rbac.md
+++ b/brain/knowledge/platform-editions-ee/ee-projects-rbac.md
@@ -26,6 +26,7 @@ Note it lives under `ee/authentication/`, not `ee/projects/`, which is where mos
- **`rbacMiddleware` only covers HTTP routes. Websocket events bypass it.** A socket is authorized once at connect, against the project it claims in the handshake. After that, every resource id arriving in an event payload is just whatever the client typed, and nothing re-checks it. So a socket handler must look the resource up scoped to the connection's project and check the permission itself. Getting this wrong is how `LOCK_RESOURCE` and `JOIN_PRESENCE` shipped letting any member lock, and read the editors of, another project's flows and tables (SRE-218). `collaborative-resource.ts` has the shape to copy.
- **A new `Permission` needs a row in the role grid, or custom roles can never grant it.** The resource-to-permission mapping is a hardcoded array, `groups()` in `packages/web/src/features/members/lib/role-permissions.ts` (it lived inline in `project-role-dialog.tsx` as `initialPermissions` until the Roles & access rebuild), and the grid is a plain `.map()` over it. Default-role grants are hardcoded separately in `access-control-list.ts`, so a permission added there but not here is invisible: ADMIN/EDITOR/VIEWER have it, custom roles cannot be given it, and the feature's tab just never appears for those members. This has already shipped three times — Variables + Knowledge Base (GIT-1751), then Agents, and `PUBLISH_SENSITIVE_FLOW_ACCESS` is missing right now: the grid is **29 of the 30 `Permission` values**, which is why its counter reads "N of 29", and flow-approval rights stay Admin-only. `packages/web/test/features/members/lib/role-permissions.test.ts` now catches the drift — it asserts `PUBLISH_SENSITIVE_FLOW_ACCESS` is the *only* `Permission` absent from the grid, so adding an enum value without a row fails that test.
- **The release diff and the release apply have to share one rule, or a field becomes either invisible or permanently dirty.** `flowDiffService` decides whether a flow changed by comparing a `normalize()`d copy of each side, and `projectStateHelper.updateFlowInProject` decides what actually gets written — two places, and for connection auth they disagreed both ways. `normalize()` blanked `input.auth` before comparing, so re-pointing a step at a different connection and changing nothing else was reported `flowsUnchanged` and never applied, while the connection the release created sat unreferenced at status `MISSING`; and when some other edit did make the diff fire, the apply unconditionally restored the destination's old auth on top of the incoming one (`f196530db6`, Jul 2024 secret preservation that predates externalId placeholders). Patching the two sites separately is the trap: it leaves a destination-has-auth / incoming-has-none step reporting changed on **every** apply forever, because the diff and the apply then hold different ideas of what unchanged means. The fix (GIT-1764) is one exported `mergeDestinationAuth` that both call, so the diff compares the merged incoming version — exactly what apply is about to write. Any future field with "keep the destination's value" semantics wants the same shape. Worth knowing while reading this code: `flowStructureUtil.transferFlow` deep-clones before the callback runs, so mutating `step` inside it never touches the caller's state; connection references persist as the literal `{{connections['<externalId>']}}`, identical in both projects, which is why comparing them across instances is meaningful at all; and `flowVersionService` recomputes `connectionIds` via `extractConnectionIds` on every mutation, so the version tracks the new reference without anyone updating it by hand.
+- **A project role is deleted by name, so two roles sharing one name lose both.** `DELETE /v1/project-roles/:name` resolves to `repo.delete({ name, platformId })`, which matches every row with that name, and `project_member.projectRole` cascades on `projectRoleId`. `create()` always refused a duplicate, `update()` did not, so renaming B to A was enough to reach that state, and it happened on a dev database without anyone trying. Closed by a unique index on `("platformId", LOWER("name"))` for platform-owned roles, with `getOne` already comparing `LOWER(name)` so the index matches the rule the API enforces. The upgrade renames existing duplicates rather than deleting them: the copy with the most members keeps the name, creation time breaks ties, the rest take the first free ` (2)`, ` (3)` suffix. There is no marker distinguishing a generated name from a chosen one, so `SELECT id, name FROM project_role WHERE name LIKE '% (%)'` lists candidates, not confirmed renames.
- **Piece filtering** now via **piece sets** — `project.pieceSetId` (nullable FK, SET NULL). When `managePiecesEnabled`, new EE projects get the Default set on create; unassigned resolves to Default at filter time. This supersedes the legacy project-plan allow/block list.
- **Worker routing**: `workerGroupId` (bare label, `^[a-z0-9_-]+$`) gated by `workerGroupsEnabled`. When set, the project's `EXECUTE_FLOW`/`EXECUTE_WEBHOOK` jobs route to `project-<label>-jobs`; other job types unaffected. Set via `POST /v1/projects/:id`; `GET /v1/projects/worker-groups` (platform-admin) lists online project-scope workers, 402 when flag off.
- `platformProjectService.getForPlatform()`: admins see all, operators see all except others' personal, users see own personal + team projects they're a member of.
diff --git a/packages/server/api/src/app/core/db/unique-violation.ts b/packages/server/api/src/app/core/db/unique-violation.ts
new file mode 100644
index 00000000000..ca3b4e8f4d1
--- /dev/null
+++ b/packages/server/api/src/app/core/db/unique-violation.ts
@@ -0,0 +1,16 @@
+import { QueryFailedError } from 'typeorm'
+
+export function isUniqueViolation(error: unknown): boolean {
+ if (!(error instanceof QueryFailedError)) {
+ return false
+ }
+ const driverError: unknown = error.driverError
+ return (
+ typeof driverError === 'object' &&
+ driverError !== null &&
+ 'code' in driverError &&
+ driverError.code === POSTGRES_UNIQUE_VIOLATION
+ )
+}
+
+const POSTGRES_UNIQUE_VIOLATION = '23505'
diff --git a/packages/server/api/src/app/database/migration/postgres/1852000000000-UniqueProjectRoleNamePerPlatform.ts b/packages/server/api/src/app/database/migration/postgres/1852000000000-UniqueProjectRoleNamePerPlatform.ts
new file mode 100644
index 00000000000..7682c03f0da
--- /dev/null
+++ b/packages/server/api/src/app/database/migration/postgres/1852000000000-UniqueProjectRoleNamePerPlatform.ts
@@ -0,0 +1,64 @@
+import { QueryRunner } from 'typeorm'
+import { Migration } from '../../migration'
+
+export class UniqueProjectRoleNamePerPlatform1852000000000 implements Migration {
+ name = 'UniqueProjectRoleNamePerPlatform1852000000000'
+ breaking = false
+ release = '0.92.0'
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`
+ WITH ranked AS (
+ SELECT pr."id", pr."platformId", pr."name", LOWER(pr."name") AS lower_name, pr."created",
+ (SELECT COUNT(*) FROM "project_member" pm WHERE pm."projectRoleId" = pr."id") AS member_count
+ FROM "project_role" pr
+ WHERE pr."platformId" IS NOT NULL
+ ),
+ targets AS (
+ SELECT "id", "platformId", "name", lower_name,
+ ROW_NUMBER() OVER (
+ PARTITION BY "platformId", lower_name
+ ORDER BY member_count DESC, "created", "id"
+ ) - 1 AS slot
+ FROM ranked
+ ),
+ dupe_groups AS (
+ SELECT DISTINCT loser."platformId", loser.lower_name, keeper."name" AS base
+ FROM targets loser
+ JOIN targets keeper
+ ON keeper."platformId" = loser."platformId"
+ AND keeper.lower_name = loser.lower_name
+ AND keeper.slot = 0
+ WHERE loser.slot > 0
+ ),
+ free AS (
+ SELECT d."platformId", d.lower_name, d.base, g.n,
+ ROW_NUMBER() OVER (PARTITION BY d."platformId", d.lower_name ORDER BY g.n) AS slot
+ FROM dupe_groups d
+ CROSS JOIN generate_series(2, (SELECT 2 * COUNT(*) + 2 FROM "project_role")) AS g(n)
+ WHERE NOT EXISTS (
+ SELECT 1 FROM "project_role" e
+ WHERE e."platformId" = d."platformId"
+ AND LOWER(e."name") = LOWER(d.base || ' (' || g.n || ')')
+ )
+ )
+ UPDATE "project_role" r
+ SET "name" = f.base || ' (' || f.n || ')'
+ FROM targets t
+ JOIN free f
+ ON f."platformId" = t."platformId" AND f.lower_name = t.lower_name AND f.slot = t.slot
+ WHERE r."id" = t."id" AND t.slot > 0
+ `)
+ await queryRunner.query(`
+ CREATE UNIQUE INDEX "idx_project_role_platform_id_name"
+ ON "project_role" ("platformId", LOWER("name"))
+ WHERE "platformId" IS NOT NULL
+ `)
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`
+ DROP INDEX IF EXISTS "idx_project_role_platform_id_name"
+ `)
+ }
+}
diff --git a/packages/server/api/src/app/database/postgres-connection.ts b/packages/server/api/src/app/database/postgres-connection.ts
index 4ce9bc834ea..ef4639141ad 100644
--- a/packages/server/api/src/app/database/postgres-connection.ts
+++ b/packages/server/api/src/app/database/postgres-connection.ts
@@ -442,6 +442,7 @@ import { NullOrphanFolderReferences1846000000000 } from './migration/postgres/18
import { IndexWaitpointLookups1847000000000 } from './migration/postgres/1847000000000-IndexWaitpointLookups'
import { AddAgentConversationAiCredits1850000000000 } from './migration/postgres/1850000000000-AddAgentConversationAiCredits'
import { AddMcpOAuthCodeNonce1851000000000 } from './migration/postgres/1851000000000-AddMcpOAuthCodeNonce'
+import { UniqueProjectRoleNamePerPlatform1852000000000 } from './migration/postgres/1852000000000-UniqueProjectRoleNamePerPlatform'
import { FlowExternalIdUniqueIgnoresDeleting1855000000000 } from './migration/postgres/1855000000000-FlowExternalIdUniqueIgnoresDeleting'
import { AddFlowTombstoneIndex1856000000000 } from './migration/postgres/1856000000000-AddFlowTombstoneIndex'
import { AddWaitpointDeadLetteredAt1857000000000 } from './migration/postgres/1857000000000-AddWaitpointDeadLetteredAt'
@@ -902,6 +903,7 @@ export const getMigrations = (): (new () => Migration)[] => {
IndexWaitpointLookups1847000000000,
AddAgentConversationAiCredits1850000000000,
AddMcpOAuthCodeNonce1851000000000,
+ UniqueProjectRoleNamePerPlatform1852000000000,
FlowExternalIdUniqueIgnoresDeleting1855000000000,
AddFlowTombstoneIndex1856000000000,
AddWaitpointDeadLetteredAt1857000000000,
diff --git a/packages/server/api/src/app/ee/pieces/piece-set/piece-set.service.ts b/packages/server/api/src/app/ee/pieces/piece-set/piece-set.service.ts
index a8389a37d70..cbba6d32e11 100644
--- a/packages/server/api/src/app/ee/pieces/piece-set/piece-set.service.ts
+++ b/packages/server/api/src/app/ee/pieces/piece-set/piece-set.service.ts
@@ -1,9 +1,10 @@
import { ActivepiecesError, apId, ErrorCode, isNil, kebabCase, SeekPage, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
import { CreatePieceSetRequestBody, PieceSet, PieceSetConfig, UpdatePieceSetRequestBody } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
-import { EntityManager, In, QueryFailedError } from 'typeorm'
+import { EntityManager, In } from 'typeorm'
import { repoFactory } from '../../../core/db/repo-factory'
import { transaction } from '../../../core/db/transaction'
+import { isUniqueViolation } from '../../../core/db/unique-violation'
import { distributedLock } from '../../../database/redis-connections'
import { buildPaginator } from '../../../helper/pagination/build-paginator'
import { paginationHelper } from '../../../helper/pagination/pagination-utils'
@@ -220,8 +221,7 @@ function resolveKey({ key, name }: { key?: string | null, name: string }): strin
}
function rethrowKeyConflict(error: unknown): never {
- const driverError: unknown = error instanceof QueryFailedError ? error.driverError : undefined
- if (typeof driverError === 'object' && driverError !== null && 'code' in driverError && driverError.code === '23505') {
+ if (isUniqueViolation(error)) {
throw new ActivepiecesError({
code: ErrorCode.VALIDATION,
params: { message: 'Piece set key already used' },
diff --git a/packages/server/api/src/app/ee/projects/project-role/project-role.entity.ts b/packages/server/api/src/app/ee/projects/project-role/project-role.entity.ts
index 71c76df74be..e4918575436 100644
--- a/packages/server/api/src/app/ee/projects/project-role/project-role.entity.ts
+++ b/packages/server/api/src/app/ee/projects/project-role/project-role.entity.ts
@@ -12,6 +12,15 @@ export type ProjectRoleSchema = ProjectRole & {
export const ProjectRoleEntity = new EntitySchema<ProjectRoleSchema>({
name: 'project_role',
+ indices: [
+ {
+ name: 'idx_project_role_platform_id_name',
+ columns: ['platformId', 'name'],
+ unique: true,
+ where: '"platformId" IS NOT NULL',
+ synchronize: false,
+ },
+ ],
columns: {
...BaseColumnSchemaPart,
name: {
diff --git a/packages/server/api/src/app/ee/projects/project-role/project-role.service.ts b/packages/server/api/src/app/ee/projects/project-role/project-role.service.ts
index 346680f99c1..b09c8f5b6a0 100644
--- a/packages/server/api/src/app/ee/projects/project-role/project-role.service.ts
+++ b/packages/server/api/src/app/ee/projects/project-role/project-role.service.ts
@@ -1,7 +1,8 @@
-import { ActivepiecesError, apId, ApId, ErrorCode, isNil, PlatformId, ProjectRole, RoleType, SeekPage, spreadIfDefined } from '@activepieces/core-utils'
+import { ActivepiecesError, apId, ApId, ErrorCode, isNil, PlatformId, ProjectRole, RoleType, SeekPage, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
import { CreateProjectRoleRequestBody } from '@activepieces/shared'
import { Brackets, Equal } from 'typeorm'
import { repoFactory } from '../../../core/db/repo-factory'
+import { isUniqueViolation } from '../../../core/db/unique-violation'
import { ProjectMemberEntity } from '../project-members/project-member.entity'
import { ProjectRoleEntity } from './project-role.entity'
@@ -74,27 +75,38 @@ export const projectRoleService = {
platformId,
})
if (projectRoleExists) {
- throw new ActivepiecesError({
- code: ErrorCode.ENTITY_NOT_FOUND,
- params: { entityType: 'project_role', entityId: params.name, message: 'Project Role name already exists' },
- })
+ throw nameAlreadyExists(params.name)
}
- return projectRoleRepo().save({
- id: apId(),
+ const id = apId()
+ const { error } = await tryCatch(() => projectRoleRepo().save({
+ id,
platformId,
...params,
- })
+ }))
+ if (error) {
+ rethrowNameConflict({ error, name: params.name })
+ }
+ return projectRoleRepo().findOneByOrFail({ id })
},
async update(params: UpdateParams): Promise<ProjectRole> {
- await projectRoleRepo().update({
+ if (!isNil(params.name)) {
+ const existing = await this.getOne({ name: params.name, platformId: params.platformId })
+ if (!isNil(existing) && existing.id !== params.id) {
+ throw nameAlreadyExists(params.name)
+ }
+ }
+ const { error } = await tryCatch(() => projectRoleRepo().update({
id: params.id,
platformId: params.platformId,
}, {
...spreadIfDefined('name', params.name),
...spreadIfDefined('permissions', params.permissions),
- })
+ }))
+ if (error) {
+ rethrowNameConflict({ error, name: params.name })
+ }
return projectRoleRepo().findOneByOrFail({ id: params.id, platformId: params.platformId })
},
@@ -103,6 +115,25 @@ export const projectRoleService = {
},
}
+function nameAlreadyExists(name: string | undefined): ActivepiecesError {
+ return new ActivepiecesError({
+ code: ErrorCode.VALIDATION,
+ params: { message: `Project role name already exists: ${name}` },
+ })
+}
+
+function rethrowNameConflict({ error, name }: RethrowNameConflictParams): never {
+ if (isUniqueViolation(error)) {
+ throw nameAlreadyExists(name)
+ }
+ throw error
+}
+
+type RethrowNameConflictParams = {
+ error: unknown
+ name: string | undefined
+}
+
type UpdateParams = {
id: ApId
name: string | undefined
diff --git a/packages/server/api/src/app/variable/variable.service.ts b/packages/server/api/src/app/variable/variable.service.ts
index efa92843172..24bd30dd44b 100644
--- a/packages/server/api/src/app/variable/variable.service.ts
+++ b/packages/server/api/src/app/variable/variable.service.ts
@@ -1,8 +1,9 @@
import { ActivepiecesError, ApId, apId, Cursor, ErrorCode, isNil, Metadata, PlatformId, ProjectId, SeekPage, spreadIfDefined, UserId } from '@activepieces/core-utils'
import { AppConnectionOwners, Variable, VariableWithoutSensitiveData } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
-import { Equal, ILike, QueryFailedError } from 'typeorm'
+import { Equal, ILike } from 'typeorm'
import { repoFactory } from '../core/db/repo-factory'
+import { isUniqueViolation } from '../core/db/unique-violation'
import { encryptUtils } from '../helper/encryption'
import { buildPaginator } from '../helper/pagination/build-paginator'
import { paginationHelper } from '../helper/pagination/pagination-utils'
@@ -158,21 +159,6 @@ async function getOneOrThrowWithoutValue(params: GetOneParams): Promise<Variable
return stripSensitiveData(row)
}
-const POSTGRES_UNIQUE_VIOLATION = '23505'
-
-function isUniqueViolation(error: unknown): boolean {
- if (!(error instanceof QueryFailedError)) {
- return false
- }
- const driverError: unknown = error.driverError
- return (
- typeof driverError === 'object' &&
- driverError !== null &&
- 'code' in driverError &&
- driverError.code === POSTGRES_UNIQUE_VIOLATION
- )
-}
-
function stripSensitiveData(row: VariableSchema): VariableWithoutSensitiveData {
return {
id: row.id,
diff --git a/packages/server/api/test/integration/ce/database/unique-project-role-name.test.ts b/packages/server/api/test/integration/ce/database/unique-project-role-name.test.ts
new file mode 100644
index 00000000000..ef7c3a66f90
--- /dev/null
+++ b/packages/server/api/test/integration/ce/database/unique-project-role-name.test.ts
@@ -0,0 +1,127 @@
+import { DataSource } from 'typeorm'
+import { createMockProjectMember, mockAndSaveBasicSetup } from '../../../helpers/mocks'
+import { initializeDatabase } from '../../../../src/app/database'
+import { databaseConnection, resetDatabaseConnection } from '../../../../src/app/database/database-connection'
+import { UniqueProjectRoleNamePerPlatform1852000000000 } from '../../../../src/app/database/migration/postgres/1852000000000-UniqueProjectRoleNamePerPlatform'
+
+const INDEX_NAME = 'idx_project_role_platform_id_name'
+const ID_PREFIX = 'zzMig'
+const PLATFORM_A = id('platformA')
+const PLATFORM_B = id('platformB')
+const PLATFORM_C = id('platformC')
+
+function id(seed: string): string {
+ return `${ID_PREFIX}${seed}`.padEnd(21, '0').slice(0, 21)
+}
+
+async function seedRole(ds: DataSource, params: { seed: string, platformId: string | null, name: string, created: string }): Promise<void> {
+ await ds.query(
+ 'INSERT INTO "project_role" ("id", "created", "updated", "name", "permissions", "platformId", "type") VALUES ($1, $2, $2, $3, $4, $5, $6)',
+ [id(params.seed), params.created, params.name, [], params.platformId, 'CUSTOM'],
+ )
+}
+
+async function nameOf(ds: DataSource, seed: string): Promise<string> {
+ const [row] = await ds.query('SELECT "name" FROM "project_role" WHERE "id" = $1', [id(seed)])
+ return row.name
+}
+
+async function runMigration(ds: DataSource): Promise<void> {
+ const queryRunner = ds.createQueryRunner()
+ await queryRunner.connect()
+ await new UniqueProjectRoleNamePerPlatform1852000000000().up(queryRunner)
+ await queryRunner.release()
+}
+
+async function cleanup(ds: DataSource): Promise<void> {
+ await ds.query(`DELETE FROM "project_member" WHERE "projectRoleId" LIKE '${ID_PREFIX}%'`)
+ await ds.query(`DELETE FROM "project_role" WHERE "id" LIKE '${ID_PREFIX}%'`)
+}
+
+describe('UniqueProjectRoleNamePerPlatform migration', () => {
+ let ds: DataSource
+
+ beforeAll(async () => {
+ resetDatabaseConnection()
+ await initializeDatabase({ runMigrations: true })
+ ds = databaseConnection()
+ })
+
+ afterAll(async () => {
+ await cleanup(ds)
+ await ds.destroy()
+ })
+
+ beforeEach(async () => {
+ await cleanup(ds)
+ await ds.query(`DROP INDEX IF EXISTS "${INDEX_NAME}"`)
+ })
+
+ it('keeps one copy and suffixes the rest, treating case variants as the same name', async () => {
+ await seedRole(ds, { seed: 'caseA', platformId: PLATFORM_A, name: 'Manager', created: '2024-01-01T00:00:00Z' })
+ await seedRole(ds, { seed: 'caseB', platformId: PLATFORM_A, name: 'manager', created: '2024-01-02T00:00:00Z' })
+ await seedRole(ds, { seed: 'caseC', platformId: PLATFORM_A, name: 'MANAGER', created: '2024-01-03T00:00:00Z' })
+
+ await runMigration(ds)
+
+ expect(await nameOf(ds, 'caseA')).toBe('Manager')
+ const renamed = [await nameOf(ds, 'caseB'), await nameOf(ds, 'caseC')]
+ expect(renamed.sort()).toEqual(['Manager (2)', 'Manager (3)'])
+ })
+
+ it('walks past a suffix already taken in another capitalisation', async () => {
+ await seedRole(ds, { seed: 'takenA', platformId: PLATFORM_B, name: 'Editor', created: '2024-01-01T00:00:00Z' })
+ await seedRole(ds, { seed: 'takenB', platformId: PLATFORM_B, name: 'Editor', created: '2024-01-02T00:00:00Z' })
+ await seedRole(ds, { seed: 'takenC', platformId: PLATFORM_B, name: 'EDITOR (2)', created: '2024-01-03T00:00:00Z' })
+
+ await runMigration(ds)
+
+ expect(await nameOf(ds, 'takenA')).toBe('Editor')
+ expect(await nameOf(ds, 'takenB')).toBe('Editor (3)')
+ expect(await nameOf(ds, 'takenC')).toBe('EDITOR (2)')
+ })
+
+ it('leaves the same name on another platform, and platform-less rows, alone', async () => {
+ await seedRole(ds, { seed: 'otherA', platformId: PLATFORM_A, name: 'Manager', created: '2024-01-01T00:00:00Z' })
+ await seedRole(ds, { seed: 'otherB', platformId: PLATFORM_C, name: 'Manager', created: '2024-01-01T00:00:00Z' })
+ await seedRole(ds, { seed: 'globalA', platformId: null, name: 'Viewer', created: '2024-01-01T00:00:00Z' })
+ await seedRole(ds, { seed: 'globalB', platformId: null, name: 'viewer', created: '2024-01-02T00:00:00Z' })
+
+ await runMigration(ds)
+
+ expect(await nameOf(ds, 'otherA')).toBe('Manager')
+ expect(await nameOf(ds, 'otherB')).toBe('Manager')
+ expect(await nameOf(ds, 'globalA')).toBe('Viewer')
+ expect(await nameOf(ds, 'globalB')).toBe('viewer')
+ })
+
+ it('keeps the name on the copy with the most members, not the oldest', async () => {
+ const { mockPlatform, mockProject, mockOwner } = await mockAndSaveBasicSetup()
+
+ await seedRole(ds, { seed: 'tieOld', platformId: mockPlatform.id, name: 'Manager', created: '2024-01-01T00:00:00Z' })
+ await seedRole(ds, { seed: 'tieNew', platformId: mockPlatform.id, name: 'Manager', created: '2024-06-01T00:00:00Z' })
+
+ const member = createMockProjectMember({
+ projectId: mockProject.id,
+ userId: mockOwner.id,
+ platformId: mockPlatform.id,
+ projectRoleId: id('tieNew'),
+ })
+ await ds.getRepository('project_member').save(member)
+
+ await runMigration(ds)
+
+ expect(await nameOf(ds, 'tieNew')).toBe('Manager')
+ expect(await nameOf(ds, 'tieOld')).toBe('Manager (2)')
+ })
+
+ it('builds an index that then rejects a case variant on the same platform', async () => {
+ await seedRole(ds, { seed: 'idxA', platformId: PLATFORM_A, name: 'Manager', created: '2024-01-01T00:00:00Z' })
+
+ await runMigration(ds)
+
+ await expect(
+ seedRole(ds, { seed: 'idxB', platformId: PLATFORM_A, name: 'MANAGER', created: '2024-02-01T00:00:00Z' }),
+ ).rejects.toThrow()
+ })
+})
diff --git a/packages/server/api/test/integration/cloud/project-role/project-role.test.ts b/packages/server/api/test/integration/cloud/project-role/project-role.test.ts
index ce0ae2ee67b..622f721a2e0 100644
--- a/packages/server/api/test/integration/cloud/project-role/project-role.test.ts
+++ b/packages/server/api/test/integration/cloud/project-role/project-role.test.ts
@@ -110,6 +110,50 @@ describe('Project Role API', () => {
expect(response?.statusCode).toBe(StatusCodes.OK)
})
+ it('should refuse a rename onto a name another role already holds', async () => {
+ const ctx = await createTestContext(app!)
+
+ const taken = createMockProjectRole({ platformId: ctx.platform.id })
+ const renamed = createMockProjectRole({ platformId: ctx.platform.id })
+ await db.save('project_role', taken)
+ await db.save('project_role', renamed)
+
+ const request: UpdateProjectRoleRequestBody = { name: taken.name }
+ const response = await ctx.post(`/v1/project-roles/${renamed.id}`, request as unknown as Record<string, unknown>)
+
+ expect(response?.statusCode).toBe(StatusCodes.CONFLICT)
+ const stillThere = await db.findOneBy('project_role', { id: renamed.id }) as ProjectRole | null
+ expect(stillThere?.name).toBe(renamed.name)
+ })
+
+ it('should refuse a rename that differs from a taken name only by case', async () => {
+ const ctx = await createTestContext(app!)
+
+ const taken = createMockProjectRole({ platformId: ctx.platform.id, name: 'Manager' })
+ const renamed = createMockProjectRole({ platformId: ctx.platform.id, name: 'Engineer' })
+ await db.save('project_role', taken)
+ await db.save('project_role', renamed)
+
+ const request: UpdateProjectRoleRequestBody = { name: 'MANAGER' }
+ const response = await ctx.post(`/v1/project-roles/${renamed.id}`, request as unknown as Record<string, unknown>)
+
+ expect(response?.statusCode).toBe(StatusCodes.CONFLICT)
+ const stillThere = await db.findOneBy('project_role', { id: renamed.id }) as ProjectRole | null
+ expect(stillThere?.name).toBe(renamed.name)
+ })
+
+ it('should allow saving a role under the name it already has', async () => {
+ const ctx = await createTestContext(app!)
+
+ const projectRole = createMockProjectRole({ platformId: ctx.platform.id })
+ await db.save('project_role', projectRole)
+
+ const request: UpdateProjectRoleRequestBody = { name: projectRole.name, permissions: ['read'] }
+ const response = await ctx.post(`/v1/project-roles/${projectRole.id}`, request as unknown as Record<string, unknown>)
+
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ })
+
it('should fail to update if user is not platform owner', async () => {
const { mockPlatform } = await mockAndSaveBasicSetup()
const { mockUser } = await mockBasicUser({