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
2 changes: 1 addition & 1 deletion apps/docs/openapi-v2-resources.json
Original file line number Diff line number Diff line change
Expand Up @@ -6874,7 +6874,7 @@
"post": {
"operationId": "executeTool",
"summary": "Run tool",
"description": "Run a built-in tool using published parameter IDs. Requires workspace read access. Sim resolves `credentialId`, hosted keys, and whole-value `{{VAR_NAME}}` references in `user-only` parameters; other values pass through unchanged. Send connected credentials as top-level `credentialId`, not inside `input`. Third-party refusal returns `200` with `status: \"failed\"`; API failures use the error envelope. Hidden or missing tools return `404`; disallowed integrations return `403` with `error.details.code: INTEGRATION_NOT_ALLOWED`. Hosted-key usage is billed to the workspace. A call that would use a hosted key returns `402` when the workspace exceeds usage or billing limits. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.",
"description": "Run a built-in tool using published parameter IDs. Requires workspace read access. Sim resolves `credentialId`, hosted keys, and whole-value `{{VAR_NAME}}` references in `user-only` parameters; other values pass through unchanged. Send connected credentials as top-level `credentialId`, not inside `input`. Third-party refusal returns `200` with `status: \"failed\"`; API failures use the error envelope. Hidden or missing tools return `404`; disallowed integrations return `403` with `error.details.code: INTEGRATION_NOT_ALLOWED`. A `credentialId` you cannot use in this workspace returns `403`. Hosted-key usage is billed to the workspace. A call that would use a hosted key returns `402` when the workspace exceeds usage or billing limits. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.",
"x-sim-operation": "tools.execute",
"x-oauth-scope": "api:write",
"tags": ["Catalog"],
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/api/contracts/v2/openapi/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2434,7 +2434,7 @@ const declaredRoutes = [
applicationOperation: toolExecutionOperations.execute,
operationId: 'executeTool',
summary: 'Run tool',
description: `Run a built-in tool using published parameter IDs. Requires workspace read access. Sim resolves \`credentialId\`, hosted keys, and whole-value \`{{VAR_NAME}}\` references in \`user-only\` parameters; other values pass through unchanged. Send connected credentials as top-level \`credentialId\`, not inside \`input\`. Third-party refusal returns \`200\` with \`status: "failed"\`; API failures use the error envelope. Hidden or missing tools return \`404\`; disallowed integrations return \`403\` with \`error.details.code: INTEGRATION_NOT_ALLOWED\`. Hosted-key usage is billed to the workspace. A call that would use a hosted key returns \`402\` when the workspace exceeds usage or billing limits. ${WORKSPACE_API_KEY_DENIED}`,
description: `Run a built-in tool using published parameter IDs. Requires workspace read access. Sim resolves \`credentialId\`, hosted keys, and whole-value \`{{VAR_NAME}}\` references in \`user-only\` parameters; other values pass through unchanged. Send connected credentials as top-level \`credentialId\`, not inside \`input\`. Third-party refusal returns \`200\` with \`status: "failed"\`; API failures use the error envelope. Hidden or missing tools return \`404\`; disallowed integrations return \`403\` with \`error.details.code: INTEGRATION_NOT_ALLOWED\`. A \`credentialId\` you cannot use in this workspace returns \`403\`. Hosted-key usage is billed to the workspace. A call that would use a hosted key returns \`402\` when the workspace exceeds usage or billing limits. ${WORKSPACE_API_KEY_DENIED}`,
errors: [...RESOURCE_ERRORS, 'UsageLimitExceeded'],
success: { description: 'The outcome of the tool call.' },
}),
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/api/mcp/generated/v2-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1355,7 +1355,7 @@ export const V2_MCP_OPERATIONS = {
contract: v2ExecuteToolContract,
summary: 'Run tool',
description:
'Run a built-in tool using published parameter IDs. Requires workspace read access. Sim resolves `credentialId`, hosted keys, and whole-value `{{VAR_NAME}}` references in `user-only` parameters; other values pass through unchanged. Send connected credentials as top-level `credentialId`, not inside `input`. Third-party refusal returns `200` with `status: "failed"`; API failures use the error envelope. Hidden or missing tools return `404`; disallowed integrations return `403` with `error.details.code: INTEGRATION_NOT_ALLOWED`. Hosted-key usage is billed to the workspace. A call that would use a hosted key returns `402` when the workspace exceeds usage or billing limits. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.',
'Run a built-in tool using published parameter IDs. Requires workspace read access. Sim resolves `credentialId`, hosted keys, and whole-value `{{VAR_NAME}}` references in `user-only` parameters; other values pass through unchanged. Send connected credentials as top-level `credentialId`, not inside `input`. Third-party refusal returns `200` with `status: "failed"`; API failures use the error envelope. Hidden or missing tools return `404`; disallowed integrations return `403` with `error.details.code: INTEGRATION_NOT_ALLOWED`. A `credentialId` you cannot use in this workspace returns `403`. Hosted-key usage is billed to the workspace. A call that would use a hosted key returns `402` when the workspace exceeds usage or billing limits. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.',
workspaceKeyUnsupported: true,
handler: () => import('@/app/api/v2/tools/[toolId]/execute/route').then((route) => route.POST),
},
Expand Down
32 changes: 32 additions & 0 deletions apps/sim/lib/tool-execution/application/execute-tool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ import {
blockVisibilityMock,
blockVisibilityMockFns,
} from '@sim/testing/mocks/block-visibility.mock'
import {
credentialsAccessMock,
credentialsAccessMockFns,
} from '@sim/testing/mocks/credentials-access.mock'
import {
customBlockOperationsMock,
customBlockOperationsMockFns,
Expand Down Expand Up @@ -50,6 +54,8 @@ vi.mock('@sim/platform-authz/workspace', () => workspaceAuthzMock)

vi.mock('@sim/audit', () => auditMock)

vi.mock('@/lib/credentials/access', () => credentialsAccessMock)

vi.mock('@/lib/integrations/principal-scope.server', () => ({
allowedIntegrationTypes: hoisted.allowedIntegrationTypes,
principalUserId: (principal: { kind: string; userId?: string }) =>
Expand Down Expand Up @@ -258,6 +264,15 @@ function run(input: Partial<Parameters<typeof executeToolForCaller.execute>[0]['
})
}

function usableCredentialIn(workspaceId: string) {
return {
credential: { id: 'credential-1', workspaceId, type: 'service_account' },
member: { role: 'member' },
hasWorkspaceAccess: true,
isAdmin: false,
}
}

describe('executeToolForCaller', () => {
afterAll(resetEnvFlagsMock)

Expand Down Expand Up @@ -286,6 +301,9 @@ describe('executeToolForCaller', () => {
mocks.resolveBillingAttribution.mockResolvedValue({ workspaceId: WORKSPACE_ID })
mocks.checkUsageLimits.mockResolvedValue({ isExceeded: false })
environmentUtilsMockFns.mockGetEffectiveDecryptedEnv.mockResolvedValue({})
credentialsAccessMockFns.mockGetCredentialActorContext.mockResolvedValue(
usableCredentialIn(WORKSPACE_ID)
)
})

it.each<PersonalApiKeyPrincipal | SessionPrincipal>([principal, createSessionPrincipal()])(
Expand Down Expand Up @@ -415,6 +433,20 @@ describe('executeToolForCaller', () => {
})
})

it('refuses a credential from another workspace the caller can use', async () => {
credentialsAccessMockFns.mockGetCredentialActorContext.mockResolvedValue(
usableCredentialIn('workspace-a')
)

await expect(
run({ toolId: 'slack_message', credentialId: 'credential-1', input: { text: 'hi' } })
).rejects.toMatchObject({
code: 'forbidden',
message: expect.stringContaining('credential you can use in this workspace'),
})
expect(mocks.executeRegistryTool).not.toHaveBeenCalled()
})

it('requires a credential for an OAuth tool before it dispatches', async () => {
await expect(run({ toolId: 'slack_message', input: { text: 'hi' } })).rejects.toMatchObject({
code: 'validation',
Expand Down
16 changes: 16 additions & 0 deletions apps/sim/lib/tool-execution/application/execute-tool.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { authorizeCredentialUseForAuth } from '@/lib/auth/credential-access'
import { resolveBillingAttribution, toBillingContext } from '@/lib/billing/core/attribution'
import { checkExecutionUsageLimits } from '@/lib/billing/core/usage-gate-cache'
import { recordUsage } from '@/lib/billing/core/usage-log'
Expand Down Expand Up @@ -361,6 +362,21 @@ export const executeToolForCaller = defineAuthorizedWorkspaceUseCase({
throw new OrchestrationError('forbidden', 'Tool execution requires an acting user')
}

// The executor authorizes credentials with no workflow, so only this ties the credential
// to the workspace whose allowedIntegrations and deniedTools govern the call.
if (input.credentialId) {
const access = await authorizeCredentialUseForAuth(
{ success: true, userId },
{ credentialId: input.credentialId, workspaceId: context.workspaceId }
)
if (!access.ok) {
throw new OrchestrationError(
'forbidden',
'credentialId is not a credential you can use in this workspace'
)
}
}

const registry = mustClassifyContent(principal)
? new ResolvedSecretTraceRegistry([], { userId, workspaceId: context.workspaceId })
: undefined
Expand Down
Loading