From eeb971f9cfb8dec9571ababbaf0d990f11a161a5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 13:11:45 -0800 Subject: [PATCH 1/3] 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. --- .../lib/function-execution/execute-request.ts | 1 + .../workbench-confidentiality.live.test.ts | 8 +++ .../mothership/tools/sandbox-session.test.ts | 50 ++++++++++++++++++- .../lib/mothership/tools/sandbox-session.ts | 34 ++++++++++++- 4 files changed, 89 insertions(+), 4 deletions(-) diff --git a/apps/sim/lib/function-execution/execute-request.ts b/apps/sim/lib/function-execution/execute-request.ts index 6642222e46a..9def9ddfc01 100644 --- a/apps/sim/lib/function-execution/execute-request.ts +++ b/apps/sim/lib/function-execution/execute-request.ts @@ -2397,6 +2397,7 @@ export async function executeFunctionRequest( ? { organizationId: admittedChatOwner.organizationId } : { workspaceId }), userId: auth.attributedUserId, + principal: auth.principal, signal: executionSignal, }) : undefined diff --git a/apps/sim/lib/mothership/tools/handlers/workbench-confidentiality.live.test.ts b/apps/sim/lib/mothership/tools/handlers/workbench-confidentiality.live.test.ts index c857545957a..d7251df34e6 100644 --- a/apps/sim/lib/mothership/tools/handlers/workbench-confidentiality.live.test.ts +++ b/apps/sim/lib/mothership/tools/handlers/workbench-confidentiality.live.test.ts @@ -351,6 +351,10 @@ async function sandboxApi(path: string, handler: () => Promise, 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 @@ -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 diff --git a/apps/sim/lib/mothership/tools/sandbox-session.test.ts b/apps/sim/lib/mothership/tools/sandbox-session.test.ts index 4d3a2e14046..4bbb12d2588 100644 --- a/apps/sim/lib/mothership/tools/sandbox-session.test.ts +++ b/apps/sim/lib/mothership/tools/sandbox-session.test.ts @@ -1,3 +1,4 @@ +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' import { setEnv } from '@sim/testing/mocks/env.mock' import { mothershipAgentUrlMock, @@ -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(), @@ -25,6 +27,7 @@ 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 { buildMothershipSandboxSession } from '@/lib/mothership/tools/sandbox-session' @@ -34,13 +37,15 @@ 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 = createSessionPrincipal({ userId: 'user' }) +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 () => @@ -94,6 +99,47 @@ 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, 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, + }) + expect(session.envs).toMatchObject({ + SIM_ORGANIZATION_ID: 'org', + SIM_ENTITLEMENTS: 'workflow-code', + }) + expect(entitlements.mock.calls[0][0]).not.toHaveProperty('workspaceId') + }) + + 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') diff --git a/apps/sim/lib/mothership/tools/sandbox-session.ts b/apps/sim/lib/mothership/tools/sandbox-session.ts index b502314401c..6cb58c4bef8 100644 --- a/apps/sim/lib/mothership/tools/sandbox-session.ts +++ b/apps/sim/lib/mothership/tools/sandbox-session.ts @@ -1,6 +1,7 @@ import { createHash } from 'node:crypto' import { readFile } from 'node:fs/promises' import { resolve } from 'node:path' +import type { Principal } from '@sim/auth/principal' import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' @@ -13,6 +14,7 @@ import { EXACT_EMPTY_DURABLE_SECRET_PROVENANCE, } from '@/lib/execution/durable-secret-provenance' import type { SandboxSessionRequest } from '@/lib/execution/remote-sandbox/types' +import { computeEntitlements } from '@/lib/mothership/entitlements' import { WorkbenchBootstrap } from '@/lib/mothership/generated/workbench' import { fetchGo } from '@/lib/mothership/request/go/fetch' import { mothershipRequestHeaders } from '@/lib/mothership/request/headers' @@ -102,11 +104,34 @@ async function workbenchCli( } } +/** + * The owner's entitlements, read fresh for each execution, for the workbench CLI's + * `SIM_ENTITLEMENTS`. Visibility only: each gated use case re-checks its flag, so a + * failed read hides the gated commands rather than failing the execution. + */ +async function sandboxEntitlements(args: { + principal: Principal + workspaceId?: string + organizationId?: string +}): Promise { + try { + return (await computeEntitlements(args)).join(',') + } catch (error) { + logger.warn('Session sandbox entitlements unavailable', { + workspaceId: args.workspaceId, + organizationId: args.organizationId, + error: getErrorMessage(error), + }) + return '' + } +} + /** * Builds the session request for a Mothership chat's persistent sandbox: the * per-chat identity, the sim-CLI bootstrap, and the CLI's headless auth * environment (`SIM_API_KEY`/`SIM_WORKSPACE`/`SIM_ENDPOINT`, the CLI's - * documented CI path). Only an opaque callback credential enters the workbench; + * documented CI path), plus the owner's `SIM_ENTITLEMENTS` so entitlement-gated + * CLI commands are visible. Only an opaque callback credential enters the workbench; * the active tool lease resolves the real user credential on the server. The * opaque credential cannot authenticate directly to ordinary v2 routes. * @@ -119,6 +144,7 @@ export async function buildMothershipSandboxSession(args: { workspaceId?: string organizationId?: string userId: string + principal: Principal signal?: AbortSignal }): Promise { args.signal?.throwIfAborted() @@ -129,7 +155,10 @@ export async function buildMothershipSandboxSession(args: { try { const apiKey = `mothership-sandbox:${generateId()}` const endpoint = env.MOTHERSHIP_SANDBOX_CLI_ENDPOINT?.trim() || getBaseUrl() - const scopedEndpoint = await sandboxResourceEndpoint(endpoint, args, apiKey) + const [scopedEndpoint, entitlements] = await Promise.all([ + sandboxResourceEndpoint(endpoint, args, apiKey), + sandboxEntitlements(args), + ]) if (scopedEndpoint !== endpoint) { const provenance: DurableSecretProvenance = { status: 'exact', @@ -155,6 +184,7 @@ export async function buildMothershipSandboxSession(args: { SIM_ENDPOINT: scopedEndpoint, ...(activeSandboxFileOwnerProtocol() === 1 ? { SIM_FILE_OWNER_PROTOCOL: '1' } : {}), ...(activeSandboxWorkspaceFileCopy() ? { SIM_WORKSPACE_FILE_COPY: '1' } : {}), + ...(entitlements ? { SIM_ENTITLEMENTS: entitlements } : {}), } } } catch (error) { From be2ac7fb78f39809e4c595f2547f1b309cfa3aec Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 13:12:43 -0800 Subject: [PATCH 2/3] chore(workspace-source): drop unused imports and use template literals flagged by biome --- .../lib/workspace-source/application/kinds/skills/adapter.ts | 1 - .../lib/workspace-source/application/kinds/tools/adapter.ts | 2 -- packages/workflow-code/src/compile/hostile.test.ts | 4 ++-- packages/workspace-code/src/kinds/files.ts | 1 - 4 files changed, 2 insertions(+), 6 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/kinds/skills/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/skills/adapter.ts index a1bf24ad2d5..947519c453e 100644 --- a/apps/sim/lib/workspace-source/application/kinds/skills/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/skills/adapter.ts @@ -23,7 +23,6 @@ import { applyNamed, authorizeNamed, type NamedKind, - type NamedPlan, planNamed, planNamedUndeclared, readRecord, diff --git a/apps/sim/lib/workspace-source/application/kinds/tools/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/tools/adapter.ts index bf721b7f8f5..73d5ab11812 100644 --- a/apps/sim/lib/workspace-source/application/kinds/tools/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/tools/adapter.ts @@ -19,7 +19,6 @@ import { resourceAddress } from '@sim/workspace-code' import { isStoredToolCode, type ToolCode, - type ToolDecl, toolCodec, toolDeclarationPath, toolLiteralSecret, @@ -41,7 +40,6 @@ import { applyNamed, authorizeNamed, type NamedKind, - type NamedPlan, planNamed, planNamedUndeclared, readRecord, diff --git a/packages/workflow-code/src/compile/hostile.test.ts b/packages/workflow-code/src/compile/hostile.test.ts index 8d78949894d..2643fda97b5 100644 --- a/packages/workflow-code/src/compile/hostile.test.ts +++ b/packages/workflow-code/src/compile/hostile.test.ts @@ -179,14 +179,14 @@ describe('hostile sources produce diagnostics only', () => { expect(result.workflow).not.toBeNull() expect(codes(result)).not.toContain('W_LITERAL_SECRET') const segment = 'A'.repeat(12) - const jwt = ['eyJ' + segment, 'eyJ' + segment, segment].join('.') + const jwt = [`eyJ${segment}`, `eyJ${segment}`, segment].join('.') const detected = run(wrap(`const a = api('A', { url: 'https://x', body: 'token ${jwt}' })`)) expect(codes(detected)).toContain('W_LITERAL_SECRET') }) it('never frames a literal secret, alone or as the warning past the cap', () => { const segment = 'A'.repeat(12) - const jwt = ['eyJ' + segment, 'eyJ' + segment, segment].join('.') + const jwt = [`eyJ${segment}`, `eyJ${segment}`, segment].join('.') const detected = run(wrap(`const a = api('A', { url: 'https://x', body: 'token ${jwt}' })`)) const finding = detected.diagnostics.find((d) => d.code === 'W_LITERAL_SECRET') expect(finding?.span.line).toBe(5) diff --git a/packages/workspace-code/src/kinds/files.ts b/packages/workspace-code/src/kinds/files.ts index b0445ed0c08..98563cab2be 100644 --- a/packages/workspace-code/src/kinds/files.ts +++ b/packages/workspace-code/src/kinds/files.ts @@ -9,7 +9,6 @@ import { hasSuspiciousCharacter, type Json } from '@sim/workflow-code' import { utf8Bytes } from '@sim/workflow-code/limits' import type { ResourceFingerprint } from '../base' -import { SUSPICIOUS_CHARACTER_HINT } from '../declaration/fields' import { diagnostic, type WorkspaceDiagnostic, From 268f70c9ff561fb6eea01ecad940c42ca224ae0a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 13:35:52 -0800 Subject: [PATCH 3/3] 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. --- .../tools/sandbox-session.integration.ts | 186 ++++++++++++++++++ .../mothership/tools/sandbox-session.test.ts | 29 ++- .../lib/mothership/tools/sandbox-session.ts | 57 +++++- 3 files changed, 263 insertions(+), 9 deletions(-) create mode 100644 apps/sim/lib/mothership/tools/sandbox-session.integration.ts diff --git a/apps/sim/lib/mothership/tools/sandbox-session.integration.ts b/apps/sim/lib/mothership/tools/sandbox-session.integration.ts new file mode 100644 index 00000000000..0c45edf66b9 --- /dev/null +++ b/apps/sim/lib/mothership/tools/sandbox-session.integration.ts @@ -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') + }) +}) diff --git a/apps/sim/lib/mothership/tools/sandbox-session.test.ts b/apps/sim/lib/mothership/tools/sandbox-session.test.ts index 4bbb12d2588..db95e1050fe 100644 --- a/apps/sim/lib/mothership/tools/sandbox-session.test.ts +++ b/apps/sim/lib/mothership/tools/sandbox-session.test.ts @@ -1,4 +1,4 @@ -import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { createDelegatedPrincipal } from '@sim/testing/factories/principal.factory' import { setEnv } from '@sim/testing/mocks/env.mock' import { mothershipAgentUrlMock, @@ -29,6 +29,7 @@ vi.mock('@/lib/mothership/request/headers', () => ({ 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 @@ -37,7 +38,11 @@ const baseURL = mothershipAgentUrlMockFns.mockGetMothershipBaseURL urlsMockFns.mockGetBaseUrl.mockReturnValue('https://unused.test') setEnv({ MOTHERSHIP_SANDBOX_CLI_ENDPOINT: 'https://sim.test', ENCRYPTION_KEY: 'a'.repeat(64) }) -const principal = createSessionPrincipal({ 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', () => { @@ -109,7 +114,15 @@ describe('deployment-owned workbench tooling', () => { expect(first.envs).toMatchObject({ SIM_ENTITLEMENTS: 'dashboards,workflow-code' }) expect(second.envs).toMatchObject({ SIM_ENTITLEMENTS: 'dashboards' }) expect(entitlements).toHaveBeenCalledWith( - expect.objectContaining({ principal, workspaceId: 'workspace' }) + expect.objectContaining({ + principal: expect.objectContaining({ + subjectUserId: 'user', + workspaceId: 'workspace', + delegationId: principal.delegationId, + audience: 'sim:workspaces', + }), + workspaceId: 'workspace', + }) ) }) @@ -120,13 +133,19 @@ describe('deployment-owned workbench tooling', () => { sessionKey: 'chat', organizationId: 'org', userId: 'user', - principal, + 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]).not.toHaveProperty('workspaceId') + 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 () => { diff --git a/apps/sim/lib/mothership/tools/sandbox-session.ts b/apps/sim/lib/mothership/tools/sandbox-session.ts index 6cb58c4bef8..165d1e395a0 100644 --- a/apps/sim/lib/mothership/tools/sandbox-session.ts +++ b/apps/sim/lib/mothership/tools/sandbox-session.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { readFile } from 'node:fs/promises' import { resolve } from 'node:path' -import type { Principal } from '@sim/auth/principal' +import type { DelegatedPrincipal, OrganizationDelegatedPrincipal } from '@sim/auth/principal' import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' @@ -14,6 +14,11 @@ import { EXACT_EMPTY_DURABLE_SECRET_PROVENANCE, } from '@/lib/execution/durable-secret-provenance' import type { SandboxSessionRequest } from '@/lib/execution/remote-sandbox/types' +import { + COPILOT_APPLICATION_DELEGATION_TTL_MS, + createTrustedCopilotPrincipal, + createTrustedOrganizationCopilotPrincipal, +} from '@/lib/mothership/auth/application-delegation' import { computeEntitlements } from '@/lib/mothership/entitlements' import { WorkbenchBootstrap } from '@/lib/mothership/generated/workbench' import { fetchGo } from '@/lib/mothership/request/go/fetch' @@ -104,18 +109,62 @@ async function workbenchCli( } } +type ExecutionPrincipal = DelegatedPrincipal | OrganizationDelegatedPrincipal + +/** + * The execution's own Copilot delegation, re-scoped from the Function audience to the + * `sim:workspaces` audience the availability use cases accept. Same actor, chat and delegation, + * never a longer lifetime; any other service keeps its principal and is refused there. + */ +function workspacesDelegation(principal: ExecutionPrincipal): ExecutionPrincipal | null { + if (principal.serviceId !== 'copilot') return null + const options = { + audience: 'sim:workspaces', + ttlMs: Math.max( + 1, + Math.min(COPILOT_APPLICATION_DELEGATION_TTL_MS, principal.expiresAt.getTime() - Date.now()) + ), + } + const chatId = principal.resourceScope?.chatId + if (principal.kind === 'organization_delegated') { + if (!chatId) return null + return createTrustedOrganizationCopilotPrincipal( + { + userId: principal.subjectUserId, + organizationId: principal.organizationId, + chatId, + delegationId: principal.delegationId, + }, + options + ) + } + return createTrustedCopilotPrincipal( + { + userId: principal.subjectUserId, + workspaceId: principal.workspaceId, + delegationId: principal.delegationId, + chatId, + executionId: principal.resourceScope?.executionId, + }, + options + ) +} + /** * The owner's entitlements, read fresh for each execution, for the workbench CLI's * `SIM_ENTITLEMENTS`. Visibility only: each gated use case re-checks its flag, so a * failed read hides the gated commands rather than failing the execution. */ async function sandboxEntitlements(args: { - principal: Principal + principal: ExecutionPrincipal workspaceId?: string organizationId?: string }): Promise { try { - return (await computeEntitlements(args)).join(',') + const principal = workspacesDelegation(args.principal) + if (!principal) return '' + const { workspaceId, organizationId } = args + return (await computeEntitlements({ principal, workspaceId, organizationId })).join(',') } catch (error) { logger.warn('Session sandbox entitlements unavailable', { workspaceId: args.workspaceId, @@ -144,7 +193,7 @@ export async function buildMothershipSandboxSession(args: { workspaceId?: string organizationId?: string userId: string - principal: Principal + principal: ExecutionPrincipal signal?: AbortSignal }): Promise { args.signal?.throwIfAborted()