Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/docs/content/docs/platform/enterprise/scim/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion apps/docs/content/docs/platform/enterprise/scim/okta.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ For example, use `Sim users` to assign the app and `Finance` as the pushed group

<Image src="/static/enterprise/okta/group-push.png" alt="Header Auth Test App Group Push selecting an engineering group and Create Group for the downstream group" width={1001} height={927} maxWidth="xl" className="mx-auto h-auto w-full" />

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

Expand Down
16 changes: 10 additions & 6 deletions apps/sim/app/api/workspaces/[id]/permissions/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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')
)

Expand All @@ -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()
})
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/ee/scim/components/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
72 changes: 68 additions & 4 deletions apps/sim/ee/scim/lib/managed-membership.ts
Original file line number Diff line number Diff line change
@@ -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 { currentGrants, loadMappingRows } from '@/ee/scim/lib/projection/directory-grants'
import { resolveDesiredGrants } from '@/ee/scim/lib/projection/grants'

/**
* Refusing membership edits that the organization's directory owns.
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -113,6 +125,58 @@ 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 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
userId: string
workspaceIds: readonly string[]
executor: DbOrTx
}): Promise<void> {
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
/**
* 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)
)
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} 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.`
)
}
59 changes: 59 additions & 0 deletions apps/sim/ee/scim/lib/projection/directory-grants.ts
Original file line number Diff line number Diff line change
@@ -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<MappingRow[]> {
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<ProjectionGrant[]> {
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 } : {}),
}))
}
49 changes: 1 addition & 48 deletions apps/sim/ee/scim/lib/projection/reconcile-user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import {
permissionGroupMember,
permissions,
scimConnection,
scimGroupMapping,
scimGroupMember,
scimProjectionGrant,
scimUser,
workspace,
Expand Down Expand Up @@ -38,11 +36,9 @@ import {
revokeWorkspaceAccessTx,
stopRunsWithoutWorkspaceAccessTx,
} from '@/lib/workspaces/access/workspace-access'
import { currentGrants, loadMappingRows } from '@/ee/scim/lib/projection/directory-grants'
import {
type MappingRow,
type ProjectionGrant,
type ProjectionGrantOrigin,
type ProjectionTargetKind,
planGrantChanges,
resolveDesiredGrants,
} from '@/ee/scim/lib/projection/grants'
Expand Down Expand Up @@ -86,49 +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

/**
* 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<MappingRow[]> {
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<ProjectionGrant[]> {
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,
Expand Down
Loading
Loading