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
151 changes: 151 additions & 0 deletions apps/sim/app/api/permission-groups/user/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/** @vitest-environment node */
import { createMockRequest } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const mocks = vi.hoisted(() => ({
session: vi.fn(),
context: vi.fn(),
role: vi.fn(),
admin: vi.fn(),
enterprise: vi.fn(),
group: vi.fn(),
}))
vi.mock('@/lib/auth', () => ({ getSession: mocks.session }))
vi.mock('@/lib/workspaces/application/workspace-context', () => ({
resolveActiveWorkspaceApplicationContext: mocks.context,
}))
vi.mock('@sim/platform-authz/workspace', async (importOriginal) => ({
...(await importOriginal<typeof import('@sim/platform-authz/workspace')>()),
resolveEffectiveWorkspacePermission: mocks.role,
}))
vi.mock('@/lib/workspaces/permissions/utils', () => ({ isOrganizationAdminOrOwner: mocks.admin }))
vi.mock('@/lib/billing/core/subscription', () => ({
isOrganizationOnEnterprisePlan: mocks.enterprise,
}))
vi.mock('@/lib/permission-groups/resolve.server', () => ({ resolveWorkspaceGroup: mocks.group }))

import { userPermissionConfigSchema } from '@/lib/api/contracts/permission-groups'
import { OrchestrationError } from '@/lib/core/orchestration/types'
import { readUserPermissionConfig } from '@/lib/permission-groups/application/read-user-config'
import { DEFAULT_PERMISSION_GROUP_CONFIG } from '@/lib/permission-groups/fields'
import { GET } from '@/app/api/permission-groups/user/route'

const principal = { kind: 'session', userId: 'viewer', sessionId: 'session' } as const
const context = {
workspaceId: 'workspace',
workspaceOrganizationId: 'owning-org',
allowPersonalApiKeys: true,
billedAccountUserId: 'owner',
}
const unrestricted = {
permissionGroupId: null,
groupName: null,
config: null,
entitled: false,
organizationId: 'owning-org',
isOrgAdmin: false,
}
function get(query = '?workspaceId=workspace') {
return GET(
createMockRequest('GET', undefined, {}, `http://localhost/api/permission-groups/user${query}`)
)
}

beforeEach(() => {
vi.clearAllMocks()
mocks.session.mockResolvedValue({
user: { id: 'viewer' },
session: { id: 'session', activeOrganizationId: 'unrelated-org' },
})
mocks.context.mockResolvedValue(context)
mocks.role.mockResolvedValue('read')
mocks.admin.mockResolvedValue(false)
mocks.enterprise.mockResolvedValue(true)
mocks.group.mockResolvedValue(null)
})

describe('user permission policy shared read', () => {
it('authenticates before parsing or protected lookups', async () => {
mocks.session.mockResolvedValue(null)
expect((await get('')).status).toBe(401)
expect(mocks.context).not.toHaveBeenCalled()
})
it.each(['', '?workspaceId='])('preserves missing workspace validation for %s', async (query) => {
const response = await get(query)
expect(response.status).toBe(400)
expect(await response.json()).toMatchObject({ error: 'workspaceId is required' })
expect(mocks.context).not.toHaveBeenCalled()
})
it('preserves missing or archived workspace responses', async () => {
mocks.context.mockRejectedValue(new OrchestrationError('not_found', 'Workspace not found'))
const response = await get()
expect(response.status).toBe(404)
expect(await response.json()).toMatchObject({ error: 'Workspace not found' })
expect(mocks.group).not.toHaveBeenCalled()
})
it('refuses current nonmembers before loading their policy', async () => {
mocks.role.mockResolvedValue(null)
const response = await get()
expect(response.status).toBe(403)
expect(await response.json()).toMatchObject({ error: 'Not a member of this workspace' })
expect(mocks.admin).not.toHaveBeenCalled()
expect(mocks.enterprise).not.toHaveBeenCalled()
expect(mocks.group).not.toHaveBeenCalled()
})
it('leaves personal workspaces unrestricted without organization reads', async () => {
mocks.context.mockResolvedValue({ ...context, workspaceOrganizationId: null })
const response = await get()
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ ...unrestricted, organizationId: null })
expect(mocks.admin).not.toHaveBeenCalled()
expect(mocks.enterprise).not.toHaveBeenCalled()
expect(mocks.group).not.toHaveBeenCalled()
})
it('retains organization admin status without enterprise entitlement', async () => {
mocks.enterprise.mockResolvedValue(false)
mocks.admin.mockResolvedValue(true)
expect(await (await get()).json()).toEqual({ ...unrestricted, isOrgAdmin: true })
expect(mocks.group).not.toHaveBeenCalled()
})
it('reads the acting member in the workspace owning organization and matches the server result', async () => {
const group = {
permissionGroupId: 'group',
groupName: 'Restricted',
config: { ...DEFAULT_PERMISSION_GROUP_CONFIG, hideCopilot: true },
}
mocks.group.mockResolvedValue(group)
const response = await get()
expect(response.status).toBe(200)
const body = await response.json()
expect(body).toEqual({ ...unrestricted, ...group, entitled: true })
expect(mocks.group).toHaveBeenCalledWith('viewer', 'owning-org', 'workspace')
expect(mocks.admin).toHaveBeenCalledWith('viewer', 'owning-org')
const serverResult = await readUserPermissionConfig.execute({
principal,
input: { workspaceId: 'workspace' },
})
expect(userPermissionConfigSchema.parse(serverResult)).toEqual(body)
})
it('retains enterprise entitlement when no group applies', async () => {
expect(await (await get()).json()).toEqual({ ...unrestricted, entitled: true })
})
it('does not turn policy infrastructure failures into unrestricted access', async () => {
mocks.enterprise.mockImplementation(async (_organizationId, onError) => {
if (onError === 'throw') throw new Error('unavailable')
return false
})
expect((await get()).status).toBe(500)
await expect(
readUserPermissionConfig.execute({ principal, input: { workspaceId: 'workspace' } })
).rejects.toThrow('unavailable')
})
it('rejects API keys before canonical lookup on the shared server entry point', async () => {
await expect(
readUserPermissionConfig.execute({
principal: { kind: 'personal_api_key', userId: 'viewer', keyId: 'key' },
input: { workspaceId: 'workspace' },
})
).rejects.toThrow('cannot perform operation')
expect(mocks.context).not.toHaveBeenCalled()
})
})
106 changes: 32 additions & 74 deletions apps/sim/app/api/permission-groups/user/route.ts
Original file line number Diff line number Diff line change
@@ -1,77 +1,35 @@
import { NextResponse } from 'next/server'
import { userPermissionConfigQuerySchema } from '@/lib/api/contracts/permission-groups'
import { getSession } from '@/lib/auth'
import { isOrganizationOnEnterprisePlan } from '@/lib/billing'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { getUserPermissionConfigContract } from '@/lib/api/contracts/permission-groups'
import {
checkWorkspaceAccess,
isOrganizationAdminOrOwner,
} from '@/lib/workspaces/permissions/utils'
import { resolveWorkspaceGroup } from '@/ee/access-control/utils/permission-check'

export const GET = withRouteHandler(async (req: Request) => {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const queryResult = userPermissionConfigQuerySchema.safeParse(
Object.fromEntries(new URL(req.url).searchParams.entries())
)
if (!queryResult.success) {
return NextResponse.json({ error: 'workspaceId is required' }, { status: 400 })
}
const { workspaceId } = queryResult.data

const access = await checkWorkspaceAccess(workspaceId, session.user.id)
if (!access.exists) {
return NextResponse.json({ error: 'Workspace not found' }, { status: 404 })
}
if (!access.hasAccess) {
return NextResponse.json({ error: 'Not a member of this workspace' }, { status: 403 })
}

const organizationId = access.workspace?.organizationId ?? null

// Workspaces without an organization have no permission groups, and the caller
// can never be an org admin in that case.
if (!organizationId) {
return NextResponse.json({
permissionGroupId: null,
groupName: null,
config: null,
entitled: false,
organizationId: null,
isOrgAdmin: false,
})
}

// Resolve role + entitlement against the WORKSPACE's owning organization (not
// the caller's active org) so management gating is scoped to the org that
// actually governs this workspace. External members are not org admins here.
const isOrgAdmin = await isOrganizationAdminOrOwner(session.user.id, organizationId)

if (!(await isOrganizationOnEnterprisePlan(organizationId))) {
return NextResponse.json({
permissionGroupId: null,
groupName: null,
config: null,
entitled: false,
organizationId,
isOrgAdmin,
})
}

// Single source of truth: specific-scope group covering this workspace ->
// the user's all-workspaces group -> org default -> none.
const resolved = await resolveWorkspaceGroup(session.user.id, organizationId, workspaceId)

return NextResponse.json({
permissionGroupId: resolved?.permissionGroupId ?? null,
groupName: resolved?.groupName ?? null,
config: resolved?.config ?? null,
entitled: true,
organizationId,
isOrgAdmin,
})
defineInternalJsonRoute,
extendInternalErrorPolicy,
internalErrorResponse,
internalOrchestrationErrorPolicy,
internalRateLimits,
internalSessionAuth,
} from '@/lib/api/server/routes'
import { NoWorkspaceAccessError } from '@/lib/core/application/workspace-authorization'
import {
readUserPermissionConfig,
readUserPermissionConfigOperation,
} from '@/lib/permission-groups/application/read-user-config'

export const GET = defineInternalJsonRoute({
contract: getUserPermissionConfigContract,
auth: internalSessionAuth,
operation: readUserPermissionConfigOperation,
rateLimit: internalRateLimits.none({
reason: 'Preserve the existing internal policy read rate.',
}),
parseOptions: {
validationErrorResponse: () =>
NextResponse.json({ error: 'workspaceId is required' }, { status: 400 }),
},
errorPolicy: extendInternalErrorPolicy(internalOrchestrationErrorPolicy, (error) =>
error instanceof NoWorkspaceAccessError
? internalErrorResponse(403, { error: 'Not a member of this workspace' })
: null
),
mapInput: ({ query }) => query,
useCase: readUserPermissionConfig,
})
15 changes: 14 additions & 1 deletion apps/sim/app/workspace/[workspaceId]/layout.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ const {
mockGetOrgWhitelabelSettings,
mockPrefetchWorkspaceHostContext,
mockPrefetchWorkspaceSidebar,
mockPrefetchWorkspaceAccess,
} = vi.hoisted(() => ({
mockBrandingProvider: vi.fn(({ children }: { children: ReactNode }) => children),
mockGetOrgWhitelabelSettings: vi.fn(),
mockPrefetchWorkspaceHostContext: vi.fn(),
mockPrefetchWorkspaceSidebar: vi.fn(),
mockPrefetchWorkspaceAccess: vi.fn(),
}))

vi.mock('@sim/emcn', () => ({
Expand Down Expand Up @@ -45,6 +47,10 @@ vi.mock('@/app/workspace/[workspaceId]/prefetch', () => ({
prefetchWorkspaceSidebar: mockPrefetchWorkspaceSidebar,
}))

vi.mock('@/app/workspace/[workspaceId]/prefetch-access', () => ({
prefetchWorkspaceAccess: mockPrefetchWorkspaceAccess,
}))

vi.mock('@/ee/whitelabeling/org-branding', () => ({
getOrgWhitelabelSettings: mockGetOrgWhitelabelSettings,
}))
Expand Down Expand Up @@ -146,10 +152,11 @@ describe('WorkspaceLayout host context', () => {
vi.clearAllMocks()
mockGetSession.mockResolvedValue({
user: { id: 'viewer-1' },
session: { activeOrganizationId: 'org-a' },
session: { id: 'session-1', activeOrganizationId: 'org-a' },
})
mockPrefetchWorkspaceHostContext.mockResolvedValue(HOST_CONTEXT)
mockPrefetchWorkspaceSidebar.mockResolvedValue(undefined)
mockPrefetchWorkspaceAccess.mockResolvedValue(undefined)
mockGetOrgWhitelabelSettings.mockResolvedValue({ brandName: 'Host B' })
})

Expand All @@ -169,6 +176,11 @@ describe('WorkspaceLayout host context', () => {
HOST_CONTEXT,
'org-a'
)
expect(mockPrefetchWorkspaceAccess).toHaveBeenCalledWith(expect.anything(), 'workspace-b', {
kind: 'session',
userId: 'viewer-1',
sessionId: 'session-1',
})
expect(mockBrandingProvider).toHaveBeenCalledWith(
expect.objectContaining({
hostOrganizationId: 'org-b',
Expand All @@ -191,6 +203,7 @@ describe('WorkspaceLayout host context', () => {
expect(html).toContain('Workspace access denied')
expect(html).not.toContain('Secret workspace child')
expect(mockPrefetchWorkspaceSidebar).not.toHaveBeenCalled()
expect(mockPrefetchWorkspaceAccess).not.toHaveBeenCalled()
expect(mockGetOrgWhitelabelSettings).not.toHaveBeenCalled()
})
})
6 changes: 6 additions & 0 deletions apps/sim/app/workspace/[workspaceId]/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
prefetchWorkspaceHostContext,
prefetchWorkspaceSidebar,
} from '@/app/workspace/[workspaceId]/prefetch'
import { prefetchWorkspaceAccess } from '@/app/workspace/[workspaceId]/prefetch-access'
import { BlockVisibilityLoader } from '@/app/workspace/[workspaceId]/providers/block-visibility-loader'
import { CustomBlocksLoader } from '@/app/workspace/[workspaceId]/providers/custom-blocks-loader'
import { DesktopOAuthConnectListener } from '@/app/workspace/[workspaceId]/providers/desktop-oauth-connect-listener'
Expand Down Expand Up @@ -60,6 +61,11 @@ export default async function WorkspaceLayout({
activeOrganizationId
),
isTableRowTtlEnabled(),
prefetchWorkspaceAccess(queryClient, workspaceId, {
Comment thread
waleedlatif1 marked this conversation as resolved.
kind: 'session',
userId: session.user.id,
sessionId: session.session.id,
}),
])
const initialSidebarCollapsed = cookieStore.get('sidebar_collapsed')?.value === '1'

Expand Down
Loading
Loading