@devries-cameron20 / composio Mirror · read-only / commits / f6cdf7aca
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 22:15 UTC

fix(python-sdk): prevent cross-tenant credential access via user_id kwarg [SEC-365]

CustomTool.__call__ was extracting user_id directly from the same **kwargs dict that carries LLM-supplied tool arguments. Because Pydantic's model_validate ignores fields not declared in the schema, an LLM (or prompt-injection input) could include user_id in its tool-call arguments and have CustomTool.__get_auth_credentials look up another tenant's OAuth tokens (CWE-639). Fix: - CustomTools.execute strips user_id from the LLM-supplied request dict at the trust boundary so only the explicit, trusted user_id parameter is honored. - CustomTool now exposes a separate trusted entry point (_invoke) where user_id is passed structurally separate from the request kwargs dict. CustomTool.__call__ no longer reads user_id from kwargs at all and always uses the safe "default" user, with a docstring pointing direct callers to CustomTools.execute. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> Co-authored-by: Srujan A <srujan@composio.dev>

Zen Agent committed Apr 28, 2026 at 07:33 UTC f6cdf7aca0f2245a8469ad0faca7e2d3a855b8dc
2 files changed +237 -5
python/composio/core/models/custom_tools.py
+42 -5
@@ -131,9 +131,33 @@ class CustomTool:
131 return account.state.val.model_dump()
132
133 def __call__(self, **kwargs: t.Any) -> t.Any:
134 - """Call the custom tool."""
135 - user_id = kwargs.pop("user_id", None) or "default"
136 - request = self.request_model.model_validate(kwargs)
134 + """Call the custom tool with the default ``user_id``.
135 +
136 + ``kwargs`` is treated as untrusted LLM-supplied input. ``user_id`` is
137 + therefore NOT extracted from ``kwargs``: allowing an LLM (or
138 + prompt-injection input) to pick which tenant's ``user_id`` is used to
139 + look up OAuth credentials would let it read another tenant's tokens
140 + (CWE-639, see SEC-365). Any ``user_id`` key in ``kwargs`` is dropped
141 + before the request body is validated.
142 +
143 + To use a non-default ``user_id``, call through
144 + ``CustomTools.execute(slug, request, user_id)`` (the canonical entry
145 + point), which sanitizes the request dict and supplies the trusted
146 + ``user_id`` from server-side context.
147 + """
148 + kwargs.pop("user_id", None)
149 + return self._invoke(user_id="default", request_kwargs=kwargs)
150 +
151 + def _invoke(self, user_id: str, request_kwargs: t.Dict[str, t.Any]) -> t.Any:
152 + """Trusted internal entry point.
153 +
154 + Called by ``CustomTools.execute`` after ``request_kwargs`` has been
155 + sanitized at the LLM trust boundary. ``user_id`` is supplied here as
156 + a positional / keyword argument that is structurally separate from
157 + the ``request_kwargs`` dict, so an LLM-controlled key inside the
158 + dict cannot be promoted to override the trusted value.
159 + """
160 + request = self.request_model.model_validate(request_kwargs)
161 if self.toolkit is None:
162 return t.cast(CustomToolProtocol, self.f)(request=request)
163
@@ -203,8 +227,21 @@ class CustomTools:
227 request: t.Dict,
228 user_id: t.Optional[str] = None,
229 ) -> t.Dict:
206 - """Execute a custom tool."""
230 + """Execute a custom tool.
231 +
232 + ``request`` is the LLM-supplied argument dict and is treated as
233 + untrusted: any ``user_id`` key it contains is stripped here so that
234 + only the explicit ``user_id`` parameter (sourced from trusted
235 + server-side context) is used to look up auth credentials. Without
236 + this sanitization an LLM (or prompt-injection input) could specify
237 + another tenant's ``user_id`` and read their OAuth tokens
238 + (CWE-639, see SEC-365).
239 + """
240 custom_tool = self.get(slug)
241 if custom_tool is None:
242 raise NotFoundError(f"Custom tool with slug {slug} not found")
210 - return custom_tool(**request, user_id=user_id)
243 + sanitized_request = {k: v for k, v in request.items() if k != "user_id"}
244 + return custom_tool._invoke(
245 + user_id=user_id or "default",
246 + request_kwargs=sanitized_request,
247 + )
python/tests/test_custom_tools_security.py new
+195
@@ -0,0 +1,195 @@
1 +"""Security tests for the legacy ``CustomTool`` / ``CustomTools`` API.
2 +
3 +Regression tests for SEC-365 (CWE-639, cross-tenant credential access).
4 +
5 +Before the fix, ``CustomTool.__call__`` extracted ``user_id`` from the same
6 +``**kwargs`` dict that carried LLM-supplied tool arguments, and
7 +``CustomTools.execute`` happily forwarded that LLM-controlled dict via
8 +``custom_tool(**request, user_id=user_id)``. An LLM (or prompt-injection
9 +input) could therefore set ``user_id`` to another tenant's identifier —
10 +either getting it forwarded into ``CustomTool.__call__`` directly or
11 +relying on Python's duplicate-kwarg ``TypeError`` to leak whose tokens
12 +were nearly looked up.
13 +
14 +The fix:
15 + * ``CustomTools.execute`` strips ``user_id`` from the LLM-supplied
16 + ``request`` dict at the trust boundary, so only the trusted, explicit
17 + ``user_id`` parameter reaches the credential lookup.
18 + * ``CustomTool.__call__`` exposes ``user_id`` as a keyword-only
19 + parameter and drops any ``user_id`` left in ``kwargs`` before the
20 + request body is validated.
21 +"""
22 +
23 +from unittest.mock import MagicMock
24 +
25 +import pytest
26 +from pydantic import BaseModel, Field
27 +
28 +from composio.core.models.custom_tools import CustomTool, CustomTools
29 +from composio.exceptions import NotFoundError
30 +
31 +
32 +class _IssueInput(BaseModel):
33 + issue_number: int = Field(description="GitHub issue number")
34 +
35 +
36 +def _make_mock_client() -> MagicMock:
37 + """Build a mock HttpClient suitable for CustomTool.__get_auth_credentials."""
38 +
39 + state = MagicMock()
40 + state.val.model_dump.return_value = {"access_token": "trusted-token"}
41 +
42 + account = MagicMock()
43 + account.created_at = "2026-01-01T00:00:00Z"
44 + account.state = state
45 +
46 + response = MagicMock()
47 + response.items = [account]
48 +
49 + client = MagicMock()
50 + client.connected_accounts.list.return_value = response
51 + client.tools.proxy = MagicMock()
52 + return client
53 +
54 +
55 +def test_execute_strips_user_id_from_llm_request() -> None:
56 + """``CustomTools.execute`` MUST strip ``user_id`` from the request dict."""
57 + client = _make_mock_client()
58 + tools = CustomTools(client=client)
59 +
60 + def github_tool(request: _IssueInput, execute_request, auth_credentials):
61 + """Fetch issue info."""
62 + return {"token": auth_credentials["access_token"]}
63 +
64 + tools.register(toolkit="github")(github_tool)
65 +
66 + result = tools.execute(
67 + slug="GITHUB_GITHUB_TOOL",
68 + request={"issue_number": 1, "user_id": "victim-user"},
69 + user_id="trusted-user",
70 + )
71 +
72 + assert result == {"token": "trusted-token"}
73 + # Only the trusted, explicit user_id reaches the credential lookup.
74 + client.connected_accounts.list.assert_called_once_with(
75 + toolkit_slugs=["github"],
76 + user_ids=["trusted-user"],
77 + )
78 +
79 +
80 +def test_execute_falls_back_to_default_when_user_id_missing() -> None:
81 + """If the caller forgets a trusted ``user_id``, fall back to ``"default"``.
82 +
83 + Specifically, ``execute`` must NOT silently use the LLM-supplied
84 + ``user_id`` from ``request`` as a fallback — that would re-introduce
85 + the SEC-365 vulnerability under a different code path.
86 + """
87 + client = _make_mock_client()
88 + tools = CustomTools(client=client)
89 +
90 + def github_tool(request: _IssueInput, execute_request, auth_credentials):
91 + """Fetch issue info."""
92 + return {"ok": True}
93 +
94 + tools.register(toolkit="github")(github_tool)
95 +
96 + tools.execute(
97 + slug="GITHUB_GITHUB_TOOL",
98 + request={"issue_number": 1, "user_id": "victim-user"},
99 + user_id=None,
100 + )
101 +
102 + client.connected_accounts.list.assert_called_once_with(
103 + toolkit_slugs=["github"],
104 + user_ids=["default"],
105 + )
106 +
107 +
108 +def test_execute_does_not_mutate_caller_request_dict() -> None:
109 + """Sanitization MUST NOT mutate the caller's ``request`` dict in place."""
110 + client = _make_mock_client()
111 + tools = CustomTools(client=client)
112 +
113 + def github_tool(request: _IssueInput, execute_request, auth_credentials):
114 + """Fetch issue info."""
115 + return {"ok": True}
116 +
117 + tools.register(toolkit="github")(github_tool)
118 +
119 + request_dict = {"issue_number": 1, "user_id": "victim-user"}
120 + tools.execute(
121 + slug="GITHUB_GITHUB_TOOL",
122 + request=request_dict,
123 + user_id="trusted-user",
124 + )
125 +
126 + # The original dict is untouched (the SDK should not surprise the caller).
127 + assert request_dict == {"issue_number": 1, "user_id": "victim-user"}
128 +
129 +
130 +def test_call_drops_user_id_smuggled_in_kwargs_dict() -> None:
131 + """``CustomTool.__call__`` MUST ignore any ``user_id`` smuggled in kwargs.
132 +
133 + A caller might unpack a partially-trusted dict like ``tool(**llm_dict)``
134 + without realizing that the LLM controls every key in it. Before the fix,
135 + a ``user_id`` key in that dict was popped and used to look up OAuth
136 + credentials — letting an LLM read another tenant's tokens. After the fix,
137 + ``__call__`` always uses the safe ``"default"`` user_id and the smuggled
138 + value is dropped before request validation.
139 + """
140 + client = _make_mock_client()
141 +
142 + def github_tool(request: _IssueInput, execute_request, auth_credentials):
143 + """Fetch issue info."""
144 + return {"ok": True}
145 +
146 + tool = CustomTool(f=github_tool, client=client, toolkit="github")
147 +
148 + smuggled_kwargs = {"issue_number": 1, "user_id": "victim-user"}
149 + tool(**smuggled_kwargs)
150 +
151 + client.connected_accounts.list.assert_called_once_with(
152 + toolkit_slugs=["github"],
153 + user_ids=["default"],
154 + )
155 +
156 +
157 +def test_invoke_uses_trusted_user_id_separate_from_request() -> None:
158 + """``_invoke`` takes ``user_id`` separately from the request dict.
159 +
160 + This is the trusted internal entry point used by ``CustomTools.execute``.
161 + Even if the LLM-controlled ``request_kwargs`` happens to contain a
162 + ``user_id`` key (and somehow gets past the sanitization in ``execute``),
163 + the ``user_id`` argument here is structurally separate, so the trusted
164 + value is what reaches the credential lookup.
165 + """
166 + client = _make_mock_client()
167 +
168 + captured: dict = {}
169 +
170 + def github_tool(request: _IssueInput, execute_request, auth_credentials):
171 + """Fetch issue info."""
172 + captured["request"] = request
173 + return {"ok": True}
174 +
175 + tool = CustomTool(f=github_tool, client=client, toolkit="github")
176 + tool._invoke(user_id="trusted-user", request_kwargs={"issue_number": 7})
177 +
178 + client.connected_accounts.list.assert_called_once_with(
179 + toolkit_slugs=["github"],
180 + user_ids=["trusted-user"],
181 + )
182 + assert captured["request"].issue_number == 7
183 +
184 +
185 +def test_execute_unknown_slug_raises() -> None:
186 + """Sanity check: unknown slugs still surface ``NotFoundError``."""
187 + client = _make_mock_client()
188 + tools = CustomTools(client=client)
189 +
190 + with pytest.raises(NotFoundError):
191 + tools.execute(
192 + slug="DOES_NOT_EXIST",
193 + request={"foo": "bar"},
194 + user_id="trusted-user",
195 + )