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
1 change: 1 addition & 0 deletions apps/sim/lib/function-execution/execute-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2397,6 +2397,7 @@ export async function executeFunctionRequest(
? { organizationId: admittedChatOwner.organizationId }
: { workspaceId }),
userId: auth.attributedUserId,
principal: auth.principal,
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
signal: executionSignal,
})
: undefined
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,10 @@ async function sandboxApi(path: string, handler: () => Promise<Response>, method
return inResourceScope(async () => {
const session = await buildMothershipSandboxSession({
...scope,
principal: createDelegatedPrincipal({
subjectUserId: scope.userId,
workspaceId: scope.workspaceId,
}),
sessionKey: chatSandboxSessionKey(chatId),
})
const endpoint = session.envs!.SIM_ENDPOINT
Expand Down Expand Up @@ -750,6 +754,10 @@ describe('persistent workbench output confidentiality', () => {
await inResourceScope(async () => {
const session = await buildMothershipSandboxSession({
...scope,
principal: createDelegatedPrincipal({
subjectUserId: scope.userId,
workspaceId: scope.workspaceId,
}),
sessionKey: chatSandboxSessionKey(chatId),
})
const credential = session.envs!.SIM_API_KEY
Expand Down
186 changes: 186 additions & 0 deletions apps/sim/lib/mothership/tools/sandbox-session.integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
/**
* Real PostgreSQL coverage for the workbench's `SIM_ENTITLEMENTS`: a Mothership Function
* execution carries a Copilot delegation scoped to Function executions, and the availability use
* cases behind each entitlement authorize it for real. Only the workbench transport (CLI bundle,
* worker bootstrap, callback endpoint) and the AppConfig fetch are replaced.
*/

import { db } from '@sim/db'
import { member, organization, permissions, user, workspace } from '@sim/db/schema'
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
import { envFlagsMock, resetEnvFlagsMock, setEnvFlags } from '@sim/testing/mocks/env-flags.mock'
import {
mothershipAgentUrlMock,
mothershipAgentUrlMockFns,
} from '@sim/testing/mocks/mothership-agent-url.mock'
import {
mothershipGoFetchMock,
mothershipGoFetchMockFns,
} from '@sim/testing/mocks/mothership-go-fetch.mock'
import { generateId } from '@sim/utils/id'
import { inArray } from 'drizzle-orm'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'

const { mockFetchProfile } = vi.hoisted(() => ({ mockFetchProfile: vi.fn() }))

vi.mock('@/lib/core/config/env-flags', () => envFlagsMock)
vi.mock('@/lib/core/config/appconfig', () => ({ fetchAppConfigProfile: mockFetchProfile }))
vi.mock('node:fs/promises', () => ({ readFile: async () => 'runtime' }))
vi.mock('@/lib/mothership/transport/connection', () => ({
getSimConnection: () => ({ mode: 'direct' }),
}))
vi.mock('@/lib/mothership/request/go/fetch', () => mothershipGoFetchMock)
vi.mock('@/lib/mothership/request/headers', () => ({ mothershipRequestHeaders: () => ({}) }))
vi.mock('@/lib/mothership/server/agent-url', () => mothershipAgentUrlMock)
vi.mock('@/lib/mothership/tools/sandbox-resources', () => ({
sandboxResourceEndpoint: async (url: string) => `${url}/api/mothership/sandbox/owned-token`,
activeSandboxChatOwner: () => undefined,
activeSandboxFileOwnerProtocol: () => undefined,
activeSandboxWorkspaceFileCopy: () => undefined,
}))

import { FUNCTION_EXECUTION_DELEGATION_AUDIENCE } from '@/lib/function-execution/application/authorization'
import { createTrustedOrganizationCopilotPrincipal } from '@/lib/mothership/auth/application-delegation'
import { buildMothershipSandboxSession } from '@/lib/mothership/tools/sandbox-session'

const tenant = { orgId: generateId(), ownerId: generateId(), workspaceId: generateId() }
const notRolledOut = { orgId: generateId(), ownerId: generateId(), workspaceId: generateId() }
const tenants = [tenant, notRolledOut]
const chatId = generateId()

/** The principal `lib/internal/function/execute.ts` builds for a workspace Copilot run. */
function workspaceExecutionPrincipal(owner = tenant) {
const issuedAt = new Date()
return {
kind: 'delegated' as const,
serviceId: 'copilot' as const,
subjectUserId: owner.ownerId,
workspaceId: owner.workspaceId,
delegationId: `function-execute:${generateId()}`,
audience: FUNCTION_EXECUTION_DELEGATION_AUDIENCE,
issuedAt,
expiresAt: new Date(issuedAt.getTime() + 60_000),
resourceScope: { executionId: generateId() },
}
}

describe('workbench entitlements for a Mothership Function execution', () => {
beforeAll(async () => {
setEnvFlags({ isAppConfigEnabled: true })
mockFetchProfile.mockImplementation(async (_ids: unknown, parse: (doc: unknown) => unknown) =>
parse({ 'workflow-code': { enabled: false, orgIds: [tenant.orgId] } })
)
mothershipAgentUrlMockFns.mockGetMothershipBaseURL.mockResolvedValue('https://worker.test')
mothershipGoFetchMockFns.mockFetchGo.mockImplementation(async () =>
Response.json({ version: 1, entrypoint: 'entry' })
)
const now = new Date()
await db.insert(user).values(
tenants.map((owner) => ({
id: owner.ownerId,
name: 'Sandbox entitlements fixture',
email: `${owner.ownerId}@sandbox-entitlements.invalid`,
emailVerified: true,
createdAt: now,
updatedAt: now,
}))
)
await db.insert(organization).values(
tenants.map((owner) => ({
id: owner.orgId,
name: 'Sandbox entitlements',
slug: owner.orgId,
createdAt: now,
}))
)
await db.insert(member).values(
tenants.map((owner) => ({
id: generateId(),
organizationId: owner.orgId,
userId: owner.ownerId,
role: 'owner',
createdAt: now,
}))
)
await insertWorkspaceFixture(
db,
tenants.map((owner) => ({
id: owner.workspaceId,
organizationId: owner.orgId,
workspaceMode: 'organization' as const,
name: 'Sandbox entitlements',
ownerId: owner.ownerId,
billedAccountUserId: owner.ownerId,
}))
)
await db.insert(permissions).values(
tenants.map((owner) => ({
id: generateId(),
userId: owner.ownerId,
entityType: 'workspace' as const,
entityId: owner.workspaceId,
permissionType: 'admin' as const,
}))
)
})

afterAll(async () => {
const workspaceIds = tenants.map((owner) => owner.workspaceId)
await db.delete(permissions).where(inArray(permissions.entityId, workspaceIds))
await deleteWorkspaceFixture(db, inArray(workspace.id, workspaceIds))
await db.delete(organization).where(
inArray(
organization.id,
tenants.map((owner) => owner.orgId)
)
)
await db.delete(user).where(
inArray(
user.id,
tenants.map((owner) => owner.ownerId)
)
)
resetEnvFlagsMock()
})

it('grants a workspace chat workflow-code through its Function delegation', async () => {
const session = await buildMothershipSandboxSession({
sessionKey: chatId,
workspaceId: tenant.workspaceId,
userId: tenant.ownerId,
principal: workspaceExecutionPrincipal(),
})
expect(session.envs?.SIM_WORKSPACE).toBe(tenant.workspaceId)
expect((session.envs?.SIM_ENTITLEMENTS ?? '').split(',')).toContain('workflow-code')
})

it('grants an organization chat workflow-code through its Function delegation', async () => {
const session = await buildMothershipSandboxSession({
sessionKey: chatId,
organizationId: tenant.orgId,
userId: tenant.ownerId,
principal: createTrustedOrganizationCopilotPrincipal(
{
userId: tenant.ownerId,
organizationId: tenant.orgId,
chatId,
delegationId: `function-execute:${generateId()}`,
},
{ audience: FUNCTION_EXECUTION_DELEGATION_AUDIENCE, ttlMs: 60_000 }
),
})
expect(session.envs?.SIM_ORGANIZATION_ID).toBe(tenant.orgId)
expect((session.envs?.SIM_ENTITLEMENTS ?? '').split(',')).toContain('workflow-code')
})

it('omits workflow-code where the workspace is not rolled out', async () => {
const session = await buildMothershipSandboxSession({
sessionKey: chatId,
workspaceId: notRolledOut.workspaceId,
userId: notRolledOut.ownerId,
principal: workspaceExecutionPrincipal(notRolledOut),
})
expect(session.envs?.SIM_WORKSPACE).toBe(notRolledOut.workspaceId)
expect(session.envs?.SIM_ENTITLEMENTS ?? '').not.toContain('workflow-code')
})
})
69 changes: 67 additions & 2 deletions apps/sim/lib/mothership/tools/sandbox-session.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createDelegatedPrincipal } from '@sim/testing/factories/principal.factory'
import { setEnv } from '@sim/testing/mocks/env.mock'
import {
mothershipAgentUrlMock,
Expand All @@ -10,8 +11,9 @@ import {
import { urlsMockFns } from '@sim/testing/mocks/urls.mock'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const { read, mint, connection, endpoint, workspaceFileCopy } = vi.hoisted(() => ({
const { read, mint, connection, endpoint, workspaceFileCopy, entitlements } = vi.hoisted(() => ({
connection: vi.fn(),
entitlements: vi.fn(),
endpoint: vi.fn(),
read: vi.fn(),
mint: vi.fn(),
Expand All @@ -25,7 +27,9 @@ vi.mock('@/lib/mothership/request/headers', () => ({
mothershipRequestHeaders: () => ({ 'x-api-key': 'worker-test-key' }),
}))
vi.mock('@/lib/mothership/server/agent-url', () => mothershipAgentUrlMock)
vi.mock('@/lib/mothership/entitlements', () => ({ computeEntitlements: entitlements }))

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

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

const request = { sessionKey: 'chat', workspaceId: 'workspace', userId: 'user' }
const principal = createDelegatedPrincipal({
subjectUserId: 'user',
workspaceId: 'workspace',
audience: 'sim:function-executions',
})
const request = { sessionKey: 'chat', workspaceId: 'workspace', userId: 'user', principal }

describe('deployment-owned workbench tooling', () => {
beforeEach(() => {
vi.resetAllMocks()
connection.mockReturnValue({ mode: 'direct' })
mint.mockResolvedValue('test-delegation')
entitlements.mockResolvedValue([])
endpoint.mockImplementation(async (url) => `${url}/api/mothership/sandbox/owned-token`)
baseURL.mockResolvedValue('https://worker.test')
fetchBootstrap.mockImplementation(async () =>
Expand Down Expand Up @@ -94,6 +104,61 @@ describe('deployment-owned workbench tooling', () => {
expect(session.envs).not.toHaveProperty('SIM_FILE_OWNER_PROTOCOL')
})

it('exposes the owner entitlements computed for this execution to the workbench CLI', async () => {
read.mockResolvedValue('bundle')
entitlements
.mockResolvedValueOnce(['dashboards', 'workflow-code'])
.mockResolvedValueOnce(['dashboards'])
const first = await buildMothershipSandboxSession(request)
const second = await buildMothershipSandboxSession(request)
expect(first.envs).toMatchObject({ SIM_ENTITLEMENTS: 'dashboards,workflow-code' })
expect(second.envs).toMatchObject({ SIM_ENTITLEMENTS: 'dashboards' })
expect(entitlements).toHaveBeenCalledWith(
expect.objectContaining({
principal: expect.objectContaining({
subjectUserId: 'user',
workspaceId: 'workspace',
delegationId: principal.delegationId,
audience: 'sim:workspaces',
}),
workspaceId: 'workspace',
})
)
})

it('scopes organization chat entitlements to the organization', async () => {
read.mockResolvedValue('bundle')
entitlements.mockResolvedValue(['workflow-code'])
const session = await buildMothershipSandboxSession({
sessionKey: 'chat',
organizationId: 'org',
userId: 'user',
principal: createTrustedOrganizationCopilotPrincipal(
{ userId: 'user', organizationId: 'org', chatId: 'chat', delegationId: 'run' },
{ audience: 'sim:function-executions', ttlMs: 60_000 }
),
})
expect(session.envs).toMatchObject({
SIM_ORGANIZATION_ID: 'org',
SIM_ENTITLEMENTS: 'workflow-code',
})
expect(entitlements.mock.calls[0][0]).toMatchObject({
principal: { organizationId: 'org', delegationId: 'run', audience: 'sim:workspaces' },
workspaceId: undefined,
})
})

it('omits SIM_ENTITLEMENTS when none are granted or they cannot be read', async () => {
read.mockResolvedValue('bundle')
expect((await buildMothershipSandboxSession(request)).envs).not.toHaveProperty(
'SIM_ENTITLEMENTS'
)
entitlements.mockRejectedValueOnce(new Error('flag store down'))
const degraded = await buildMothershipSandboxSession(request)
expect(degraded.envs).toMatchObject({ SIM_WORKSPACE: 'workspace' })
expect(degraded.envs).not.toHaveProperty('SIM_ENTITLEMENTS')
})

it('refuses setup when the deployment artifact is missing instead of fetching another CLI release', async () => {
read.mockRejectedValue(new Error('missing workbench bundle'))
await expect(buildMothershipSandboxSession(request)).rejects.toThrow('missing workbench bundle')
Expand Down
Loading
Loading