diff --git a/stackone_ai/tools.py b/stackone_ai/tools.py index 27bba12..82de8c6 100644 --- a/stackone_ai/tools.py +++ b/stackone_ai/tools.py @@ -1114,6 +1114,9 @@ def _parse_arguments(self, arguments: str | JsonDict | None) -> JsonDict: parsed = arguments if not isinstance(parsed, dict): raise ToolArgumentsError(f"Tool arguments for {_json_text(self.name)} must be a JSON object") + # Header sanitising calls string methods on every top-level key. + if not all(isinstance(key, str) for key in parsed): + raise ToolArgumentsError(f"Tool arguments for {_json_text(self.name)} must have string keys") return dict(parsed) def _declared_headers(self) -> tuple[set[str] | None, set[str], bool]: diff --git a/stackone_ai/toolset.py b/stackone_ai/toolset.py index 1415764..ac8c162 100644 --- a/stackone_ai/toolset.py +++ b/stackone_ai/toolset.py @@ -739,6 +739,8 @@ def execute( raise ToolsetConfigError(f"action_id must be a non-empty string, got {_json_text(action_id)}") if arguments is not None and not isinstance(arguments, dict): raise ToolsetConfigError(f"arguments must be a JSON object, got {_json_type(arguments)}") + if arguments is not None and not all(isinstance(key, str) for key in arguments): + raise ToolsetConfigError("arguments must have string keys") if session_id is not None and (not isinstance(session_id, str) or not session_id): raise ToolsetConfigError(f"session_id must be a non-empty string, got {_json_text(session_id)}") @@ -1100,26 +1102,30 @@ def _discover_account_ids(self) -> list[str]: def _fetch_active_account_ids(self) -> list[str]: generation = self._cache_generation accounts = self.fetch_accounts() + # Skipped the way fetch_accounts() skips them when recording end users and providers. + records = [a for a in accounts if isinstance(a, dict)] - active = [a["id"] for a in accounts if a.get("status") == "active" and a.get("id")] + active = [ + a["id"] + for a in records + if a.get("status") == "active" and isinstance(a.get("id"), str) and a["id"] + ] if not active: - if not accounts: + if not records: raise ToolsetConfigError( "This API key has no linked accounts. Link one in the StackOne " "dashboard, or pass an account id explicitly." ) - listed = ", ".join(f"{a.get('provider')} ({a.get('status')})" for a in accounts) + listed = ", ".join(f"{a.get('provider')} ({a.get('status')})" for a in records) raise ToolsetConfigError( - f"None of this API key's {len(accounts)} linked accounts are active: {listed}. " + f"None of this API key's {len(records)} linked accounts are active: {listed}. " "Re-link them in the StackOne dashboard, or pass an account id explicitly." ) # Each non-shared account belongs to a single end user: discovering it would put one # end user's tools in front of whoever uses this toolset. if not self._include_non_shared: - skipped = sorted( - {a["id"] for a in accounts if a.get("id") in active and a.get("shared") is False} - ) + skipped = sorted({a["id"] for a in records if a.get("id") in active and a.get("shared") is False}) if skipped and len(skipped) == len(set(active)): raise ToolsetConfigError( f"None of this API key's {len(skipped)} active account(s) are shared: each " diff --git a/tests/test_fetch_tools.py b/tests/test_fetch_tools.py index 079a9be..4bea2c2 100644 --- a/tests/test_fetch_tools.py +++ b/tests/test_fetch_tools.py @@ -935,6 +935,31 @@ def test_inactive_accounts_are_skipped(self, mcp_mock_server: str): toolset = StackOneToolSet(api_key="test-key", base_url=mcp_mock_server) assert toolset._discover_account_ids() == ["default"] + def test_malformed_account_entries_are_skipped(self, monkeypatch): + """An entry that is not an object, or whose id is not a string, is not an account.""" + toolset = StackOneToolSet(api_key="test-key") + listed: list[Any] = ["junk", None, {"id": 5, "status": "active"}] + monkeypatch.setattr( + toolset, "fetch_accounts", lambda: [*listed, {"id": "acc", "provider": "p", "status": "active"}] + ) + assert toolset._discover_account_ids() == ["acc"] + + def test_only_malformed_account_entries_count_as_no_accounts(self, monkeypatch): + toolset = StackOneToolSet(api_key="test-key") + monkeypatch.setattr(toolset, "fetch_accounts", lambda: ["junk", None]) + with pytest.raises(ToolsetConfigError, match="This API key has no linked accounts"): + toolset._discover_account_ids() + + def test_a_malformed_entry_is_not_counted_as_an_inactive_account(self, monkeypatch): + toolset = StackOneToolSet(api_key="test-key") + monkeypatch.setattr( + toolset, "fetch_accounts", lambda: ["junk", {"provider": "p", "status": "revoked"}] + ) + with pytest.raises( + ToolsetConfigError, match=r"None of this API key's 1 linked accounts are active: p \(revoked\)\." + ): + toolset._discover_account_ids() + def test_a_discovery_in_flight_during_a_clear_is_not_cached(self, monkeypatch): """An account list fetched before clear_catalog_cache() must not outlive it.""" toolset = StackOneToolSet(api_key="test-key") @@ -1719,6 +1744,8 @@ def explode(*_args, **_kwargs): toolset = StackOneToolSet(api_key="test-key", account_id="acc1") with pytest.raises(ToolsetConfigError, match="JSON object"): toolset.execute("linear_list_issues", [1, 2, 3]) + with pytest.raises(ToolsetConfigError, match="string keys"): + toolset.execute("linear_list_issues", {1: "x"}) # type: ignore[dict-item] def test_fetch_accounts_rejects_a_non_list_body(self, monkeypatch): """list(dict) yields the keys, which blew up much later as an AttributeError.""" diff --git a/tests/test_models.py b/tests/test_models.py index db28134..19a3fb9 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -12,6 +12,7 @@ ExecuteConfig, StackOneAPIError, StackOneError, + ToolArgumentsError, ToolParameters, ) @@ -329,6 +330,11 @@ def test_non_dict_arguments(self): with pytest.raises(ValueError, match=r'^Tool arguments for "[^"]+" must be a JSON object$'): _mcp_tool().execute("[1, 2, 3]") + def test_non_string_keys_are_refused(self): + """Header sanitising calls string methods on every key, so a non-string key is refused up front.""" + with pytest.raises(ToolArgumentsError, match=r'^Tool arguments for "[^"]+" must have string keys$'): + _mcp_tool().execute({1: "x"}) # type: ignore[dict-item] + @given(invalid_json=invalid_json_strategy) @settings(max_examples=50) def test_invalid_json_arguments_pbt(self, invalid_json: str):