-
Notifications
You must be signed in to change notification settings - Fork 3.9k
fix(workspace): hydrate access policy before rendering chat #7875
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.