Skip to content

Commit 3475356

Browse files
committed
fix(copilot): enforce a run's permission cap on server tool writes
A workspace run's permission can sit below its principal's live role: an unattributed inbox message runs as the workspace owner, capped to read. The server-tool router only checked that cap for the media tools, so the write actions of settings, dashboards, tests, changelog, workspaces and search_sources ran against the owner's live role. - the router enforces the cap wherever a tool's writes(args) is true, replacing the per-tool WRITE_ACTIONS table; organization chats carry no workspace cap and are unchanged - changelog and the media tools declare writes() - the executor no longer replaces a workspace run's permission with its target's live role; only organization chats take the target's role
1 parent c2ff178 commit 3475356

12 files changed

Lines changed: 224 additions & 48 deletions

File tree

‎apps/sim/lib/mothership/request/tools/permissions.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@ import type { ExecutionContext, ToolCallResult } from '@/lib/mothership/request/
55
* Guards a post-tool output-redirection sink against read-only principals.
66
*
77
* `run_function`, `user_table`, and `read` are read-allowed for execution
8-
* (they don't mutate the workspace themselves), so the router's `WRITE_ACTIONS`
9-
* gate in `tools/server/router.ts` lets read-only collaborators run them. But
10-
* their output-redirection declarations (`outputs.files`, `outputTable`)
11-
* durably persist to the workspace — creating/overwriting files and table rows.
8+
* (they don't mutate the workspace themselves), so their own permission gate
9+
* lets read-only collaborators run them. But their output-redirection
10+
* declarations (`outputs.files`, `outputTable`) durably persist to the
11+
* workspace — creating/overwriting files and table rows.
1212
* Those writes must satisfy the same write gate as the dedicated mutation tools.
1313
*
1414
* Returns a denial `ToolCallResult` when the caller lacks write access (so the

‎apps/sim/lib/mothership/tool-executor/executor.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,29 @@ describe('organization direct tool targets', () => {
680680
)
681681
expect(registry.isComplete()).toBe(true)
682682
})
683+
it('keeps a workspace run’s cap when it names its own workspace as the target', async () => {
684+
const handler = vi.fn().mockResolvedValue({ success: true })
685+
registerHandler('provider_operation', handler)
686+
const result = await executeTool(
687+
'provider_operation',
688+
{},
689+
{
690+
userId: 'owner',
691+
workflowId: '',
692+
workspaceId: 'selected',
693+
chatId: 'chat',
694+
requestMode: 'agent',
695+
targetWorkspaceId: 'selected',
696+
userPermission: 'read',
697+
}
698+
)
699+
expect(result).toEqual({
700+
success: false,
701+
error:
702+
"Permission denied: provider_operation requires write access. You have 'read' permission.",
703+
})
704+
expect(handler).not.toHaveBeenCalled()
705+
})
683706
it('stamps returned organization resources with the actual authorized target', async () => {
684707
registerHandler(
685708
'provider_operation',

‎apps/sim/lib/mothership/tool-executor/executor.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,11 @@ export async function executeTool(
136136
chatOrganizationId,
137137
secretActorUserId: context.userId,
138138
secretMountPolicy: undefined,
139+
// Only an organization chat takes the target's role: a workspace chat targets
140+
// its own workspace, and its context permission may be a deliberate cap.
141+
userPermission: target.permission ?? context.userPermission,
139142
}
140143
: {}),
141-
userPermission: target.permission ?? context.userPermission,
142144
})
143145
)
144146
return chatOrganizationId && result.resources?.length

‎apps/sim/lib/mothership/tools/permissions.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,16 @@ import { type PermissionType, permissionSatisfies } from '@sim/platform-authz/wo
22

33
/**
44
* Whether a copilot tool call may write. Fails closed: `userPermission` is
5-
* optional on the execution context, and absent must deny. Shared by the
6-
* server-tool router and the handler-map tools.
5+
* optional on the execution context, and absent must deny.
76
*/
87
export function copilotToolCanWrite(userPermission: string | null | undefined): boolean {
98
return permissionSatisfies((userPermission ?? null) as PermissionType | null, 'write')
109
}
1110

12-
/** Renders the denial message shared by both copilot execution paths. */
11+
/** Renders the denial for a copilot tool call that would write without write access. */
1312
export function copilotWriteDeniedMessage(
1413
toolName: string,
15-
operation: string | undefined,
14+
operation: string | null | undefined,
1615
userPermission: string | null | undefined
1716
): string {
1817
const actionLabel = operation ? `'${operation}' on ` : ''

‎apps/sim/lib/mothership/tools/server/changelog.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,12 @@ function withChat<T extends { chatId?: string }>(changes: T[], context?: ServerT
3333
: changes
3434
}
3535

36+
const CHANGELOG_READ_ACTIONS = new Set(['list', 'get'])
37+
3638
export const changelogServerTool: BaseServerTool = {
3739
name: 'changelog',
3840
inputSchema: mothershipChangelogInputSchema,
41+
writes: (args) => !CHANGELOG_READ_ACTIONS.has(mothershipChangelogInputSchema.parse(args).action),
3942
async execute(raw, context) {
4043
const input = mothershipChangelogInputSchema.parse(raw)
4144
const workspaceId = workspaceFor(input, context)

‎apps/sim/lib/mothership/tools/server/image/generate-image.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ async function loadReferenceImage(
108108

109109
export const generateImageServerTool: BaseServerTool<GenerateImageArgs, GenerateImageResult> = {
110110
name: GenerateImage.id,
111+
writes: () => true,
111112

112113
async execute(
113114
params: GenerateImageArgs,

‎apps/sim/lib/mothership/tools/server/media/ffmpeg.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ interface FfmpegResult {
8282

8383
export const ffmpegServerTool: BaseServerTool<FfmpegArgs, FfmpegResult> = {
8484
name: Ffmpeg.id,
85+
writes: () => true,
8586

8687
async execute(params: FfmpegArgs, context?: ServerToolContext): Promise<FfmpegResult> {
8788
if (!context?.userId) {

‎apps/sim/lib/mothership/tools/server/media/generate-audio.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ function audioExtFromContentType(contentType: string): string {
6868

6969
export const generateAudioServerTool: BaseServerTool<GenerateAudioArgs, GenerateAudioResult> = {
7070
name: GenerateAudio.id,
71+
writes: () => true,
7172

7273
async execute(
7374
params: GenerateAudioArgs,

‎apps/sim/lib/mothership/tools/server/media/generate-video.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ interface GenerateVideoResult {
5454

5555
export const generateVideoServerTool: BaseServerTool<GenerateVideoArgs, GenerateVideoResult> = {
5656
name: GenerateVideo.id,
57+
writes: () => true,
5758

5859
async execute(
5960
params: GenerateVideoArgs,
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import { beforeEach, describe, expect, it, vi } from 'vitest'
2+
import type { BaseServerTool, ServerToolContext } from '@/lib/mothership/tools/server/base-tool'
3+
import { changelogServerTool } from '@/lib/mothership/tools/server/changelog'
4+
import { dashboardsServerTool } from '@/lib/mothership/tools/server/dashboards'
5+
import { ffmpegServerTool } from '@/lib/mothership/tools/server/media/ffmpeg'
6+
import { routeExecution } from '@/lib/mothership/tools/server/router'
7+
import { organizationSearchSourcesServerTool } from '@/lib/mothership/tools/server/search-sources'
8+
import { settingsServerTool } from '@/lib/mothership/tools/server/settings'
9+
import { testsServerTool } from '@/lib/mothership/tools/server/tests'
10+
import { workspacesServerTool } from '@/lib/mothership/tools/server/workspaces'
11+
12+
const tools: BaseServerTool[] = [
13+
settingsServerTool,
14+
dashboardsServerTool,
15+
changelogServerTool,
16+
testsServerTool,
17+
workspacesServerTool,
18+
organizationSearchSourcesServerTool,
19+
ffmpegServerTool,
20+
]
21+
22+
/** The shape an unattributed inbox message runs with: the owner as principal, capped to read. */
23+
const cappedWorkspaceRun: ServerToolContext = {
24+
userId: 'owner',
25+
workspaceId: 'workspace',
26+
chatId: 'chat',
27+
toolCallId: 'call',
28+
copilotToolExecution: true,
29+
requestMode: 'agent',
30+
userPermission: 'read',
31+
}
32+
33+
const writes: Array<[string, Record<string, unknown>]> = [
34+
[
35+
'settings',
36+
{
37+
action: 'execute',
38+
scope: 'workspace',
39+
section: 'teammates',
40+
operation: 'invite',
41+
input: { emails: ['outsider@example.com'], permission: 'admin' },
42+
},
43+
],
44+
['settings', { action: 'update', scope: 'workspace', section: 'general', changes: {} }],
45+
['dashboards', { action: 'set', content: '# Revenue' }],
46+
[
47+
'changelog',
48+
{
49+
action: 'publish',
50+
title: 'Release',
51+
body: 'Notes',
52+
bump: 'patch',
53+
bumpReason: 'Fixes',
54+
changes: [{ text: 'Fix' }],
55+
},
56+
],
57+
['changelog', { action: 'update', releaseId: 'release', expectedRevision: '1' }],
58+
['tests', { action: 'create', name: 'billing', title: 'Billing' }],
59+
['tests', { action: 'update', name: 'billing', title: 'Billing' }],
60+
['tests', { action: 'delete', name: 'billing' }],
61+
['tests', { action: 'run', version: 'draft' }],
62+
['workspaces', { action: 'create', name: 'Research' }],
63+
['search_sources', { action: 'approve', connectorType: 'slack', approved: true }],
64+
['ffmpeg', { operation: 'probe', inputs: { files: [{ path: 'files/a.mp4' }] } }],
65+
]
66+
67+
const reads: Array<[string, Record<string, unknown>]> = [
68+
['settings', { action: 'list', scope: 'workspace' }],
69+
[
70+
'settings',
71+
{
72+
action: 'execute',
73+
scope: 'workspace',
74+
section: 'teammates',
75+
operation: 'list_invitations',
76+
input: {},
77+
},
78+
],
79+
['dashboards', { action: 'get' }],
80+
['changelog', { action: 'list' }],
81+
['tests', { action: 'list', version: 'draft' }],
82+
['search_sources', { action: 'list' }],
83+
]
84+
85+
const dispatched = vi.fn()
86+
87+
beforeEach(() => {
88+
dispatched.mockReset()
89+
for (const tool of tools) {
90+
vi.spyOn(tool, 'execute').mockImplementation(async () => {
91+
dispatched(tool.name)
92+
return { success: true }
93+
})
94+
}
95+
})
96+
97+
/** Dispatch is what is under test; the stubbed result need not satisfy each tool's output schema. */
98+
async function routeIgnoringOutput(
99+
toolName: string,
100+
payload: Record<string, unknown>,
101+
context: ServerToolContext
102+
) {
103+
await routeExecution(toolName, payload, context).catch(() => undefined)
104+
}
105+
106+
describe('a run capped below its principal’s role', () => {
107+
it.each(writes)('refuses %s %j before dispatch', async (toolName, payload) => {
108+
await expect(routeExecution(toolName, payload, cappedWorkspaceRun)).rejects.toThrow(
109+
"requires write access. You have 'read' permission."
110+
)
111+
expect(dispatched).not.toHaveBeenCalled()
112+
})
113+
114+
it('refuses a write when the run carries no permission at all', async () => {
115+
await expect(
116+
routeExecution(
117+
'dashboards',
118+
{ action: 'set', content: '# Revenue' },
119+
{
120+
...cappedWorkspaceRun,
121+
userPermission: undefined,
122+
}
123+
)
124+
).rejects.toThrow("You have 'none' permission.")
125+
expect(dispatched).not.toHaveBeenCalled()
126+
})
127+
128+
it.each(reads)('still answers %s %j', async (toolName, payload) => {
129+
await routeIgnoringOutput(toolName, payload, cappedWorkspaceRun)
130+
expect(dispatched).toHaveBeenCalledExactlyOnceWith(toolName)
131+
})
132+
})
133+
134+
describe('a run whose permission admits writes', () => {
135+
it('dispatches a write at write permission', async () => {
136+
await routeIgnoringOutput(
137+
'dashboards',
138+
{ action: 'set', content: '# Revenue' },
139+
{ ...cappedWorkspaceRun, userPermission: 'write' }
140+
)
141+
expect(dispatched).toHaveBeenCalledExactlyOnceWith('dashboards')
142+
})
143+
144+
it.each([
145+
['an organization chat', { organizationId: 'org', workspaceId: undefined }],
146+
['an organization chat acting on a workspace', { chatOrganizationId: 'org' }],
147+
])(
148+
'leaves %s to the live role its operations authorize',
149+
async (_label, scope: Partial<ServerToolContext>) => {
150+
await routeIgnoringOutput(
151+
'search_sources',
152+
{ action: 'approve', connectorType: 'slack', approved: true },
153+
{ ...cappedWorkspaceRun, userPermission: undefined, ...scope }
154+
)
155+
expect(dispatched).toHaveBeenCalledExactlyOnceWith('search_sources')
156+
}
157+
)
158+
})

0 commit comments

Comments
 (0)