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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(connections): add a dedicated permission for replacing connections (#16846)
Abdul00b95e5495ca
diff --git a/brain/knowledge/platform-editions-ee/ee-projects-rbac.md b/brain/knowledge/platform-editions-ee/ee-projects-rbac.mdindex 1964bdf7c19..720f1cff8dc 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- **A Member can't be removed from their last project** from the members table: `removeFromProject` refuses with `LAST_PROJECT` (409) when it's their only project on the platform, counting a personal project. Admins and Operators are never blocked, since they see every project. SCIM group changes call `projectMemberService.delete` and are deliberately not guarded, so the identity provider stays the source of truth. API-key calls skip the guard too (`enforceLastProjectGuard`, and the members list's `isLastProject` flag, are only set for a USER principal): embedding customers remove users through the API, and an embedded user is almost always in exactly one project, so the guard would break their offboarding. The no-projects screen is the fallback.- **`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.+- **If a permission needs another permission to work, the role permission dialog must turn both on together.** Otherwise a custom role can get the first permission without the second, and the feature it controls is unusable. For example, replacing connections needs read access to connections, so the dialog turns on read access with it, and turns replace off when read access goes off.- **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.diff --git a/packages/core/shared/src/lib/ee/authn/access-control-list.ts b/packages/core/shared/src/lib/ee/authn/access-control-list.tsindex 5b5b986c1bb..1e8061531b5 100644--- a/packages/core/shared/src/lib/ee/authn/access-control-list.ts+++ b/packages/core/shared/src/lib/ee/authn/access-control-list.ts@@ -5,6 +5,7 @@ export const rolePermissions: Record<DefaultProjectRole, Permission[]> = {[DefaultProjectRole.ADMIN]: [Permission.READ_APP_CONNECTION,Permission.WRITE_APP_CONNECTION,+ Permission.REPLACE_APP_CONNECTION,Permission.READ_FLOW,Permission.WRITE_FLOW,Permission.UPDATE_FLOW_STATUS,@@ -37,6 +38,7 @@ export const rolePermissions: Record<DefaultProjectRole, Permission[]> = {[DefaultProjectRole.EDITOR]: [Permission.READ_APP_CONNECTION,Permission.WRITE_APP_CONNECTION,+ Permission.REPLACE_APP_CONNECTION,Permission.READ_FLOW,Permission.WRITE_FLOW,Permission.UPDATE_FLOW_STATUS,diff --git a/packages/core/utils/package.json b/packages/core/utils/package.jsonindex 725edd6b44a..941a7c45e34 100644--- a/packages/core/utils/package.json+++ b/packages/core/utils/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/core-utils",- "version": "0.12.1",+ "version": "0.12.2","type": "commonjs","main": "./dist/src/index.js","scripts": {diff --git a/packages/core/utils/src/lib/permission.ts b/packages/core/utils/src/lib/permission.tsindex 683370e5193..11579ac0613 100644--- a/packages/core/utils/src/lib/permission.ts+++ b/packages/core/utils/src/lib/permission.ts@@ -2,6 +2,7 @@export enum Permission {READ_APP_CONNECTION = 'READ_APP_CONNECTION',WRITE_APP_CONNECTION = 'WRITE_APP_CONNECTION',+ REPLACE_APP_CONNECTION = 'REPLACE_APP_CONNECTION',READ_FLOW = 'READ_FLOW',WRITE_FLOW = 'WRITE_FLOW',UPDATE_FLOW_STATUS = 'UPDATE_FLOW_STATUS',diff --git a/packages/server/api/src/app/app-connection/app-connection.controller.ts b/packages/server/api/src/app/app-connection/app-connection.controller.tsindex a99076809cd..2c0bef73757 100644--- a/packages/server/api/src/app/app-connection/app-connection.controller.ts+++ b/packages/server/api/src/app/app-connection/app-connection.controller.ts@@ -228,7 +228,7 @@ const ReplaceAppConnectionsRequest = {config: {security: securityAccess.project([PrincipalType.USER, PrincipalType.SERVICE],- Permission.WRITE_APP_CONNECTION,+ Permission.REPLACE_APP_CONNECTION,{type: ProjectResourceType.BODY,},diff --git a/packages/server/api/src/app/database/migration/postgres/1879000000000-AddReplaceAppConnectionPermission.ts b/packages/server/api/src/app/database/migration/postgres/1879000000000-AddReplaceAppConnectionPermission.tsnew file mode 100644index 00000000000..b45d7a3a745--- /dev/null+++ b/packages/server/api/src/app/database/migration/postgres/1879000000000-AddReplaceAppConnectionPermission.ts@@ -0,0 +1,25 @@+import { QueryRunner } from 'typeorm'+import { Migration } from '../../migration'++export class AddReplaceAppConnectionPermission1879000000000 implements Migration {+ name = 'AddReplaceAppConnectionPermission1879000000000'+ breaking = false+ release = '0.93.0'+ transaction = true++ public async up(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`+ UPDATE "project_role"+ SET "permissions" = array_append("permissions", 'REPLACE_APP_CONNECTION')+ WHERE 'WRITE_APP_CONNECTION' = ANY("permissions")+ AND NOT 'REPLACE_APP_CONNECTION' = ANY("permissions")+ `)+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`+ UPDATE "project_role"+ SET "permissions" = array_remove("permissions", 'REPLACE_APP_CONNECTION')+ `)+ }+}diff --git a/packages/server/api/src/app/database/postgres-connection.ts b/packages/server/api/src/app/database/postgres-connection.tsindex 1f0d2ea8f75..685fc60064c 100644--- a/packages/server/api/src/app/database/postgres-connection.ts+++ b/packages/server/api/src/app/database/postgres-connection.ts@@ -465,6 +465,7 @@ import { AddDefaultChatModelToPlatformConfiguration1875000000000 } from './migraimport { AddAgentConversationWaitpointId1876000000000 } from './migration/postgres/1876000000000-AddAgentConversationWaitpointId'import { AddIsDefaultToProject1877000000000 } from './migration/postgres/1877000000000-AddIsDefaultToProject'import { AddAiUsageTables1878000000000 } from './migration/postgres/1878000000000-AddAiUsageTables'+import { AddReplaceAppConnectionPermission1879000000000 } from './migration/postgres/1879000000000-AddReplaceAppConnectionPermission'import { AddAgentConversationProviderConfigIdIndex1869000000000 } from './migration/postgres/background/1869000000000-AddAgentConversationProviderConfigIdIndex'import { ReshapeFlowRunListIndexesForBarrierChildren1871000000000 } from './migration/postgres/background/1871000000000-ReshapeFlowRunListIndexesForBarrierChildren'import { BackfillPieceTranslation1874000000000 } from './migration/postgres/background/1874000000000-BackfillPieceTranslation'@@ -957,6 +958,7 @@ export const getMigrations = (): (new () => Migration)[] => {AddAgentConversationWaitpointId1876000000000,AddIsDefaultToProject1877000000000,AddAiUsageTables1878000000000,+ AddReplaceAppConnectionPermission1879000000000,]return migrations}diff --git a/packages/server/api/test/integration/cloud/app-connection/app-connection.test.ts b/packages/server/api/test/integration/cloud/app-connection/app-connection.test.tsindex 1d469a91d02..cc631ca0540 100644--- a/packages/server/api/test/integration/cloud/app-connection/app-connection.test.ts+++ b/packages/server/api/test/integration/cloud/app-connection/app-connection.test.ts@@ -1,3 +1,4 @@+import { apId, Permission, RoleType } from '@activepieces/core-utils'import {AppConnectionType,DefaultProjectRole,@@ -9,9 +10,10 @@ import { pieceMetadataService } from '../../../../src/app/pieces/metadata/piece-import { db } from '../../../helpers/db'import {createMockPieceMetadata,+ createMockProjectRole,} from '../../../helpers/mocks'import { describeRolePermissions } from '../../../helpers/permission-test'-import { createTestContext } from '../../../helpers/test-context'+import { createMemberContext, createTestContext } from '../../../helpers/test-context'import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'let app: FastifyInstance | null = null@@ -107,4 +109,41 @@ describe('AppConnection API', () => {forbiddenRoles: [],})})++ describe('Replace AppConnections endpoint', () => {+ describeRolePermissions({+ app: () => app!,+ request: (memberCtx, ownerCtx) => {+ return memberCtx.post('/v1/app-connections/replace', {+ sourceAppConnectionId: apId(),+ targetAppConnectionId: apId(),+ projectId: ownerCtx.project.id,+ flowIds: [apId()],+ })+ },+ allowedRoles: [DefaultProjectRole.ADMIN, DefaultProjectRole.EDITOR],+ forbiddenRoles: [DefaultProjectRole.VIEWER],+ })++ it('Fails for a custom role that can write connections but not replace them', async () => {+ const ctx = await createTestContext(app!)+ const role = createMockProjectRole({+ platformId: ctx.platform.id,+ name: `custom-${apId()}`,+ permissions: [Permission.READ_APP_CONNECTION, Permission.WRITE_APP_CONNECTION],+ type: RoleType.CUSTOM,+ })+ await db.save('project_role', role)+ const memberCtx = await createMemberContext(app!, ctx, { projectRole: role.name })++ const response = await memberCtx.post('/v1/app-connections/replace', {+ sourceAppConnectionId: apId(),+ targetAppConnectionId: apId(),+ projectId: ctx.project.id,+ flowIds: [apId()],+ })++ expect(response.statusCode).toBe(StatusCodes.FORBIDDEN)+ })+ })})diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex 19ec22d2156..d9a83cd64fe 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -821,6 +821,7 @@"Please select a connection to replace": "Please select a connection to replace","Please select a connection to replace with": "Please select a connection to replace with","Replace connection": "Replace connection",+ "Replace connections": "Replace connections","Review and confirm": "Review and confirm","Switch flows from one connection to another. Choose the connection to replace and the one to use instead.": "Switch flows from one connection to another. Choose the connection to replace and the one to use instead.","Review what changes, then replace.": "Review what changes, then replace.",diff --git a/packages/web/src/app/components/flow-actions-menu.tsx b/packages/web/src/app/components/flow-actions-menu.tsxindex cc3908081a3..fc084c505c6 100644--- a/packages/web/src/app/components/flow-actions-menu.tsx+++ b/packages/web/src/app/components/flow-actions-menu.tsx@@ -106,8 +106,8 @@ const FlowActionMenu: React.FC<FlowActionMenuProps> = ({const { checkAccess } = useAuthorization();const userHasPermissionToWriteFolder = checkAccess(Permission.WRITE_FOLDER);const userHasPermissionToUpdateFlow = checkAccess(Permission.WRITE_FLOW);- const userHasPermissionToWriteAppConnection = checkAccess(- Permission.WRITE_APP_CONNECTION,+ const userHasPermissionToReplaceAppConnection = checkAccess(+ Permission.REPLACE_APP_CONNECTION,);const userHasPermissionToPushToGit = checkAccess(Permission.WRITE_PROJECT_RELEASE,@@ -334,12 +334,12 @@ const FlowActionMenu: React.FC<FlowActionMenuProps> = ({showsDraftOrPublishedVersion &&!embedState.isEmbedded && (<PermissionNeededTooltip- hasPermission={userHasPermissionToWriteAppConnection}+ hasPermission={userHasPermissionToReplaceAppConnection}><ReplaceConnectionForFlowDialog><DropdownMenuItemdisabled={- !userHasPermissionToWriteAppConnection || isFlowLocked+ !userHasPermissionToReplaceAppConnection || isFlowLocked}onSelect={(e) => e.preventDefault()}>diff --git a/packages/web/src/app/routes/connections/index.tsx b/packages/web/src/app/routes/connections/index.tsxindex 48d9b261523..d38cc24a758 100644--- a/packages/web/src/app/routes/connections/index.tsx+++ b/packages/web/src/app/routes/connections/index.tsx@@ -126,6 +126,9 @@ function AppConnectionsPage() {const userHasPermissionToWriteAppConnection = checkAccess(Permission.WRITE_APP_CONNECTION,);+ const userHasPermissionToReplaceAppConnection = checkAccess(+ Permission.REPLACE_APP_CONNECTION,+ );const { data: owners } = appConnectionsQueries.useConnectionsOwners();const filters: DataTableFilters<keyof AppConnectionWithoutSensitiveData>[] =ownerColumnHooks.useOwnerColumnFilter<AppConnectionWithoutSensitiveData>(@@ -391,7 +394,7 @@ function AppConnectionsPage() {() => [<PermissionNeededTooltipkey="replace"- hasPermission={userHasPermissionToWriteAppConnection}+ hasPermission={userHasPermissionToReplaceAppConnection}><ReplaceConnectionForProjectDialogprojectId={projectId}@@ -404,7 +407,7 @@ function AppConnectionsPage() {icon={ReplaceIcon}iconSize={16}variant="outline"- disabled={!userHasPermissionToWriteAppConnection}+ disabled={!userHasPermissionToReplaceAppConnection}>{t('Replace')}</AnimatedIconButton>@@ -432,7 +435,11 @@ function AppConnectionsPage() {</NewConnectionDialog></PermissionNeededTooltip>,],- [userHasPermissionToWriteAppConnection, refresh],+ [+ userHasPermissionToWriteAppConnection,+ userHasPermissionToReplaceAppConnection,+ refresh,+ ],);return (<div className="flex-col w-full">diff --git a/packages/web/src/features/members/lib/role-permissions.ts b/packages/web/src/features/members/lib/role-permissions.tsindex c1a488ccddf..6d0cd3e979c 100644--- a/packages/web/src/features/members/lib/role-permissions.ts+++ b/packages/web/src/features/members/lib/role-permissions.ts@@ -86,6 +86,12 @@ function groups(): PermissionGroup[] {view: Permission.READ_APP_CONNECTION,edit: Permission.WRITE_APP_CONNECTION,},+ {+ key: 'replace-app-connections',+ label: t('Replace connections'),+ edit: Permission.REPLACE_APP_CONNECTION,+ requires: Permission.READ_APP_CONNECTION,+ },{key: 'project-releases',label: t('Project releases'),@@ -171,28 +177,38 @@ function toggleBox({column,checked,}: ToggleBoxParams): string[] {- const next = new Set(permissions);+ const updatedPermissions = new Set(permissions);if (column === 'edit' && row.edit) {if (checked) {- next.add(row.edit);+ updatedPermissions.add(row.edit);if (row.view) {- next.add(row.view);+ updatedPermissions.add(row.view);+ }+ if (row.requires) {+ updatedPermissions.add(row.requires);}} else {- next.delete(row.edit);+ updatedPermissions.delete(row.edit);}}if (column === 'view' && row.view && !row.viewAlwaysOn) {if (checked) {- next.add(row.view);+ updatedPermissions.add(row.view);} else {- next.delete(row.view);+ updatedPermissions.delete(row.view);if (row.edit) {- next.delete(row.edit);+ updatedPermissions.delete(row.edit);}+ allRows()+ .filter((dependentRow) => dependentRow.requires === row.view)+ .forEach((dependentRow) => {+ if (dependentRow.edit) {+ updatedPermissions.delete(dependentRow.edit);+ }+ });}}- return Array.from(next);+ return Array.from(updatedPermissions);}function changedRowKeys({@@ -235,6 +251,7 @@ export type PermissionRow = {view?: Permission;edit?: Permission;viewAlwaysOn?: boolean;+ requires?: Permission;};export type PermissionGroup = {diff --git a/packages/web/test/features/members/lib/role-permissions.test.ts b/packages/web/test/features/members/lib/role-permissions.test.tsindex e28ce66d080..b0351fb75ac 100644--- a/packages/web/test/features/members/lib/role-permissions.test.ts+++ b/packages/web/test/features/members/lib/role-permissions.test.ts@@ -41,6 +41,7 @@ const EXPECTED_MAPPING: [string, Permission | undefined, Permission | undefined]Permission.READ_APP_CONNECTION,Permission.WRITE_APP_CONNECTION,],+ ['replace-app-connections', undefined, Permission.REPLACE_APP_CONNECTION],['project-releases',Permission.READ_PROJECT_RELEASE,@@ -82,8 +83,8 @@ describe('the permission grid mapping', () => {expect(missing).toEqual([Permission.PUBLISH_SENSITIVE_FLOW_ACCESS]);});- it('has 29 boxes, which is what the counter promises', () => {- expect(rolePermissionModel.totalBoxes()).toBe(29);+ it('has 30 boxes, which is what the counter promises', () => {+ expect(rolePermissionModel.totalBoxes()).toBe(30);});it('keeps view permanently on only where a role cannot function without it', () => {@@ -99,7 +100,7 @@ describe('the built-in bases', () => {it.each([['Nothing' as const, [Permission.READ_FLOW, Permission.READ_PROJECT], 2],['Viewer' as const, rolePermissions[DefaultProjectRole.VIEWER], 12],- ['Editor' as const, rolePermissions[DefaultProjectRole.EDITOR], 24],+ ['Editor' as const, rolePermissions[DefaultProjectRole.EDITOR], 25],])('%s seeds the stored set and counts %i', (base, expected, count) => {const permissions = rolePermissionModel.basePermissions({ base });expect(new Set(permissions)).toEqual(new Set(expected));@@ -170,6 +171,35 @@ describe('toggling a box', () => {expect(permissions).toEqual([]);});+ it('turns on connection read access when replace goes on', () => {+ const permissions = rolePermissionModel.toggleBox({+ permissions: [],+ row: row('replace-app-connections'),+ column: 'edit',+ checked: true,+ });+ expect(new Set(permissions)).toEqual(+ new Set([+ Permission.REPLACE_APP_CONNECTION,+ Permission.READ_APP_CONNECTION,+ ]),+ );+ });++ it('clears replace when connection read access goes off', () => {+ const permissions = rolePermissionModel.toggleBox({+ permissions: [+ Permission.READ_APP_CONNECTION,+ Permission.WRITE_APP_CONNECTION,+ Permission.REPLACE_APP_CONNECTION,+ ],+ row: row('app-connections'),+ column: 'view',+ checked: false,+ });+ expect(permissions).toEqual([]);+ });+it('reaches exactly the three states the old None/Read/Write control offered', () => {const tables = row('tables');const none = rolePermissionModel.toggleBox({