From 69f0b2e9b4518d9a2575fef437b369b2a19d7071 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 14:00:31 -0800 Subject: [PATCH 1/3] fix(scim): scope the managed-membership lock to workspaces the member's directory groups map The lock refused every manual workspace grant for directory-provisioned members, including workspaces no group mapping reaches, so they could never be shared into new workspaces. It now owns org membership and role, plus workspace access that reconciliation itself sets through the member's mapped groups, derived from the same mapping rows and rules. --- .../docs/platform/enterprise/scim/index.mdx | 4 +- .../docs/platform/enterprise/scim/okta.mdx | 2 +- .../workspaces/[id]/permissions/route.test.ts | 16 +- apps/sim/ee/scim/components/options.ts | 2 +- apps/sim/ee/scim/lib/managed-membership.ts | 61 ++++- .../ee/scim/lib/projection/mapping-rows.ts | 27 +++ .../ee/scim/lib/projection/reconcile-user.ts | 27 +-- .../scim-locked-invitations.integration.ts | 210 ++++++++++++++++++ apps/sim/lib/invitations/direct-grant.ts | 7 +- .../lib/invitations/workspace-invitations.ts | 50 +++-- .../__integration__/members.integration.ts | 27 ++- .../permissions/management-store.ts | 16 +- 12 files changed, 383 insertions(+), 66 deletions(-) create mode 100644 apps/sim/ee/scim/lib/projection/mapping-rows.ts create mode 100644 apps/sim/lib/invitations/__integration__/scim-locked-invitations.integration.ts diff --git a/apps/docs/content/docs/platform/enterprise/scim/index.mdx b/apps/docs/content/docs/platform/enterprise/scim/index.mdx index 0882bc06595..3aeed9e3c1e 100644 --- a/apps/docs/content/docs/platform/enterprise/scim/index.mdx +++ b/apps/docs/content/docs/platform/enterprise/scim/index.mdx @@ -170,13 +170,13 @@ Sim tracks grants made through directory mappings. Removing a member from a grou Other directory mappings and independent access can still keep the person in a workspace. Removing a permission-group membership changes their governing policy; it does not remove workspace access. Sim then uses another applicable workspace policy, the organization default, or no permission-group restrictions if neither exists. An empty mapped group applies to nobody and never turns into an all-members policy. Verify both workspace access and the fallback policy when testing a removal. -**Lock managed membership** is enabled by default on a new connection. It makes the directory authoritative for provisioned members: Sim refuses manual invitations, workspace grants, workspace role changes, and organization role changes for them. Manual access already held when a mapping begins covering it becomes directory-managed and is withdrawn with that mapping. Administrators can still remove access in an emergency. +**Lock managed membership** is enabled by default on a new connection. It makes the directory authoritative for provisioned members: Sim refuses manual organization invitations and organization role changes for them, and manual grants and role changes on any workspace one of their groups is mapped to. Other workspace access stays shareable by hand, since the directory does not manage it. To have the directory own a member's access to a workspace, map one of their groups to it. Manual access already held when a mapping begins covering it becomes directory-managed and is withdrawn with that mapping. Administrators can still remove access in an emergency. The lock does not prevent editing permission-group membership directly in Sim. A manual removal can be restored by reconciliation, and a manual addition to an overlapping policy can block a directory assignment. Manage mapped policy membership through the directory and check **Group mappings** for unassigned members after resolving conflicts. With locking off, prior manual workspace access is preserved. If a member had manual Read access and a directory mapping raises it to Admin, removing the mapping restores Read. A role manually raised above the directory's level also remains. [Older grants have a baseline limitation](#deployment-and-upgrades). -You can manually invite people the directory does not manage. For managed members with locking on, grant access through directory groups. +You can manually invite people the directory does not manage. For managed members with locking on, change access to workspaces their groups are mapped to through the directory; share other workspaces with them as usual. ## Provisioning and SSO together diff --git a/apps/docs/content/docs/platform/enterprise/scim/okta.mdx b/apps/docs/content/docs/platform/enterprise/scim/okta.mdx index 92bf74946e9..a5f16ef5a9e 100644 --- a/apps/docs/content/docs/platform/enterprise/scim/okta.mdx +++ b/apps/docs/content/docs/platform/enterprise/scim/okta.mdx @@ -118,7 +118,7 @@ For example, use `Sim users` to assign the app and `Finance` as the pushed group Header Auth Test App Group Push selecting an engineering group and Create Group for the downstream group -With **Lock managed membership** enabled, Sim blocks manual invitations and grants for provisioned members. Read [How access is withdrawn](/platform/enterprise/scim#how-access-is-withdrawn) before mapping groups that overlap existing manual access. +With **Lock managed membership** enabled, Sim blocks manual grants for provisioned members on workspaces their groups are mapped to. Read [How access is withdrawn](/platform/enterprise/scim#how-access-is-withdrawn) before mapping groups that overlap existing manual access. ## Rotate a token diff --git a/apps/sim/app/api/workspaces/[id]/permissions/route.test.ts b/apps/sim/app/api/workspaces/[id]/permissions/route.test.ts index c0a70b47a38..6899a3d53ea 100644 --- a/apps/sim/app/api/workspaces/[id]/permissions/route.test.ts +++ b/apps/sim/app/api/workspaces/[id]/permissions/route.test.ts @@ -24,12 +24,12 @@ import { } from '@sim/testing/mocks/workspace-context.mock' import { beforeEach, describe, expect, it, vi } from 'vitest' -const { mockAssertMembershipNotScimManaged } = vi.hoisted(() => ({ - mockAssertMembershipNotScimManaged: vi.fn(), +const { mockAssertWorkspaceAccessNotScimManaged } = vi.hoisted(() => ({ + mockAssertWorkspaceAccessNotScimManaged: vi.fn(), })) vi.mock('@/ee/scim/lib/managed-membership', () => ({ - assertMembershipNotScimManaged: mockAssertMembershipNotScimManaged, + assertWorkspaceAccessNotScimManaged: mockAssertWorkspaceAccessNotScimManaged, })) vi.mock('@sim/audit', () => auditMock) @@ -441,7 +441,7 @@ describe('workspace permissions route', () => { it('refuses a role change for a member the directory manages', async () => { queueOrgWorkspace([], [permissionRow(MEMBER_ID, 'read')]) - mockAssertMembershipNotScimManaged.mockRejectedValueOnce( + mockAssertWorkspaceAccessNotScimManaged.mockRejectedValueOnce( new ForbiddenOperationError('SCIM_MANAGED_MEMBERSHIP', 'Managed by the directory') ) @@ -452,8 +452,12 @@ describe('workspace permissions route', () => { expect(response.status).toBe(403) await expect(response.json()).resolves.toMatchObject({ error: 'Managed by the directory' }) - expect(mockAssertMembershipNotScimManaged).toHaveBeenCalledWith( - expect.objectContaining({ organizationId: ORG_ID, userId: MEMBER_ID }) + expect(mockAssertWorkspaceAccessNotScimManaged).toHaveBeenCalledWith( + expect.objectContaining({ + organizationId: ORG_ID, + userId: MEMBER_ID, + workspaceIds: [WORKSPACE_ID], + }) ) expect(dbChainMockFns.update).not.toHaveBeenCalled() }) diff --git a/apps/sim/ee/scim/components/options.ts b/apps/sim/ee/scim/components/options.ts index 7d4f6e1743e..a9fce737107 100644 --- a/apps/sim/ee/scim/components/options.ts +++ b/apps/sim/ee/scim/components/options.ts @@ -22,7 +22,7 @@ export const SETTING_TOGGLES = [ key: 'lockManualMembership', label: 'Lock managed membership', description: - 'Prevent manual invitations, role changes, and access grants for provisioned members.', + 'Prevent manual organization changes for provisioned members, and manual access changes on workspaces their directory groups are mapped to.', }, { key: 'disableJit', diff --git a/apps/sim/ee/scim/lib/managed-membership.ts b/apps/sim/ee/scim/lib/managed-membership.ts index 2ab304e587f..bbd064e7f9a 100644 --- a/apps/sim/ee/scim/lib/managed-membership.ts +++ b/apps/sim/ee/scim/lib/managed-membership.ts @@ -1,8 +1,10 @@ import { scimConnection, scimUser } from '@sim/db/schema' -import { type AnyColumn, Column, getTableName, is, type SQL, sql } from 'drizzle-orm' +import { type AnyColumn, and, Column, eq, getTableName, is, type SQL, sql } from 'drizzle-orm' import { ForbiddenOperationError } from '@/lib/core/application' import type { DbOrTx } from '@/lib/db/types' import { isScimDeploymentEnabled, isScimEntitledForOrganization } from '@/ee/scim/lib/entitlement' +import { resolveDesiredGrants } from '@/ee/scim/lib/projection/grants' +import { loadMappingRows } from '@/ee/scim/lib/projection/mapping-rows' /** * Refusing membership edits that the organization's directory owns. @@ -13,6 +15,12 @@ import { isScimDeploymentEnabled, isScimEntitledForOrganization } from '@/ee/sci * and nothing explains why. This turns that into an error that names the * remedy. * + * The directory owns a provisioned member's organization membership and role. + * It owns their workspace access only where one of their groups is mapped to + * that workspace: the grants reconciliation sets and withdraws. Access the + * directory cannot express is left to manual sharing; refusing it would leave + * no way to share the workspace at all. + * * Deliberately not applied to deprovisioning: an administrator must always be * able to remove someone in an emergency, whatever the directory believes. A * member removing themselves is refused, since the directory would re-add them. @@ -45,10 +53,14 @@ export function scimManagedUserPredicate( where ${qualifiedColumn(scimUser.userId)} = ${userId} and ${qualifiedColumn(scimConnection.organizationId)} = ${organizationId} and ${qualifiedColumn(scimConnection.status)} = 'active' - and coalesce((${qualifiedColumn(scimConnection.settings)} ->> 'lockManualMembership')::boolean, false) = true + and ${lockedSetting()} )` } +function lockedSetting(): SQL { + return sql`coalesce((${qualifiedColumn(scimConnection.settings)} ->> 'lockManualMembership')::boolean, false) = true` +} + /** * Drizzle removes Column qualifiers from single-table SELECT expressions, * including nested SQL. Explicit identifiers preserve this subquery's joins @@ -104,7 +116,7 @@ async function refuseIfDirectoryManaged( throw new ForbiddenOperationError('SCIM_MANAGED_MEMBERSHIP', message) } -/** Refuses an invitation to someone the directory already provisions, while the directory can still sync. */ +/** Refuses an invitation that would add someone the directory provisions to the organization. */ export async function assertInviteeNotScimManaged(params: { organizationId: string managed: boolean | null | undefined @@ -113,6 +125,47 @@ export async function assertInviteeNotScimManaged(params: { if (!(await isScimEntitledForOrganization(params.organizationId))) return throw new ForbiddenOperationError( 'SCIM_MANAGED_MEMBERSHIP', - 'This person is provisioned by the organization’s identity provider, so Sim will not grant them access separately. They already have access, or will once the next directory sync runs.' + 'This person is provisioned by the organization’s identity provider, which manages their organization membership. Add them to the organization there.' + ) +} + +/** + * Refuses a manual change to workspace access the directory owns: access that + * reconciliation sets and withdraws because one of the user's groups in this + * organization's locked connection is mapped to the workspace. Derived from the + * same mapping rows and rules reconciliation uses, so the two cannot disagree. + */ +export async function assertWorkspaceAccessNotScimManaged(params: { + organizationId: string + userId: string + workspaceIds: readonly string[] + executor: DbOrTx +}): Promise { + if (!isScimDeploymentEnabled() || params.workspaceIds.length === 0) return + const [provisioned] = await params.executor + .select({ scimUserId: scimUser.id }) + .from(scimUser) + .innerJoin(scimConnection, eq(scimConnection.id, scimUser.connectionId)) + .where( + and( + eq(scimUser.userId, params.userId), + eq(scimConnection.organizationId, params.organizationId), + eq(scimConnection.status, 'active'), + lockedSetting() + ) + ) + .limit(1) + if (!provisioned) return + const requested = new Set(params.workspaceIds) + const owned = resolveDesiredGrants( + await loadMappingRows(params.executor, provisioned.scimUserId) + ).some((grant) => grant.targetKind === 'workspace' && requested.has(grant.targetId)) + if (!owned) return + /** Read only once an owned workspace is found, so the common case costs nothing. */ + if (!(await isScimEntitledForOrganization(params.organizationId, params.executor))) return + const target = params.workspaceIds.length === 1 ? 'this workspace' : 'a selected workspace' + throw new ForbiddenOperationError( + 'SCIM_MANAGED_MEMBERSHIP', + `This person’s access to ${target} comes from a directory group mapped to it, so the organization’s identity provider manages it. Change their group membership there, or remove the workspace’s group mapping.` ) } diff --git a/apps/sim/ee/scim/lib/projection/mapping-rows.ts b/apps/sim/ee/scim/lib/projection/mapping-rows.ts new file mode 100644 index 00000000000..bc3f3b5373d --- /dev/null +++ b/apps/sim/ee/scim/lib/projection/mapping-rows.ts @@ -0,0 +1,27 @@ +import { scimGroupMapping, scimGroupMember } from '@sim/db/schema' +import { eq } from 'drizzle-orm' +import type { DbOrTx } from '@/lib/db/types' +import type { MappingRow } from '@/ee/scim/lib/projection/grants' + +/** + * The mapping rows this user reaches through their groups. + * + * Deliberately independent of whether the user is active. A deactivation blocks + * sign-in and API keys through suspension; it does not withdraw grants, because + * withdrawing a workspace grant reassigns the workflows the person owns there, + * and that cannot be undone by reactivating them. Grants change only when group + * membership or mappings change, or when the user is deprovisioned outright. + */ +export async function loadMappingRows(tx: DbOrTx, scimUserId: string): Promise { + return tx + .select({ + targetKind: scimGroupMapping.targetKind, + permissionGroupId: scimGroupMapping.permissionGroupId, + workspaceId: scimGroupMapping.workspaceId, + permissionType: scimGroupMapping.permissionType, + role: scimGroupMapping.role, + }) + .from(scimGroupMember) + .innerJoin(scimGroupMapping, eq(scimGroupMapping.groupId, scimGroupMember.groupId)) + .where(eq(scimGroupMember.scimUserId, scimUserId)) +} diff --git a/apps/sim/ee/scim/lib/projection/reconcile-user.ts b/apps/sim/ee/scim/lib/projection/reconcile-user.ts index cfbc77b3549..99512c441dc 100644 --- a/apps/sim/ee/scim/lib/projection/reconcile-user.ts +++ b/apps/sim/ee/scim/lib/projection/reconcile-user.ts @@ -4,8 +4,6 @@ import { permissionGroupMember, permissions, scimConnection, - scimGroupMapping, - scimGroupMember, scimProjectionGrant, scimUser, workspace, @@ -39,13 +37,13 @@ import { stopRunsWithoutWorkspaceAccessTx, } from '@/lib/workspaces/access/workspace-access' import { - type MappingRow, type ProjectionGrant, type ProjectionGrantOrigin, type ProjectionTargetKind, planGrantChanges, resolveDesiredGrants, } from '@/ee/scim/lib/projection/grants' +import { loadMappingRows } from '@/ee/scim/lib/projection/mapping-rows' const logger = createLogger('ScimProjection') @@ -86,29 +84,6 @@ function addChanges(total: ProjectionChanges, changes: ProjectionChanges): void /** Users per transaction when projecting outside a request's own transaction; the organization lock is held for the batch. */ export const PROJECTION_BATCH_SIZE = 25 -/** - * The mapping rows this user reaches through their groups. - * - * Deliberately independent of whether the user is active. A deactivation blocks - * sign-in and API keys through suspension; it does not withdraw grants, because - * withdrawing a workspace grant reassigns the workflows the person owns there, - * and that cannot be undone by reactivating them. Grants change only when group - * membership or mappings change, or when the user is deprovisioned outright. - */ -async function loadMappingRows(tx: DbOrTx, scimUserId: string): Promise { - return tx - .select({ - targetKind: scimGroupMapping.targetKind, - permissionGroupId: scimGroupMapping.permissionGroupId, - workspaceId: scimGroupMapping.workspaceId, - permissionType: scimGroupMapping.permissionType, - role: scimGroupMapping.role, - }) - .from(scimGroupMember) - .innerJoin(scimGroupMapping, eq(scimGroupMapping.groupId, scimGroupMember.groupId)) - .where(eq(scimGroupMember.scimUserId, scimUserId)) -} - async function currentGrants(tx: DbOrTx, scimUserId: string): Promise { const rows = await tx .select({ diff --git a/apps/sim/lib/invitations/__integration__/scim-locked-invitations.integration.ts b/apps/sim/lib/invitations/__integration__/scim-locked-invitations.integration.ts new file mode 100644 index 00000000000..2c7c7fabb9a --- /dev/null +++ b/apps/sim/lib/invitations/__integration__/scim-locked-invitations.integration.ts @@ -0,0 +1,210 @@ +/** + * Inviting a directory-provisioned member when the organization has locked + * managed membership: the directory owns workspaces a group is mapped to, and + * nothing else, so an unmapped workspace stays shareable by hand. + */ + +import { db } from '@sim/db' +import { + auditLog, + invitation, + member, + organization, + permissions, + scimConnection, + scimGroupMapping, + user, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { envFlagsMock } from '@sim/testing/mocks/env-flags.mock' +import { generateId } from '@sim/utils/id' +import { and, eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { withWorkspaceInvocationScope } from '@/lib/core/application/workspace-invocation-scope' +import { createScopedCliTransport } from '@/lib/mothership/agent-cli/scoped-transport' +import { addGroupMember, insertScimGroup } from '@/ee/scim/lib/repository/groups' +import { insertScimUser } from '@/ee/scim/lib/repository/users' +import '@/app/api/v2/workspaces/[workspaceId]/invitations/route' + +/** Directory provisioning on a self-hosted deployment, so a locked connection is enforced. */ +vi.mock('@/lib/core/config/env-flags', () => ({ ...envFlagsMock, isScimEnabled: true })) + +const ORIGIN = 'http://localhost:3000' +const organizationId = generateId() +const connectionId = generateId() +const unmappedWorkspaceId = generateId() +const mappedWorkspaceId = generateId() +const adminId = generateId() +const managedMemberId = generateId() +/** Provisioned and in the organization, but in no group mapped to anything. */ +const ungroupedMemberId = generateId() +const managedOutsiderId = generateId() +const fixtureDomain = `${generateId()}.scim-invite.test` +const emailOf = (id: string) => `${id}@${fixtureDomain}` + +function invite(workspaceId: string, email: string) { + const transport = createScopedCliTransport(ORIGIN, { + userId: adminId, + workspaceId, + chatId: generateId(), + }) + return withWorkspaceInvocationScope({ workspaceId, organizationId }, () => + transport(`${ORIGIN}/api/v2/workspaces/${workspaceId}/invitations`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ emails: [email], permission: 'write', membership: 'member' }), + }) + ) +} + +async function permissionOf(userId: string, workspaceId: string) { + const [row] = await db + .select({ permission: permissions.permissionType }) + .from(permissions) + .where( + and( + eq(permissions.entityType, 'workspace'), + eq(permissions.entityId, workspaceId), + eq(permissions.userId, userId) + ) + ) + return row?.permission ?? null +} + +/** The batch route answers 200 and lists each refused email with its reason. */ +async function refusalOf(response: Response) { + expect(response.status).toBe(200) + const body = (await response.json()) as { + data: { successful: string[]; failed: { error: string }[] } + } + expect(body.data.successful).toEqual([]) + return body.data.failed[0]?.error +} + +async function provision(userId: string) { + const { id } = await insertScimUser(db, { + connectionId, + userId, + active: true, + attributes: { + userName: emailOf(userId), + active: true, + displayName: 'Provisioned', + name: { formatted: 'Provisioned' }, + emails: [{ value: emailOf(userId), primary: true, type: 'work' }], + }, + }) + return id +} + +describe('workspace invitations under a locked directory connection', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + [adminId, managedMemberId, ungroupedMemberId, managedOutsiderId].map((id) => ({ + id, + name: 'SCIM invitation fixture', + email: emailOf(id), + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await db.insert(organization).values({ + id: organizationId, + name: 'SCIM invitation fixture', + slug: organizationId, + createdAt: now, + updatedAt: now, + }) + await db.insert(member).values( + [adminId, managedMemberId, ungroupedMemberId].map((userId) => ({ + id: generateId(), + userId, + organizationId, + role: 'member', + createdAt: now, + })) + ) + for (const id of [unmappedWorkspaceId, mappedWorkspaceId]) { + await insertWorkspaceFixture(db, { + id, + name: 'SCIM invitation fixture', + ownerId: adminId, + billedAccountUserId: adminId, + organizationId, + workspaceMode: 'organization', + }) + await db.insert(permissions).values({ + id: generateId(), + userId: adminId, + entityType: 'workspace', + entityId: id, + permissionType: 'admin', + }) + } + await db.insert(scimConnection).values({ + id: connectionId, + organizationId, + status: 'active', + settings: { lockManualMembership: true }, + }) + const group = await insertScimGroup(db, { connectionId, displayName: 'Mapped group' }) + await db.insert(scimGroupMapping).values({ + id: generateId(), + groupId: group.id, + targetKind: 'workspace', + workspaceId: mappedWorkspaceId, + permissionType: 'read', + }) + await addGroupMember(db, { groupId: group.id, scimUserId: await provision(managedMemberId) }) + await provision(ungroupedMemberId) + await provision(managedOutsiderId) + }) + + afterAll(async () => { + const workspaceIds = [unmappedWorkspaceId, mappedWorkspaceId] + await db.delete(invitation).where(eq(invitation.organizationId, organizationId)) + await db.delete(auditLog).where(inArray(auditLog.workspaceId, workspaceIds)) + await db.delete(scimConnection).where(eq(scimConnection.id, connectionId)) + await deleteWorkspaceFixture(db, inArray(workspace.id, workspaceIds)) + await db.delete(organization).where(eq(organization.id, organizationId)) + await db + .delete(user) + .where(inArray(user.id, [adminId, managedMemberId, ungroupedMemberId, managedOutsiderId])) + }) + + it('grants a provisioned member access to a workspace no group is mapped to', async () => { + const response = await invite(unmappedWorkspaceId, emailOf(managedMemberId)) + + expect(response.status).toBe(200) + expect(await permissionOf(managedMemberId, unmappedWorkspaceId)).toBe('write') + }) + + it('refuses a manual grant on a workspace the member’s directory group is mapped to', async () => { + const response = await invite(mappedWorkspaceId, emailOf(managedMemberId)) + + expect(await refusalOf(response)).toMatch(/identity provider/) + expect(await permissionOf(managedMemberId, mappedWorkspaceId)).toBeNull() + }) + + it('grants a mapped workspace to a provisioned member outside its mapped group', async () => { + const response = await invite(mappedWorkspaceId, emailOf(ungroupedMemberId)) + + expect(response.status).toBe(200) + expect(await permissionOf(ungroupedMemberId, mappedWorkspaceId)).toBe('write') + }) + + it('refuses inviting a provisioned person who is not an organization member', async () => { + const response = await invite(unmappedWorkspaceId, emailOf(managedOutsiderId)) + + expect(await refusalOf(response)).toMatch(/identity provider/) + const pending = await db + .select({ id: invitation.id }) + .from(invitation) + .where(eq(invitation.email, emailOf(managedOutsiderId))) + expect(pending).toEqual([]) + expect(await permissionOf(managedOutsiderId, unmappedWorkspaceId)).toBeNull() + }) +}) diff --git a/apps/sim/lib/invitations/direct-grant.ts b/apps/sim/lib/invitations/direct-grant.ts index 56877067ad1..12fa2111dfe 100644 --- a/apps/sim/lib/invitations/direct-grant.ts +++ b/apps/sim/lib/invitations/direct-grant.ts @@ -39,7 +39,7 @@ import { type WorkspaceWithOwner, } from '@/lib/workspaces/permissions/utils' import type { WorkspaceInvitePolicy } from '@/lib/workspaces/policy' -import { assertMembershipNotScimManaged } from '@/ee/scim/lib/managed-membership' +import { assertWorkspaceAccessNotScimManaged } from '@/ee/scim/lib/managed-membership' const logger = createLogger('InvitationDirectGrant') @@ -152,10 +152,11 @@ export async function grantWorkspaceAccessDirectly( userId: input.userId, organizationIds: [input.organizationId], }) - /** A member the directory manages gets workspace access from the directory, not by hand. */ - await assertMembershipNotScimManaged({ + /** Access to a workspace a directory group is mapped to comes from the directory, not by hand. */ + await assertWorkspaceAccessNotScimManaged({ organizationId: input.organizationId, userId: input.userId, + workspaceIds: [input.workspaceId], executor: tx, }) diff --git a/apps/sim/lib/invitations/workspace-invitations.ts b/apps/sim/lib/invitations/workspace-invitations.ts index efdc042feba..72c2a654459 100644 --- a/apps/sim/lib/invitations/workspace-invitations.ts +++ b/apps/sim/lib/invitations/workspace-invitations.ts @@ -54,6 +54,8 @@ import { validateInvitationsAllowed } from '@/ee/access-control/utils/permission import { isScimDeploymentEnabled } from '@/ee/scim/lib/entitlement' import { assertInviteeNotScimManaged, + assertMembershipNotScimManaged, + assertWorkspaceAccessNotScimManaged, scimManagedUserPredicate, } from '@/ee/scim/lib/managed-membership' @@ -179,6 +181,10 @@ async function ensureExistingMemberOrganizationRole({ email, }) } + /** The directory owns a provisioned member's organization role. */ + if (needsPromotion) { + await assertMembershipNotScimManaged({ organizationId, userId, executor: tx }) + } for (const workspaceId of context.targets.map((target) => target.workspaceId).sort()) { const workspaceDetails = await getWorkspaceWithOwner(workspaceId, { executor: tx, @@ -563,17 +569,23 @@ export async function createWorkspaceInvitation({ .where(eq(foldedEmail(user.email), normalizedEmail)) .then((rows) => rows[0]) + const existingMembership = existingUser ? await getUserOrganization(existingUser.id) : null + const isExistingMember = + organizationId !== null && existingMembership?.organizationId === organizationId + /** * When the organization has made its identity provider the source of truth for - * membership, a Sim invitation to someone the directory already provisions is - * redundant at best and reverted at worst. Read as part of the lookup above so - * the common case costs no extra query. + * membership, an invitation that would add someone the directory provisions to + * the organization is reverted by the next sync. Read as part of the lookup + * above so the common case costs no extra query. A provisioned member who + * already belongs is checked per workspace below, before any grant is written. */ if (organizationId) { - await assertInviteeNotScimManaged({ organizationId, managed: existingUser?.scimManaged }) + await assertInviteeNotScimManaged({ + organizationId, + managed: existingUser?.scimManaged && !isExistingMember, + }) } - - const existingMembership = existingUser ? await getUserOrganization(existingUser.id) : null let existingOrganizationRole = existingMembership?.role let organizationRoleUpdated = false if ( @@ -600,10 +612,7 @@ export async function createWorkspaceInvitation({ let pendingTargets = context.targets if (existingUser) { - const inheritsWorkspaceAdmin = - organizationId !== null && - existingMembership?.organizationId === organizationId && - isOrgAdminRole(existingOrganizationRole) + const inheritsWorkspaceAdmin = isExistingMember && isOrgAdminRole(existingOrganizationRole) const accessibleRows = await db .select({ workspaceId: permissions.entityId, permission: permissions.permissionType }) .from(permissions) @@ -635,11 +644,7 @@ export async function createWorkspaceInvitation({ (target) => !accessibleWorkspaceIds.has(target.workspaceId) ) if (pendingTargets.length === 0) { - if ( - existingAccessPolicy === 'ensure-at-least' && - organizationId && - existingMembership?.organizationId === organizationId - ) { + if (existingAccessPolicy === 'ensure-at-least' && isExistingMember) { return { id: existingUser.id, email: normalizedEmail, @@ -663,7 +668,20 @@ export async function createWorkspaceInvitation({ * Already in this organization: they hold a seat, so grant access directly * with no invitation or acceptance step. */ - if (organizationId && existingMembership?.organizationId === organizationId) { + if (organizationId && isExistingMember) { + /** + * Refuse up front when any selected workspace's access is directory-owned, + * so a multi-workspace invite does not grant some and then fail. Each grant + * rechecks under its own locks. + */ + if (existingUser.scimManaged) { + await assertWorkspaceAccessNotScimManaged({ + organizationId, + userId: existingUser.id, + workspaceIds: pendingTargets.map((target) => target.workspaceId), + executor: db, + }) + } let outcome: DirectGrantOutcome['outcome'] = organizationRoleUpdated ? 'updated' : 'unchanged' const grantedWorkspaceIds: string[] = [] for (const target of pendingTargets) { diff --git a/apps/sim/lib/workspaces/__integration__/members.integration.ts b/apps/sim/lib/workspaces/__integration__/members.integration.ts index 7b213711503..7696f7fd25e 100644 --- a/apps/sim/lib/workspaces/__integration__/members.integration.ts +++ b/apps/sim/lib/workspaces/__integration__/members.integration.ts @@ -9,6 +9,7 @@ import { organization, permissions, scimConnection, + scimGroupMapping, scimUser, session, user, @@ -28,8 +29,10 @@ import { PATCH as updateMember, } from '@/app/api/v2/workspaces/[workspaceId]/members/[userId]/route' import { GET as listMembers } from '@/app/api/v2/workspaces/[workspaceId]/members/route' +import { addGroupMember, insertScimGroup } from '@/ee/scim/lib/repository/groups' /** Directory provisioning on a self-hosted deployment, so a locked SCIM member is refused. */ + vi.mock('@/lib/core/config/env-flags', () => ({ ...envFlagsMock, isScimEnabled: true })) const USER_NAMES = [ @@ -430,7 +433,29 @@ describe('v2 workspace member management against PostgreSQL', () => { expect(await roleOf(f.users.reader)).toBe('read') }) - it('keeps the SCIM_MANAGED_MEMBERSHIP code for a directory-managed member', async () => { + it('changes a provisioned member’s role on a workspace no directory group is mapped to', async () => { + const response = await call(key('admin'), 'PATCH', f.users.managed, { body: { role: 'read' } }) + expect(response.status).toBe(200) + expect(await roleOf(f.users.managed)).toBe('read') + }) + + it('keeps the SCIM_MANAGED_MEMBERSHIP code on a workspace the member’s directory group is mapped to', async () => { + const group = await insertScimGroup(db, { + connectionId: f.scimConnectionId, + displayName: 'Mapped group', + }) + await db.insert(scimGroupMapping).values({ + id: generateId(), + groupId: group.id, + targetKind: 'workspace', + workspaceId: f.workspaceId, + permissionType: 'write', + }) + const [managed] = await db + .select({ id: scimUser.id }) + .from(scimUser) + .where(eq(scimUser.userId, f.users.managed)) + await addGroupMember(db, { groupId: group.id, scimUserId: managed.id }) const response = await call(key('admin'), 'PATCH', f.users.managed, { body: { role: 'read' } }) expect(response).toMatchObject({ status: 403, diff --git a/apps/sim/lib/workspaces/permissions/management-store.ts b/apps/sim/lib/workspaces/permissions/management-store.ts index ee2b035d86b..3db25913153 100644 --- a/apps/sim/lib/workspaces/permissions/management-store.ts +++ b/apps/sim/lib/workspaces/permissions/management-store.ts @@ -18,7 +18,7 @@ import { getEffectiveWorkspacePermission, getWorkspaceWithOwner, } from '@/lib/workspaces/permissions/utils' -import { assertMembershipNotScimManaged } from '@/ee/scim/lib/managed-membership' +import { assertWorkspaceAccessNotScimManaged } from '@/ee/scim/lib/managed-membership' const logger = createLogger('WorkspacesPermissionsAPI') @@ -309,13 +309,17 @@ export async function updateWorkspacePermissionRecords( lockedMembers.filter((row) => isOrgAdminRole(row.role)).map((row) => row.userId) ) /** - * A directory that owns membership also owns the workspace role it set, - * so the change is refused here for the same reason an invitation is: - * the next sync would revert it. Checked under the member lock so a - * connection enabled mid-request cannot slip a change past it. + * A role the directory sets through one of the member's mapped groups is + * refused here for the same reason an invitation is: the next sync would + * revert it. */ for (const userId of targetUserIds) { - await assertMembershipNotScimManaged({ organizationId, userId, executor: tx }) + await assertWorkspaceAccessNotScimManaged({ + organizationId, + userId, + workspaceIds: [workspaceId], + executor: tx, + }) } } From 5a426113330ba1b4305b02a283640cf5c1bff9bf Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 14:08:43 -0800 Subject: [PATCH 2/3] fix(scim): keep tracked directory grants locked until reconciliation withdraws them --- apps/sim/ee/scim/lib/managed-membership.ts | 27 ++++++--- .../scim/lib/projection/directory-grants.ts | 59 +++++++++++++++++++ .../ee/scim/lib/projection/mapping-rows.ts | 27 --------- .../ee/scim/lib/projection/reconcile-user.ts | 24 +------- .../__integration__/members.integration.ts | 22 +++++++ 5 files changed, 101 insertions(+), 58 deletions(-) create mode 100644 apps/sim/ee/scim/lib/projection/directory-grants.ts delete mode 100644 apps/sim/ee/scim/lib/projection/mapping-rows.ts diff --git a/apps/sim/ee/scim/lib/managed-membership.ts b/apps/sim/ee/scim/lib/managed-membership.ts index bbd064e7f9a..5c7dcc17383 100644 --- a/apps/sim/ee/scim/lib/managed-membership.ts +++ b/apps/sim/ee/scim/lib/managed-membership.ts @@ -3,8 +3,8 @@ import { type AnyColumn, and, Column, eq, getTableName, is, type SQL, sql } from import { ForbiddenOperationError } from '@/lib/core/application' import type { DbOrTx } from '@/lib/db/types' import { isScimDeploymentEnabled, isScimEntitledForOrganization } from '@/ee/scim/lib/entitlement' +import { currentGrants, loadMappingRows } from '@/ee/scim/lib/projection/directory-grants' import { resolveDesiredGrants } from '@/ee/scim/lib/projection/grants' -import { loadMappingRows } from '@/ee/scim/lib/projection/mapping-rows' /** * Refusing membership edits that the organization's directory owns. @@ -131,9 +131,10 @@ export async function assertInviteeNotScimManaged(params: { /** * Refuses a manual change to workspace access the directory owns: access that - * reconciliation sets and withdraws because one of the user's groups in this - * organization's locked connection is mapped to the workspace. Derived from the - * same mapping rows and rules reconciliation uses, so the two cannot disagree. + * reconciliation sets because one of the user's groups in this organization's + * locked connection is mapped to the workspace, or that it applied and has not + * yet withdrawn. Derived from the same rows reconciliation reads, so the two + * cannot disagree. */ export async function assertWorkspaceAccessNotScimManaged(params: { organizationId: string @@ -156,16 +157,26 @@ export async function assertWorkspaceAccessNotScimManaged(params: { ) .limit(1) if (!provisioned) return - const requested = new Set(params.workspaceIds) - const owned = resolveDesiredGrants( + /** + * Owned while a mapping calls for the grant, and until reconciliation has + * withdrawn one it still tracks: a mapping removal commits before its members + * are reconciled, and a manual change in that gap would be undone by the + * pending withdrawal. + */ + const mapped = resolveDesiredGrants( await loadMappingRows(params.executor, provisioned.scimUserId) - ).some((grant) => grant.targetKind === 'workspace' && requested.has(grant.targetId)) + ) + const tracked = await currentGrants(params.executor, provisioned.scimUserId) + const requested = new Set(params.workspaceIds) + const owned = [...mapped, ...tracked].some( + (grant) => grant.targetKind === 'workspace' && requested.has(grant.targetId) + ) if (!owned) return /** Read only once an owned workspace is found, so the common case costs nothing. */ if (!(await isScimEntitledForOrganization(params.organizationId, params.executor))) return const target = params.workspaceIds.length === 1 ? 'this workspace' : 'a selected workspace' throw new ForbiddenOperationError( 'SCIM_MANAGED_MEMBERSHIP', - `This person’s access to ${target} comes from a directory group mapped to it, so the organization’s identity provider manages it. Change their group membership there, or remove the workspace’s group mapping.` + `This person’s access to ${target} is managed by the organization’s identity provider through a directory group mapping. Change their group membership there, or remove the mapping and let the next directory sync finish.` ) } diff --git a/apps/sim/ee/scim/lib/projection/directory-grants.ts b/apps/sim/ee/scim/lib/projection/directory-grants.ts new file mode 100644 index 00000000000..8d947af9385 --- /dev/null +++ b/apps/sim/ee/scim/lib/projection/directory-grants.ts @@ -0,0 +1,59 @@ +import { scimGroupMapping, scimGroupMember, scimProjectionGrant } from '@sim/db/schema' +import { eq } from 'drizzle-orm' +import type { DbOrTx } from '@/lib/db/types' +import type { + MappingRow, + ProjectionGrant, + ProjectionGrantOrigin, + ProjectionTargetKind, +} from '@/ee/scim/lib/projection/grants' + +/** + * What reconciliation reads for one directory user: the grants their groups' + * mappings call for, and the grants it has already applied and still tracks. + * Shared with the managed-membership guard so both agree on what the directory owns. + */ + +/** + * The mapping rows this user reaches through their groups. + * + * Deliberately independent of whether the user is active. A deactivation blocks + * sign-in and API keys through suspension; it does not withdraw grants, because + * withdrawing a workspace grant reassigns the workflows the person owns there, + * and that cannot be undone by reactivating them. Grants change only when group + * membership or mappings change, or when the user is deprovisioned outright. + */ +export async function loadMappingRows(tx: DbOrTx, scimUserId: string): Promise { + return tx + .select({ + targetKind: scimGroupMapping.targetKind, + permissionGroupId: scimGroupMapping.permissionGroupId, + workspaceId: scimGroupMapping.workspaceId, + permissionType: scimGroupMapping.permissionType, + role: scimGroupMapping.role, + }) + .from(scimGroupMember) + .innerJoin(scimGroupMapping, eq(scimGroupMapping.groupId, scimGroupMember.groupId)) + .where(eq(scimGroupMember.scimUserId, scimUserId)) +} + +/** The grants reconciliation applied for this user and has not yet withdrawn. */ +export async function currentGrants(tx: DbOrTx, scimUserId: string): Promise { + const rows = await tx + .select({ + targetKind: scimProjectionGrant.targetKind, + targetId: scimProjectionGrant.targetId, + permissionType: scimProjectionGrant.permissionType, + origin: scimProjectionGrant.origin, + baselinePermission: scimProjectionGrant.baselinePermission, + }) + .from(scimProjectionGrant) + .where(eq(scimProjectionGrant.scimUserId, scimUserId)) + return rows.map((row) => ({ + targetKind: row.targetKind as ProjectionTargetKind, + targetId: row.targetId, + origin: row.origin as ProjectionGrantOrigin, + baselinePermission: row.baselinePermission ?? null, + ...(row.permissionType ? { permissionType: row.permissionType } : {}), + })) +} diff --git a/apps/sim/ee/scim/lib/projection/mapping-rows.ts b/apps/sim/ee/scim/lib/projection/mapping-rows.ts deleted file mode 100644 index bc3f3b5373d..00000000000 --- a/apps/sim/ee/scim/lib/projection/mapping-rows.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { scimGroupMapping, scimGroupMember } from '@sim/db/schema' -import { eq } from 'drizzle-orm' -import type { DbOrTx } from '@/lib/db/types' -import type { MappingRow } from '@/ee/scim/lib/projection/grants' - -/** - * The mapping rows this user reaches through their groups. - * - * Deliberately independent of whether the user is active. A deactivation blocks - * sign-in and API keys through suspension; it does not withdraw grants, because - * withdrawing a workspace grant reassigns the workflows the person owns there, - * and that cannot be undone by reactivating them. Grants change only when group - * membership or mappings change, or when the user is deprovisioned outright. - */ -export async function loadMappingRows(tx: DbOrTx, scimUserId: string): Promise { - return tx - .select({ - targetKind: scimGroupMapping.targetKind, - permissionGroupId: scimGroupMapping.permissionGroupId, - workspaceId: scimGroupMapping.workspaceId, - permissionType: scimGroupMapping.permissionType, - role: scimGroupMapping.role, - }) - .from(scimGroupMember) - .innerJoin(scimGroupMapping, eq(scimGroupMapping.groupId, scimGroupMember.groupId)) - .where(eq(scimGroupMember.scimUserId, scimUserId)) -} diff --git a/apps/sim/ee/scim/lib/projection/reconcile-user.ts b/apps/sim/ee/scim/lib/projection/reconcile-user.ts index 99512c441dc..21e28b6ecd9 100644 --- a/apps/sim/ee/scim/lib/projection/reconcile-user.ts +++ b/apps/sim/ee/scim/lib/projection/reconcile-user.ts @@ -36,14 +36,12 @@ import { revokeWorkspaceAccessTx, stopRunsWithoutWorkspaceAccessTx, } from '@/lib/workspaces/access/workspace-access' +import { currentGrants, loadMappingRows } from '@/ee/scim/lib/projection/directory-grants' import { type ProjectionGrant, - type ProjectionGrantOrigin, - type ProjectionTargetKind, planGrantChanges, resolveDesiredGrants, } from '@/ee/scim/lib/projection/grants' -import { loadMappingRows } from '@/ee/scim/lib/projection/mapping-rows' const logger = createLogger('ScimProjection') @@ -84,26 +82,6 @@ function addChanges(total: ProjectionChanges, changes: ProjectionChanges): void /** Users per transaction when projecting outside a request's own transaction; the organization lock is held for the batch. */ export const PROJECTION_BATCH_SIZE = 25 -async function currentGrants(tx: DbOrTx, scimUserId: string): Promise { - const rows = await tx - .select({ - targetKind: scimProjectionGrant.targetKind, - targetId: scimProjectionGrant.targetId, - permissionType: scimProjectionGrant.permissionType, - origin: scimProjectionGrant.origin, - baselinePermission: scimProjectionGrant.baselinePermission, - }) - .from(scimProjectionGrant) - .where(eq(scimProjectionGrant.scimUserId, scimUserId)) - return rows.map((row) => ({ - targetKind: row.targetKind as ProjectionTargetKind, - targetId: row.targetId, - origin: row.origin as ProjectionGrantOrigin, - baselinePermission: row.baselinePermission ?? null, - ...(row.permissionType ? { permissionType: row.permissionType } : {}), - })) -} - /** Reads access independently of provenance so a reconcile can repair real drift. */ async function actualGrants( tx: DbOrTx, diff --git a/apps/sim/lib/workspaces/__integration__/members.integration.ts b/apps/sim/lib/workspaces/__integration__/members.integration.ts index 7696f7fd25e..f9b0aa13ac5 100644 --- a/apps/sim/lib/workspaces/__integration__/members.integration.ts +++ b/apps/sim/lib/workspaces/__integration__/members.integration.ts @@ -10,6 +10,7 @@ import { permissions, scimConnection, scimGroupMapping, + scimProjectionGrant, scimUser, session, user, @@ -464,6 +465,27 @@ describe('v2 workspace member management against PostgreSQL', () => { expect(await roleOf(f.users.managed)).toBe('write') }) + it('refuses a role change while a removed mapping’s grant awaits withdrawal', async () => { + const [managed] = await db + .select({ id: scimUser.id }) + .from(scimUser) + .where(eq(scimUser.userId, f.users.managed)) + await db.insert(scimProjectionGrant).values({ + id: generateId(), + connectionId: f.scimConnectionId, + scimUserId: managed.id, + targetKind: 'workspace', + targetId: f.workspaceId, + permissionType: 'write', + }) + const response = await call(key('admin'), 'PATCH', f.users.managed, { body: { role: 'admin' } }) + expect(response).toMatchObject({ + status: 403, + body: { error: { code: 'FORBIDDEN', details: { code: 'SCIM_MANAGED_MEMBERSHIP' } } }, + }) + expect(await roleOf(f.users.managed)).toBe('write') + }) + it('answers a role change held up by a competing writer with a retryable 503', async () => { let lockTaken!: () => void let release!: () => void From ec594a7b5bae1d59d5738774aa0cad0da14fa41d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 14:26:21 -0800 Subject: [PATCH 3/3] test(scim): cover the mapped-workspace lock boundary in the SCIM e2e --- apps/sim/scripts/test-scim-e2e.ts | 73 ++++++++++++++++++++----------- 1 file changed, 48 insertions(+), 25 deletions(-) diff --git a/apps/sim/scripts/test-scim-e2e.ts b/apps/sim/scripts/test-scim-e2e.ts index f21fb3174a5..b93f2ab3ae4 100644 --- a/apps/sim/scripts/test-scim-e2e.ts +++ b/apps/sim/scripts/test-scim-e2e.ts @@ -1580,7 +1580,7 @@ async function run() { ) await check( - 'Managed membership locks block invitations and permission edits while allowing unmanaged members', + 'Managed membership locks block edits only on workspaces the member’s groups map, and never unmanaged members', async () => { const manualUserId = generateId() const manualEmail = `manual@${primary.domain}` @@ -1589,42 +1589,61 @@ async function run() { await sql`insert into user_stats (id, user_id) values (${generateId()}, ${manualUserId})` await sql`insert into member (id, user_id, organization_id, role) values (${generateId()}, ${manualUserId}, ${primary.orgId}, 'member')` + const editAlice = (permissions: string, expected?: number) => + request(`/api/workspaces/${primary.workspaceId}/permissions`, { + fixture: primary, + method: 'PATCH', + ...(expected ? { expected } : {}), + contentType: 'application/json', + body: { updates: [{ userId: aliceUserId, permissions }] }, + }) await admin(primary, '', { method: 'PUT', body: { settings: { lockManualMembership: true } }, }) + let lockedGroupId = '' try { - const invitationBody = { - workspaceIds: [primary.workspaceId], - permission: 'read', - membership: 'member', - } - const managedInvite = ( - await request('/api/workspaces/invitations/batch', { - fixture: primary, - method: 'POST', - contentType: 'application/json', - body: { ...invitationBody, emails: [aliceEmail] }, - }) - ).body - assert.equal(managedInvite.success, false) - assert(Array.isArray(managedInvite.failed)) - assert.match(string(record(managedInvite.failed[0]).error), /identity provider/) - assert(!JSON.stringify(managedInvite).includes('select ')) - await request(`/api/workspaces/${primary.workspaceId}/permissions`, { - fixture: primary, - method: 'PATCH', - expected: 403, - contentType: 'application/json', - body: { updates: [{ userId: aliceUserId, permissions: 'write' }] }, + await editAlice('write') + assert.equal(await permission(aliceUserId, primary.workspaceId), 'write') + await editAlice('read') + assert.equal(await permission(aliceUserId, primary.workspaceId), 'read') + + const created = await scim(token, '/Groups', { + method: 'POST', + expected: 201, + body: { + schemas: [GROUP_SCHEMA], + displayName: 'SCIM E2E managed workspace', + members: [{ value: aliceId }], + }, }) + lockedGroupId = string(created.body.id) + await admin(primary, '/mappings', { + method: 'POST', + expected: 201, + body: { + groupId: lockedGroupId, + targetKind: 'workspace', + workspaceId: primary.workspaceId, + permissionType: 'read', + }, + }) + const refused = await editAlice('write', 403) + assert.match(JSON.stringify(refused.body), /identity provider/) + assert(!JSON.stringify(refused.body).includes('select ')) assert.equal(await permission(aliceUserId, primary.workspaceId), 'read') + const manualInvite = ( await request('/api/workspaces/invitations/batch', { fixture: primary, method: 'POST', contentType: 'application/json', - body: { ...invitationBody, emails: [manualEmail] }, + body: { + workspaceIds: [primary.workspaceId], + permission: 'read', + membership: 'member', + emails: [manualEmail], + }, }) ).body assert.equal(manualInvite.success, true) @@ -1637,11 +1656,15 @@ async function run() { }) assert.equal(await permission(manualUserId, primary.workspaceId), 'write') } finally { + /** Unlocked first, so removing the mapping restores Alice's manual access instead of withdrawing it. */ await admin(primary, '', { method: 'PUT', body: { settings: { lockManualMembership: false } }, }) + if (lockedGroupId) + await scim(token, `/Groups/${lockedGroupId}`, { method: 'DELETE', expected: 204 }) } + assert.equal(await permission(aliceUserId, primary.workspaceId), 'read') } )