Skip to content

Commit a76c545

Browse files
authored
fix(copilot): hold callerless runs to the read grant for server tool writes (#10061)
An unattributed inbox run executes as the workspace owner. Server tools now run such a callerless run (secretActorUserId === null) under the api:read grant, as the CLI lane already did, so the router's write-scope check refuses settings/dashboards/tests/changelog/workspaces/search_sources writes. The executor also keeps a workspace run's permission when it names its own workspace as target.
1 parent 2442320 commit a76c545

5 files changed

Lines changed: 76 additions & 2 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/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/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/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)

0 commit comments

Comments
 (0)