Skip to content

Commit 8e65da9

Browse files
committed
fix(copilot): hold callerless runs to the read grant for server tools
The router gate keyed on userPermission, which never reaches Go's in-band tool lane: those calls carry only the turn's recorded secret authority, so the gate would have refused every server-tool write there. Key on the same signal the CLI lane uses instead: a run with no caller of its own executes server tools under the api:read grant, and the router's existing write-scope check refuses any call whose arguments write.
1 parent 3475356 commit 8e65da9

11 files changed

Lines changed: 94 additions & 196 deletions

File tree

‎apps/sim/lib/mothership/agent-cli/project-file-read.integration.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import {
5050
import { projectToolResultForCopilot } from '@/lib/mothership/request/tools/resolved-secret-result'
5151
import type { ToolExecutionContext } from '@/lib/mothership/tool-executor/types'
5252
import { executeSimCli } from '@/lib/mothership/tools/handlers/sim-cli'
53+
import { createServerToolHandler } from '@/lib/mothership/tools/registry/server-tool-adapter'
5354
import { createProjectFile } from '@/lib/projects/files/application'
5455
import { storeCompiledDoc } from '@/lib/uploads/documents/compiled-store'
5556
import { fileDocumentInputIdentity } from '@/lib/uploads/documents/input-identity'
@@ -402,6 +403,42 @@ check('sim_cli services for a callerless run refuse the writes they route', asyn
402403
expect(await inboxSecretScope()).toBe(widen)
403404
})
404405

406+
check('server tools for a callerless run refuse the writes they route', async () => {
407+
const f = await fixture()
408+
const settings = createServerToolHandler('settings')
409+
const inboxSecretScope = async () =>
410+
(
411+
await db
412+
.select({ scope: workspace.inboxSecretScope })
413+
.from(workspace)
414+
.where(eq(workspace.id, f.workspaceId))
415+
)[0]?.scope
416+
const before = await inboxSecretScope()
417+
const widen = before === 'all' ? 'selected' : 'all'
418+
const update = {
419+
scope: 'workspace',
420+
action: 'update',
421+
section: 'inbox',
422+
changes: { secretScope: widen },
423+
}
424+
425+
const callerless: ToolExecutionContext = { ...f.context, workflowId: '', secretActorUserId: null }
426+
const refused = await settings(update, callerless)
427+
expect(refused.success).toBe(false)
428+
expect(refused.error).toContain('api:write')
429+
expect(await inboxSecretScope()).toBe(before)
430+
const read = await settings({ scope: 'workspace', action: 'get', section: 'inbox' }, callerless)
431+
expect(read.success, read.error).toBe(true)
432+
433+
const written = await settings(update, {
434+
...f.context,
435+
workflowId: '',
436+
secretActorUserId: f.userId,
437+
})
438+
expect(written.success, written.error).toBe(true)
439+
expect(await inboxSecretScope()).toBe(widen)
440+
})
441+
405442
check('sim_cli for a read-only member keeps what that role allows', async () => {
406443
const f = await fixture()
407444
const memberId = await insertUser('Read member')

‎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 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.
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.
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/tools/permissions.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,17 @@ 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.
5+
* optional on the execution context, and absent must deny. Shared by the
6+
* server-tool router and the handler-map tools.
67
*/
78
export function copilotToolCanWrite(userPermission: string | null | undefined): boolean {
89
return permissionSatisfies((userPermission ?? null) as PermissionType | null, 'write')
910
}
1011

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

‎apps/sim/lib/mothership/tools/registry/server-tool-adapter.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { toError } from '@sim/utils/errors'
33
import { isRecordLike } from '@sim/utils/object'
44
import { managementToolContracts } from '@/lib/api/contracts/mothership-management-tools'
55
import { openResourceOutputSchema } from '@/lib/api/contracts/mothership-resource-tools'
6+
import { OAUTH_API_READ_SCOPE } from '@/lib/auth/oauth-provider'
7+
import { withDelegatedApiScopes } from '@/lib/core/application/delegated-api-scopes'
68
import { messageForCopilotApplicationError } from '@/lib/mothership/application/errors'
79
import { projectToolErrorMessageForCopilot } from '@/lib/mothership/request/tools/resolved-secret-result'
810
import { searchResourceFromToolResult } from '@/lib/mothership/resources/search-tool-result'
@@ -12,7 +14,7 @@ import { routeExecution } from '@/lib/mothership/tools/server/router'
1214
const logger = createLogger('ServerToolAdapter')
1315

1416
export function createServerToolHandler(toolId: string): ToolHandler {
15-
return async (params, context): Promise<ToolExecutionResult> => {
17+
const execute: ToolHandler = async (params, context): Promise<ToolExecutionResult> => {
1618
const enrichedParams = { ...params }
1719
if (toolId !== 'open_resource' && !managementToolContracts.some((tool) => tool.id === toolId)) {
1820
if (!enrichedParams.workflowId && context.workflowId)
@@ -88,4 +90,11 @@ export function createServerToolHandler(toolId: string): ToolHandler {
8890
}
8991
}
9092
}
93+
// A run with no caller of its own (an unattributed inbox message) executes as the workspace owner,
94+
// whose live role the tools' operations authorize. It holds only the read grant, as in the CLI
95+
// lane, so the router refuses any call whose arguments write.
96+
return (params, context) =>
97+
context.secretActorUserId === null
98+
? withDelegatedApiScopes([OAUTH_API_READ_SCOPE], () => execute(params, context))
99+
: execute(params, context)
91100
}

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

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

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

113112
async execute(
114113
params: GenerateImageArgs,

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

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

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

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

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

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

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

7372
async execute(
7473
params: GenerateAudioArgs,

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

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

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

5958
async execute(
6059
params: GenerateVideoArgs,

‎apps/sim/lib/mothership/tools/server/router.test.ts‎

Lines changed: 0 additions & 158 deletions
This file was deleted.

0 commit comments

Comments
 (0)