Skip to content

Commit eeb971f

Browse files
committed
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.
1 parent bc8f09c commit eeb971f

4 files changed

Lines changed: 89 additions & 4 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

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

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { createSessionPrincipal } 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,6 +27,7 @@ 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

2932
import { buildMothershipSandboxSession } from '@/lib/mothership/tools/sandbox-session'
3033

@@ -34,13 +37,15 @@ const baseURL = mothershipAgentUrlMockFns.mockGetMothershipBaseURL
3437
urlsMockFns.mockGetBaseUrl.mockReturnValue('https://unused.test')
3538
setEnv({ MOTHERSHIP_SANDBOX_CLI_ENDPOINT: 'https://sim.test', ENCRYPTION_KEY: 'a'.repeat(64) })
3639

37-
const request = { sessionKey: 'chat', workspaceId: 'workspace', userId: 'user' }
40+
const principal = createSessionPrincipal({ userId: 'user' })
41+
const request = { sessionKey: 'chat', workspaceId: 'workspace', userId: 'user', principal }
3842

3943
describe('deployment-owned workbench tooling', () => {
4044
beforeEach(() => {
4145
vi.resetAllMocks()
4246
connection.mockReturnValue({ mode: 'direct' })
4347
mint.mockResolvedValue('test-delegation')
48+
entitlements.mockResolvedValue([])
4449
endpoint.mockImplementation(async (url) => `${url}/api/mothership/sandbox/owned-token`)
4550
baseURL.mockResolvedValue('https://worker.test')
4651
fetchBootstrap.mockImplementation(async () =>
@@ -94,6 +99,47 @@ describe('deployment-owned workbench tooling', () => {
9499
expect(session.envs).not.toHaveProperty('SIM_FILE_OWNER_PROTOCOL')
95100
})
96101

102+
it('exposes the owner entitlements computed for this execution to the workbench CLI', async () => {
103+
read.mockResolvedValue('bundle')
104+
entitlements
105+
.mockResolvedValueOnce(['dashboards', 'workflow-code'])
106+
.mockResolvedValueOnce(['dashboards'])
107+
const first = await buildMothershipSandboxSession(request)
108+
const second = await buildMothershipSandboxSession(request)
109+
expect(first.envs).toMatchObject({ SIM_ENTITLEMENTS: 'dashboards,workflow-code' })
110+
expect(second.envs).toMatchObject({ SIM_ENTITLEMENTS: 'dashboards' })
111+
expect(entitlements).toHaveBeenCalledWith(
112+
expect.objectContaining({ principal, workspaceId: 'workspace' })
113+
)
114+
})
115+
116+
it('scopes organization chat entitlements to the organization', async () => {
117+
read.mockResolvedValue('bundle')
118+
entitlements.mockResolvedValue(['workflow-code'])
119+
const session = await buildMothershipSandboxSession({
120+
sessionKey: 'chat',
121+
organizationId: 'org',
122+
userId: 'user',
123+
principal,
124+
})
125+
expect(session.envs).toMatchObject({
126+
SIM_ORGANIZATION_ID: 'org',
127+
SIM_ENTITLEMENTS: 'workflow-code',
128+
})
129+
expect(entitlements.mock.calls[0][0]).not.toHaveProperty('workspaceId')
130+
})
131+
132+
it('omits SIM_ENTITLEMENTS when none are granted or they cannot be read', async () => {
133+
read.mockResolvedValue('bundle')
134+
expect((await buildMothershipSandboxSession(request)).envs).not.toHaveProperty(
135+
'SIM_ENTITLEMENTS'
136+
)
137+
entitlements.mockRejectedValueOnce(new Error('flag store down'))
138+
const degraded = await buildMothershipSandboxSession(request)
139+
expect(degraded.envs).toMatchObject({ SIM_WORKSPACE: 'workspace' })
140+
expect(degraded.envs).not.toHaveProperty('SIM_ENTITLEMENTS')
141+
})
142+
97143
it('refuses setup when the deployment artifact is missing instead of fetching another CLI release', async () => {
98144
read.mockRejectedValue(new Error('missing workbench bundle'))
99145
await expect(buildMothershipSandboxSession(request)).rejects.toThrow('missing workbench bundle')

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

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { createHash } from 'node:crypto'
22
import { readFile } from 'node:fs/promises'
33
import { resolve } from 'node:path'
4+
import type { Principal } from '@sim/auth/principal'
45
import { createLogger } from '@sim/logger'
56
import { getErrorMessage } from '@sim/utils/errors'
67
import { generateId } from '@sim/utils/id'
@@ -13,6 +14,7 @@ import {
1314
EXACT_EMPTY_DURABLE_SECRET_PROVENANCE,
1415
} from '@/lib/execution/durable-secret-provenance'
1516
import type { SandboxSessionRequest } from '@/lib/execution/remote-sandbox/types'
17+
import { computeEntitlements } from '@/lib/mothership/entitlements'
1618
import { WorkbenchBootstrap } from '@/lib/mothership/generated/workbench'
1719
import { fetchGo } from '@/lib/mothership/request/go/fetch'
1820
import { mothershipRequestHeaders } from '@/lib/mothership/request/headers'
@@ -102,11 +104,34 @@ async function workbenchCli(
102104
}
103105
}
104106

107+
/**
108+
* The owner's entitlements, read fresh for each execution, for the workbench CLI's
109+
* `SIM_ENTITLEMENTS`. Visibility only: each gated use case re-checks its flag, so a
110+
* failed read hides the gated commands rather than failing the execution.
111+
*/
112+
async function sandboxEntitlements(args: {
113+
principal: Principal
114+
workspaceId?: string
115+
organizationId?: string
116+
}): Promise<string> {
117+
try {
118+
return (await computeEntitlements(args)).join(',')
119+
} catch (error) {
120+
logger.warn('Session sandbox entitlements unavailable', {
121+
workspaceId: args.workspaceId,
122+
organizationId: args.organizationId,
123+
error: getErrorMessage(error),
124+
})
125+
return ''
126+
}
127+
}
128+
105129
/**
106130
* Builds the session request for a Mothership chat's persistent sandbox: the
107131
* per-chat identity, the sim-CLI bootstrap, and the CLI's headless auth
108132
* environment (`SIM_API_KEY`/`SIM_WORKSPACE`/`SIM_ENDPOINT`, the CLI's
109-
* documented CI path). Only an opaque callback credential enters the workbench;
133+
* documented CI path), plus the owner's `SIM_ENTITLEMENTS` so entitlement-gated
134+
* CLI commands are visible. Only an opaque callback credential enters the workbench;
110135
* the active tool lease resolves the real user credential on the server. The
111136
* opaque credential cannot authenticate directly to ordinary v2 routes.
112137
*
@@ -119,6 +144,7 @@ export async function buildMothershipSandboxSession(args: {
119144
workspaceId?: string
120145
organizationId?: string
121146
userId: string
147+
principal: Principal
122148
signal?: AbortSignal
123149
}): Promise<SandboxSessionRequest> {
124150
args.signal?.throwIfAborted()
@@ -129,7 +155,10 @@ export async function buildMothershipSandboxSession(args: {
129155
try {
130156
const apiKey = `mothership-sandbox:${generateId()}`
131157
const endpoint = env.MOTHERSHIP_SANDBOX_CLI_ENDPOINT?.trim() || getBaseUrl()
132-
const scopedEndpoint = await sandboxResourceEndpoint(endpoint, args, apiKey)
158+
const [scopedEndpoint, entitlements] = await Promise.all([
159+
sandboxResourceEndpoint(endpoint, args, apiKey),
160+
sandboxEntitlements(args),
161+
])
133162
if (scopedEndpoint !== endpoint) {
134163
const provenance: DurableSecretProvenance = {
135164
status: 'exact',
@@ -155,6 +184,7 @@ export async function buildMothershipSandboxSession(args: {
155184
SIM_ENDPOINT: scopedEndpoint,
156185
...(activeSandboxFileOwnerProtocol() === 1 ? { SIM_FILE_OWNER_PROTOCOL: '1' } : {}),
157186
...(activeSandboxWorkspaceFileCopy() ? { SIM_WORKSPACE_FILE_COPY: '1' } : {}),
187+
...(entitlements ? { SIM_ENTITLEMENTS: entitlements } : {}),
158188
}
159189
}
160190
} catch (error) {

0 commit comments

Comments
 (0)