Files
cp1-agents/mcp-servers/gcp-discovery/tests/test_gcp.py
Jonathan Boniface c14a94f33b
Some checks failed
check agents / check (push) Failing after 12s
Add hyperscaler discovery MCP servers and Well-Architected guidance
azure-discovery, aws-discovery and gcp-discovery collect read-only metadata
on servers, workloads, Kubernetes clusters, networks, data stores, policies
and provider recommendations. Credentials arrive per call from the vault.
Replies are paged, scrubbed of secrets and anonymised, and throttled calls
back off. cloud-knowledge searches each provider's Well-Architected guidance
from fixed lists only, so no customer detail can leave the platform.

Adds shared skills, the render and test tooling, a public Python Dockerfile
until the hardened base image is reachable, the customer access guide, the
implementation plan and the Vault Service platform issue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 20:11:57 +00:00

118 lines
4.4 KiB
Python

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