Skip to content

Commit 268f70c

Browse files
committed
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 be2ac7f commit 268f70c

3 files changed

Lines changed: 263 additions & 9 deletions

File tree

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: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { createSessionPrincipal } from '@sim/testing/factories/principal.factory'
1+
import { createDelegatedPrincipal } from '@sim/testing/factories/principal.factory'
22
import { setEnv } from '@sim/testing/mocks/env.mock'
33
import {
44
mothershipAgentUrlMock,
@@ -29,6 +29,7 @@ vi.mock('@/lib/mothership/request/headers', () => ({
2929
vi.mock('@/lib/mothership/server/agent-url', () => mothershipAgentUrlMock)
3030
vi.mock('@/lib/mothership/entitlements', () => ({ computeEntitlements: entitlements }))
3131

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

3435
const fetchBootstrap = mothershipGoFetchMockFns.mockFetchGo
@@ -37,7 +38,11 @@ const baseURL = mothershipAgentUrlMockFns.mockGetMothershipBaseURL
3738
urlsMockFns.mockGetBaseUrl.mockReturnValue('https://unused.test')
3839
setEnv({ MOTHERSHIP_SANDBOX_CLI_ENDPOINT: 'https://sim.test', ENCRYPTION_KEY: 'a'.repeat(64) })
3940

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

4348
describe('deployment-owned workbench tooling', () => {
@@ -109,7 +114,15 @@ describe('deployment-owned workbench tooling', () => {
109114
expect(first.envs).toMatchObject({ SIM_ENTITLEMENTS: 'dashboards,workflow-code' })
110115
expect(second.envs).toMatchObject({ SIM_ENTITLEMENTS: 'dashboards' })
111116
expect(entitlements).toHaveBeenCalledWith(
112-
expect.objectContaining({ principal, workspaceId: 'workspace' })
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+
})
113126
)
114127
})
115128

@@ -120,13 +133,19 @@ describe('deployment-owned workbench tooling', () => {
120133
sessionKey: 'chat',
121134
organizationId: 'org',
122135
userId: 'user',
123-
principal,
136+
principal: createTrustedOrganizationCopilotPrincipal(
137+
{ userId: 'user', organizationId: 'org', chatId: 'chat', delegationId: 'run' },
138+
{ audience: 'sim:function-executions', ttlMs: 60_000 }
139+
),
124140
})
125141
expect(session.envs).toMatchObject({
126142
SIM_ORGANIZATION_ID: 'org',
127143
SIM_ENTITLEMENTS: 'workflow-code',
128144
})
129-
expect(entitlements.mock.calls[0][0]).not.toHaveProperty('workspaceId')
145+
expect(entitlements.mock.calls[0][0]).toMatchObject({
146+
principal: { organizationId: 'org', delegationId: 'run', audience: 'sim:workspaces' },
147+
workspaceId: undefined,
148+
})
130149
})
131150

132151
it('omits SIM_ENTITLEMENTS when none are granted or they cannot be read', async () => {

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

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +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'
4+
import type { DelegatedPrincipal, OrganizationDelegatedPrincipal } from '@sim/auth/principal'
55
import { createLogger } from '@sim/logger'
66
import { getErrorMessage } from '@sim/utils/errors'
77
import { generateId } from '@sim/utils/id'
@@ -14,6 +14,11 @@ import {
1414
EXACT_EMPTY_DURABLE_SECRET_PROVENANCE,
1515
} from '@/lib/execution/durable-secret-provenance'
1616
import type { SandboxSessionRequest } from '@/lib/execution/remote-sandbox/types'
17+
import {
18+
COPILOT_APPLICATION_DELEGATION_TTL_MS,
19+
createTrustedCopilotPrincipal,
20+
createTrustedOrganizationCopilotPrincipal,
21+
} from '@/lib/mothership/auth/application-delegation'
1722
import { computeEntitlements } from '@/lib/mothership/entitlements'
1823
import { WorkbenchBootstrap } from '@/lib/mothership/generated/workbench'
1924
import { fetchGo } from '@/lib/mothership/request/go/fetch'
@@ -104,18 +109,62 @@ async function workbenchCli(
104109
}
105110
}
106111

112+
type ExecutionPrincipal = DelegatedPrincipal | OrganizationDelegatedPrincipal
113+
114+
/**
115+
* The execution's own Copilot delegation, re-scoped from the Function audience to the
116+
* `sim:workspaces` audience the availability use cases accept. Same actor, chat and delegation,
117+
* never a longer lifetime; any other service keeps its principal and is refused there.
118+
*/
119+
function workspacesDelegation(principal: ExecutionPrincipal): ExecutionPrincipal | null {
120+
if (principal.serviceId !== 'copilot') return null
121+
const options = {
122+
audience: 'sim:workspaces',
123+
ttlMs: Math.max(
124+
1,
125+
Math.min(COPILOT_APPLICATION_DELEGATION_TTL_MS, principal.expiresAt.getTime() - Date.now())
126+
),
127+
}
128+
const chatId = principal.resourceScope?.chatId
129+
if (principal.kind === 'organization_delegated') {
130+
if (!chatId) return null
131+
return createTrustedOrganizationCopilotPrincipal(
132+
{
133+
userId: principal.subjectUserId,
134+
organizationId: principal.organizationId,
135+
chatId,
136+
delegationId: principal.delegationId,
137+
},
138+
options
139+
)
140+
}
141+
return createTrustedCopilotPrincipal(
142+
{
143+
userId: principal.subjectUserId,
144+
workspaceId: principal.workspaceId,
145+
delegationId: principal.delegationId,
146+
chatId,
147+
executionId: principal.resourceScope?.executionId,
148+
},
149+
options
150+
)
151+
}
152+
107153
/**
108154
* The owner's entitlements, read fresh for each execution, for the workbench CLI's
109155
* `SIM_ENTITLEMENTS`. Visibility only: each gated use case re-checks its flag, so a
110156
* failed read hides the gated commands rather than failing the execution.
111157
*/
112158
async function sandboxEntitlements(args: {
113-
principal: Principal
159+
principal: ExecutionPrincipal
114160
workspaceId?: string
115161
organizationId?: string
116162
}): Promise<string> {
117163
try {
118-
return (await computeEntitlements(args)).join(',')
164+
const principal = workspacesDelegation(args.principal)
165+
if (!principal) return ''
166+
const { workspaceId, organizationId } = args
167+
return (await computeEntitlements({ principal, workspaceId, organizationId })).join(',')
119168
} catch (error) {
120169
logger.warn('Session sandbox entitlements unavailable', {
121170
workspaceId: args.workspaceId,
@@ -144,7 +193,7 @@ export async function buildMothershipSandboxSession(args: {
144193
workspaceId?: string
145194
organizationId?: string
146195
userId: string
147-
principal: Principal
196+
principal: ExecutionPrincipal
148197
signal?: AbortSignal
149198
}): Promise<SandboxSessionRequest> {
150199
args.signal?.throwIfAborted()

0 commit comments

Comments
 (0)