Skip to content

Commit 76fa5b5

Browse files
authored
feat(mothership): expose owner entitlements to the workbench as SIM_ENTITLEMENTS (#10218)
* feat(mothership): expose owner entitlements to the workbench as SIM_ENTITLEMENTS The worker's workbench bootstrap reads SIM_ENTITLEMENTS so entitlement-gated CLI commands (workflows/workspaces source on workflow-code) appear in the workbench terminal. buildMothershipSandboxSession now takes the execution's principal and computes the turn owner's entitlements fresh per execution, in parallel with the scoped endpoint. Visibility only: gated use cases still re-check their flags, and a failed read omits the variable. * chore(workspace-source): drop unused imports and use template literals flagged by biome * fix(mothership): read workbench entitlements through a sim:workspaces delegation The Function execution's Copilot delegation is scoped to sim:function-executions, which the availability use cases refuse, so workspace chats never got SIM_ENTITLEMENTS. Re-scope the execution's own delegation (same actor, chat and delegation id, no longer lifetime) to sim:workspaces through the existing trusted Copilot principal helpers before computing entitlements; non-Copilot principals get none. Adds real-Postgres coverage through the real availability use cases.
1 parent bc8f09c commit 76fa5b5

9 files changed

Lines changed: 345 additions & 10 deletions

File tree

‎apps/sim/lib/function-execution/execute-request.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2397,6 +2397,7 @@ export async function executeFunctionRequest(
23972397
? { organizationId: admittedChatOwner.organizationId }
23982398
: { workspaceId }),
23992399
userId: auth.attributedUserId,
2400+
principal: auth.principal,
24002401
signal: executionSignal,
24012402
})
24022403
: undefined

‎apps/sim/lib/mothership/tools/handlers/workbench-confidentiality.live.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,10 @@ async function sandboxApi(path: string, handler: () => Promise<Response>, method
351351
return inResourceScope(async () => {
352352
const session = await buildMothershipSandboxSession({
353353
...scope,
354+
principal: createDelegatedPrincipal({
355+
subjectUserId: scope.userId,
356+
workspaceId: scope.workspaceId,
357+
}),
354358
sessionKey: chatSandboxSessionKey(chatId),
355359
})
356360
const endpoint = session.envs!.SIM_ENDPOINT
@@ -750,6 +754,10 @@ describe('persistent workbench output confidentiality', () => {
750754
await inResourceScope(async () => {
751755
const session = await buildMothershipSandboxSession({
752756
...scope,
757+
principal: createDelegatedPrincipal({
758+
subjectUserId: scope.userId,
759+
workspaceId: scope.workspaceId,
760+
}),
753761
sessionKey: chatSandboxSessionKey(chatId),
754762
})
755763
const credential = session.envs!.SIM_API_KEY
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
/**
2+
* Real PostgreSQL coverage for the workbench's `SIM_ENTITLEMENTS`: a Mothership Function
3+
* execution carries a Copilot delegation scoped to Function executions, and the availability use
4+
* cases behind each entitlement authorize it for real. Only the workbench transport (CLI bundle,
5+
* worker bootstrap, callback endpoint) and the AppConfig fetch are replaced.
6+
*/
7+
8+
import { db } from '@sim/db'
9+
import { member, organization, permissions, user, workspace } from '@sim/db/schema'
10+
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
11+
import { envFlagsMock, resetEnvFlagsMock, setEnvFlags } from '@sim/testing/mocks/env-flags.mock'
12+
import {
13+
mothershipAgentUrlMock,
14+
mothershipAgentUrlMockFns,
15+
} from '@sim/testing/mocks/mothership-agent-url.mock'
16+
import {
17+
mothershipGoFetchMock,
18+
mothershipGoFetchMockFns,
19+
} from '@sim/testing/mocks/mothership-go-fetch.mock'
20+
import { generateId } from '@sim/utils/id'
21+
import { inArray } from 'drizzle-orm'
22+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
23+
24+
const { mockFetchProfile } = vi.hoisted(() => ({ mockFetchProfile: vi.fn() }))
25+
26+
vi.mock('@/lib/core/config/env-flags', () => envFlagsMock)
27+
vi.mock('@/lib/core/config/appconfig', () => ({ fetchAppConfigProfile: mockFetchProfile }))
28+
vi.mock('node:fs/promises', () => ({ readFile: async () => 'runtime' }))
29+
vi.mock('@/lib/mothership/transport/connection', () => ({
30+
getSimConnection: () => ({ mode: 'direct' }),
31+
}))
32+
vi.mock('@/lib/mothership/request/go/fetch', () => mothershipGoFetchMock)
33+
vi.mock('@/lib/mothership/request/headers', () => ({ mothershipRequestHeaders: () => ({}) }))
34+
vi.mock('@/lib/mothership/server/agent-url', () => mothershipAgentUrlMock)
35+
vi.mock('@/lib/mothership/tools/sandbox-resources', () => ({
36+
sandboxResourceEndpoint: async (url: string) => `${url}/api/mothership/sandbox/owned-token`,
37+
activeSandboxChatOwner: () => undefined,
38+
activeSandboxFileOwnerProtocol: () => undefined,
39+
activeSandboxWorkspaceFileCopy: () => undefined,
40+
}))
41+
42+
import { FUNCTION_EXECUTION_DELEGATION_AUDIENCE } from '@/lib/function-execution/application/authorization'
43+
import { createTrustedOrganizationCopilotPrincipal } from '@/lib/mothership/auth/application-delegation'
44+
import { buildMothershipSandboxSession } from '@/lib/mothership/tools/sandbox-session'
45+
46+
const tenant = { orgId: generateId(), ownerId: generateId(), workspaceId: generateId() }
47+
const notRolledOut = { orgId: generateId(), ownerId: generateId(), workspaceId: generateId() }
48+
const tenants = [tenant, notRolledOut]
49+
const chatId = generateId()
50+
51+
/** The principal `lib/internal/function/execute.ts` builds for a workspace Copilot run. */
52+
function workspaceExecutionPrincipal(owner = tenant) {
53+
const issuedAt = new Date()
54+
return {
55+
kind: 'delegated' as const,
56+
serviceId: 'copilot' as const,
57+
subjectUserId: owner.ownerId,
58+
workspaceId: owner.workspaceId,
59+
delegationId: `function-execute:${generateId()}`,
60+
audience: FUNCTION_EXECUTION_DELEGATION_AUDIENCE,
61+
issuedAt,
62+
expiresAt: new Date(issuedAt.getTime() + 60_000),
63+
resourceScope: { executionId: generateId() },
64+
}
65+
}
66+
67+
describe('workbench entitlements for a Mothership Function execution', () => {
68+
beforeAll(async () => {
69+
setEnvFlags({ isAppConfigEnabled: true })
70+
mockFetchProfile.mockImplementation(async (_ids: unknown, parse: (doc: unknown) => unknown) =>
71+
parse({ 'workflow-code': { enabled: false, orgIds: [tenant.orgId] } })
72+
)
73+
mothershipAgentUrlMockFns.mockGetMothershipBaseURL.mockResolvedValue('https://worker.test')
74+
mothershipGoFetchMockFns.mockFetchGo.mockImplementation(async () =>
75+
Response.json({ version: 1, entrypoint: 'entry' })
76+
)
77+
const now = new Date()
78+
await db.insert(user).values(
79+
tenants.map((owner) => ({
80+
id: owner.ownerId,
81+
name: 'Sandbox entitlements fixture',
82+
email: `${owner.ownerId}@sandbox-entitlements.invalid`,
83+
emailVerified: true,
84+
createdAt: now,
85+
updatedAt: now,
86+
}))
87+
)
88+
await db.insert(organization).values(
89+
tenants.map((owner) => ({
90+
id: owner.orgId,
91+
name: 'Sandbox entitlements',
92+
slug: owner.orgId,
93+
createdAt: now,
94+
}))
95+
)
96+
await db.insert(member).values(
97+
tenants.map((owner) => ({
98+
id: generateId(),
99+
organizationId: owner.orgId,
100+
userId: owner.ownerId,
101+
role: 'owner',
102+
createdAt: now,
103+
}))
104+
)
105+
await insertWorkspaceFixture(
106+
db,
107+
tenants.map((owner) => ({
108+
id: owner.workspaceId,
109+
organizationId: owner.orgId,
110+
workspaceMode: 'organization' as const,
111+
name: 'Sandbox entitlements',
112+
ownerId: owner.ownerId,
113+
billedAccountUserId: owner.ownerId,
114+
}))
115+
)
116+
await db.insert(permissions).values(
117+
tenants.map((owner) => ({
118+
id: generateId(),
119+
userId: owner.ownerId,
120+
entityType: 'workspace' as const,
121+
entityId: owner.workspaceId,
122+
permissionType: 'admin' as const,
123+
}))
124+
)
125+
})
126+
127+
afterAll(async () => {
128+
const workspaceIds = tenants.map((owner) => owner.workspaceId)
129+
await db.delete(permissions).where(inArray(permissions.entityId, workspaceIds))
130+
await deleteWorkspaceFixture(db, inArray(workspace.id, workspaceIds))
131+
await db.delete(organization).where(
132+
inArray(
133+
organization.id,
134+
tenants.map((owner) => owner.orgId)
135+
)
136+
)
137+
await db.delete(user).where(
138+
inArray(
139+
user.id,
140+
tenants.map((owner) => owner.ownerId)
141+
)
142+
)
143+
resetEnvFlagsMock()
144+
})
145+
146+
it('grants a workspace chat workflow-code through its Function delegation', async () => {
147+
const session = await buildMothershipSandboxSession({
148+
sessionKey: chatId,
149+
workspaceId: tenant.workspaceId,
150+
userId: tenant.ownerId,
151+
principal: workspaceExecutionPrincipal(),
152+
})
153+
expect(session.envs?.SIM_WORKSPACE).toBe(tenant.workspaceId)
154+
expect((session.envs?.SIM_ENTITLEMENTS ?? '').split(',')).toContain('workflow-code')
155+
})
156+
157+
it('grants an organization chat workflow-code through its Function delegation', async () => {
158+
const session = await buildMothershipSandboxSession({
159+
sessionKey: chatId,
160+
organizationId: tenant.orgId,
161+
userId: tenant.ownerId,
162+
principal: createTrustedOrganizationCopilotPrincipal(
163+
{
164+
userId: tenant.ownerId,
165+
organizationId: tenant.orgId,
166+
chatId,
167+
delegationId: `function-execute:${generateId()}`,
168+
},
169+
{ audience: FUNCTION_EXECUTION_DELEGATION_AUDIENCE, ttlMs: 60_000 }
170+
),
171+
})
172+
expect(session.envs?.SIM_ORGANIZATION_ID).toBe(tenant.orgId)
173+
expect((session.envs?.SIM_ENTITLEMENTS ?? '').split(',')).toContain('workflow-code')
174+
})
175+
176+
it('omits workflow-code where the workspace is not rolled out', async () => {
177+
const session = await buildMothershipSandboxSession({
178+
sessionKey: chatId,
179+
workspaceId: notRolledOut.workspaceId,
180+
userId: notRolledOut.ownerId,
181+
principal: workspaceExecutionPrincipal(notRolledOut),
182+
})
183+
expect(session.envs?.SIM_WORKSPACE).toBe(notRolledOut.workspaceId)
184+
expect(session.envs?.SIM_ENTITLEMENTS ?? '').not.toContain('workflow-code')
185+
})
186+
})

‎apps/sim/lib/mothership/tools/sandbox-session.test.ts‎

Lines changed: 67 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { createDelegatedPrincipal } from '@sim/testing/factories/principal.factory'
12
import { setEnv } from '@sim/testing/mocks/env.mock'
23
import {
34
mothershipAgentUrlMock,
@@ -10,8 +11,9 @@ import {
1011
import { urlsMockFns } from '@sim/testing/mocks/urls.mock'
1112
import { beforeEach, describe, expect, it, vi } from 'vitest'
1213

13-
const { read, mint, connection, endpoint, workspaceFileCopy } = vi.hoisted(() => ({
14+
const { read, mint, connection, endpoint, workspaceFileCopy, entitlements } = vi.hoisted(() => ({
1415
connection: vi.fn(),
16+
entitlements: vi.fn(),
1517
endpoint: vi.fn(),
1618
read: vi.fn(),
1719
mint: vi.fn(),
@@ -25,7 +27,9 @@ vi.mock('@/lib/mothership/request/headers', () => ({
2527
mothershipRequestHeaders: () => ({ 'x-api-key': 'worker-test-key' }),
2628
}))
2729
vi.mock('@/lib/mothership/server/agent-url', () => mothershipAgentUrlMock)
30+
vi.mock('@/lib/mothership/entitlements', () => ({ computeEntitlements: entitlements }))
2831

32+
import { createTrustedOrganizationCopilotPrincipal } from '@/lib/mothership/auth/application-delegation'
2933
import { buildMothershipSandboxSession } from '@/lib/mothership/tools/sandbox-session'
3034

3135
const fetchBootstrap = mothershipGoFetchMockFns.mockFetchGo
@@ -34,13 +38,19 @@ const baseURL = mothershipAgentUrlMockFns.mockGetMothershipBaseURL
3438
urlsMockFns.mockGetBaseUrl.mockReturnValue('https://unused.test')
3539
setEnv({ MOTHERSHIP_SANDBOX_CLI_ENDPOINT: 'https://sim.test', ENCRYPTION_KEY: 'a'.repeat(64) })
3640

37-
const request = { sessionKey: 'chat', workspaceId: 'workspace', userId: 'user' }
41+
const principal = createDelegatedPrincipal({
42+
subjectUserId: 'user',
43+
workspaceId: 'workspace',
44+
audience: 'sim:function-executions',
45+
})
46+
const request = { sessionKey: 'chat', workspaceId: 'workspace', userId: 'user', principal }
3847

3948
describe('deployment-owned workbench tooling', () => {
4049
beforeEach(() => {
4150
vi.resetAllMocks()
4251
connection.mockReturnValue({ mode: 'direct' })
4352
mint.mockResolvedValue('test-delegation')
53+
entitlements.mockResolvedValue([])
4454
endpoint.mockImplementation(async (url) => `${url}/api/mothership/sandbox/owned-token`)
4555
baseURL.mockResolvedValue('https://worker.test')
4656
fetchBootstrap.mockImplementation(async () =>
@@ -94,6 +104,61 @@ describe('deployment-owned workbench tooling', () => {
94104
expect(session.envs).not.toHaveProperty('SIM_FILE_OWNER_PROTOCOL')
95105
})
96106

107+
it('exposes the owner entitlements computed for this execution to the workbench CLI', async () => {
108+
read.mockResolvedValue('bundle')
109+
entitlements
110+
.mockResolvedValueOnce(['dashboards', 'workflow-code'])
111+
.mockResolvedValueOnce(['dashboards'])
112+
const first = await buildMothershipSandboxSession(request)
113+
const second = await buildMothershipSandboxSession(request)
114+
expect(first.envs).toMatchObject({ SIM_ENTITLEMENTS: 'dashboards,workflow-code' })
115+
expect(second.envs).toMatchObject({ SIM_ENTITLEMENTS: 'dashboards' })
116+
expect(entitlements).toHaveBeenCalledWith(
117+
expect.objectContaining({
118+
principal: expect.objectContaining({
119+
subjectUserId: 'user',
120+
workspaceId: 'workspace',
121+
delegationId: principal.delegationId,
122+
audience: 'sim:workspaces',
123+
}),
124+
workspaceId: 'workspace',
125+
})
126+
)
127+
})
128+
129+
it('scopes organization chat entitlements to the organization', async () => {
130+
read.mockResolvedValue('bundle')
131+
entitlements.mockResolvedValue(['workflow-code'])
132+
const session = await buildMothershipSandboxSession({
133+
sessionKey: 'chat',
134+
organizationId: 'org',
135+
userId: 'user',
136+
principal: createTrustedOrganizationCopilotPrincipal(
137+
{ userId: 'user', organizationId: 'org', chatId: 'chat', delegationId: 'run' },
138+
{ audience: 'sim:function-executions', ttlMs: 60_000 }
139+
),
140+
})
141+
expect(session.envs).toMatchObject({
142+
SIM_ORGANIZATION_ID: 'org',
143+
SIM_ENTITLEMENTS: 'workflow-code',
144+
})
145+
expect(entitlements.mock.calls[0][0]).toMatchObject({
146+
principal: { organizationId: 'org', delegationId: 'run', audience: 'sim:workspaces' },
147+
workspaceId: undefined,
148+
})
149+
})
150+
151+
it('omits SIM_ENTITLEMENTS when none are granted or they cannot be read', async () => {
152+
read.mockResolvedValue('bundle')
153+
expect((await buildMothershipSandboxSession(request)).envs).not.toHaveProperty(
154+
'SIM_ENTITLEMENTS'
155+
)
156+
entitlements.mockRejectedValueOnce(new Error('flag store down'))
157+
const degraded = await buildMothershipSandboxSession(request)
158+
expect(degraded.envs).toMatchObject({ SIM_WORKSPACE: 'workspace' })
159+
expect(degraded.envs).not.toHaveProperty('SIM_ENTITLEMENTS')
160+
})
161+
97162
it('refuses setup when the deployment artifact is missing instead of fetching another CLI release', async () => {
98163
read.mockRejectedValue(new Error('missing workbench bundle'))
99164
await expect(buildMothershipSandboxSession(request)).rejects.toThrow('missing workbench bundle')

0 commit comments

Comments
 (0)