import asyncio import json import sys from pathlib import Path import httpx sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import mcp_connection # noqa: E402 import server # noqa: E402 CONNECTION = {"scope_root": "organizations/42", "service_account_json": "{}"} class Google: def __init__(self, results=None, key="results", next_token=None, status=200): self.results, self.key, self.next_token, self.status, self.urls = results or [], key, next_token, status, [] def __call__(self, request): self.urls.append(request.url) if self.status != 200: return httpx.Response(self.status, json={"error": "ana@customer.example"}) body = {self.key: self.results} if self.next_token: body["nextPageToken"] = self.next_token return httpx.Response(200, json=body) def call(tool, arguments, google, connection=CONNECTION): async def run(): client = httpx.AsyncClient(transport=httpx.MockTransport(google)) original, token = server.get_upstream_client, server._gcp_token server.get_upstream_client = lambda kind, build: client async def fake_token(): return "tok" server._gcp_token = fake_token bound = mcp_connection.bind(connection) try: return await getattr(server, tool)(arguments) finally: mcp_connection.unbind(bound) server.get_upstream_client, server._gcp_token = original, token await client.aclose() return asyncio.run(run()) def test_every_search_is_under_the_scope_root(): google = Google([{"name": "//compute.googleapis.com/x"}]) assert call("gcp_list_servers", {}, google)["success"] assert google.urls[0].path == "/v1/organizations/42:searchAllResources" assert google.urls[0].params["assetTypes"] == "compute.googleapis.com/Instance" def test_a_caller_cannot_move_the_scope(): google = Google([]) call("gcp_list_resources", {"scope": "organizations/99"}, google) assert "organizations/42" in google.urls[0].path def test_bad_asset_type_is_refused(): assert call("gcp_list_resources", {"asset_type": "x y"}, Google())["error"]["code"] == "invalid_argument" def test_iam_people_are_anonymised_and_service_accounts_kept(): policy = {"resource": "//r", "policy": {"bindings": [{"role": "roles/viewer", "members": [ "user:ana@customer.example", "group:ops@customer.example", "serviceAccount:scan@p.iam.gserviceaccount.com"]}]}} text = json.dumps(call("gcp_list_resource_policies", {}, Google([policy]))) assert "ana@" not in text and "ops@" not in text assert "[user]" in text and "[group]" in text and "scan@p.iam.gserviceaccount.com" in text def test_organization_policies_use_the_scope_root(): google = Google([{"name": "organizations/42/policies/x"}], key="policies") assert call("gcp_list_organization_policies", {}, google)["success"] assert google.urls[0].path == "/v2/organizations/42/policies" def test_project_outside_scope_is_refused(): result = call("gcp_list_recommendations", {"project_id": "other"}, Google([])) assert result["error"]["code"] == "outside_scope" def test_recommendations_map_to_pillars(): google = Google([{"name": "//x/projects/p1", "primaryImpact": {"category": "MANAGEABILITY"}}]) def handler(request): if "recommender.googleapis.com" in str(request.url): return httpx.Response(200, json={"recommendations": [{"primaryImpact": {"category": "MANAGEABILITY"}}]}) return httpx.Response(200, json={"results": [{"name": "//cloudresourcemanager.googleapis.com/projects/p1"}]}) item = call("gcp_list_recommendations", {"project_id": "p1"}, handler)["data"]["items"][0] assert item["pillar"] == "operations" def test_upstream_error_text_is_not_returned(): text = json.dumps(call("gcp_list_servers", {}, Google(status=403))) assert "403" in text and "ana@" not in text def test_bad_scope_root_fails_closed(): result = call("gcp_list_servers", {}, Google([]), {**CONNECTION, "scope_root": "billingAccounts/1"}) assert result["success"] is False def test_a_throttled_call_waits_and_succeeds(): state = {"left": 2} def google(request): if state["left"]: state["left"] -= 1 return httpx.Response(429, headers={"retry-after": "0"}, json={}) return httpx.Response(200, json={"results": [{"name": "//x"}]}) assert call("gcp_list_servers", {}, google)["data"]["count"] == 1