import asyncio import json import os import sys from pathlib import Path import boto3 import pytest from moto import mock_aws sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import mcp_connection # noqa: E402 import server # noqa: E402 os.environ.setdefault("AWS_DEFAULT_REGION", "eu-west-2") CONNECTION = {"access_key_id": "testing", "secret_access_key": "testing", "external_id": "kab-external-id", "role_arn": "arn:aws:iam::123456789012:role/kab-read-only", "regions": "eu-west-2,eu-west-1", "account_ids": "222222222222", "member_role_name": "kab-read-only"} @pytest.fixture def aws(): with mock_aws(): server.AWS_SESSIONS.clear() yield def call(tool, arguments=None): async def run(): bound = mcp_connection.bind(CONNECTION) try: return await getattr(server, tool)(arguments or {}) finally: mcp_connection.unbind(bound) return asyncio.run(run()) def client(service, region="eu-west-2"): return boto3.client(service, region_name=region, aws_access_key_id="testing", aws_secret_access_key="testing") def test_check_connection(aws): result = call("aws_check_connection") assert result["ok"] is True and result["account"] def test_servers_and_owner_tag(aws): ec2 = client("ec2") image = ec2.describe_images()["Images"][0]["ImageId"] ec2.run_instances(ImageId=image, MinCount=1, MaxCount=1, UserData="c2VjcmV0", TagSpecifications=[{"ResourceType": "instance", "Tags": [{"Key": "Owner", "Value": "Ana"}, {"Key": "Name", "Value": "web-01"}]}]) result = call("aws_list_servers") text = json.dumps(result) assert result["data"]["count"] == 1 and "web-01" in text and '"Ana"' not in text def test_networks_and_subnets(aws): ec2 = client("ec2") vpc = ec2.create_vpc(CidrBlock="10.9.0.0/16")["Vpc"]["VpcId"] ec2.create_subnet(VpcId=vpc, CidrBlock="10.9.1.0/24") assert vpc in json.dumps(call("aws_get_network_topology", {"kind": "vpcs"})) assert "10.9.1.0/24" in json.dumps(call("aws_get_network_topology", {"kind": "subnets"})) def test_each_region_is_read_separately(aws): client("ec2", "eu-west-1").create_vpc(CidrBlock="10.8.0.0/16") assert "10.8.0.0/16" in json.dumps(call("aws_get_network_topology", {"region": "eu-west-1"})) assert "10.8.0.0/16" not in json.dumps(call("aws_get_network_topology", {"region": "eu-west-2"})) def test_region_outside_the_connection_is_refused(aws): assert call("aws_list_servers", {"region": "us-east-1"})["error"]["code"] == "outside_scope" def test_account_outside_the_connection_is_refused(aws): assert call("aws_list_servers", {"account_id": "999999999999"})["error"]["code"] == "outside_scope" def test_listed_member_account_is_assumed(aws): assert call("aws_list_servers", {"account_id": "222222222222"})["success"] is True def test_data_stores(aws): client("s3").create_bucket(Bucket="orders", CreateBucketConfiguration={"LocationConstraint": "eu-west-2"}) assert "orders" in json.dumps(call("aws_list_data_stores", {"kind": "s3_buckets"})) def test_lambda_environment_is_removed(aws): role = client("iam").create_role(RoleName="fn", AssumeRolePolicyDocument="{}")["Role"]["Arn"] client("lambda").create_function(FunctionName="f", Runtime="python3.12", Role=role, Handler="a.b", Code={"ZipFile": b"x"}, Environment={"Variables": {"DB_PASSWORD": "hunter2"}}) assert "hunter2" not in json.dumps(call("aws_list_workloads")) def test_bucket_policy_principals_are_anonymised(aws): s3 = client("s3") s3.create_bucket(Bucket="kab-test-one", CreateBucketConfiguration={"LocationConstraint": "eu-west-2"}) s3.put_bucket_policy(Bucket="kab-test-one", Policy=json.dumps({"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::123456789012:user/ana"}, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::kab-test-one/*"}]})) item = call("aws_list_resource_policies", {"kind": "s3_buckets"})["data"]["items"][0] assert item["layer"] == "resource" and item["document"]["Statement"][0]["Effect"] == "Allow" assert item["document"]["Statement"][0]["Principal"]["AWS"] == "[user]" def test_a_bucket_without_a_policy_is_reported_not_fatal(aws): client("s3").create_bucket(Bucket="kab-test-two", CreateBucketConfiguration={"LocationConstraint": "eu-west-2"}) items = call("aws_list_resource_policies", {"kind": "s3_buckets"})["data"]["items"] assert items[0]["unread"] def test_role_trust_policies_keep_roles(aws): client("iam").create_role(RoleName="ops", AssumeRolePolicyDocument=json.dumps({"Statement": [{ "Effect": "Allow", "Principal": {"Service": "ec2.amazonaws.com"}, "Action": "sts:AssumeRole"}]})) assert "ec2.amazonaws.com" in json.dumps(call("aws_list_resource_policies", {"kind": "iam_role_trust"})) def test_kubernetes_clusters(aws): role = client("iam").create_role(RoleName="eks", AssumeRolePolicyDocument="{}")["Role"]["Arn"] client("eks").create_cluster(name="prod", roleArn=role, resourcesVpcConfig={"subnetIds": ["subnet-1"]}) item = call("aws_list_kubernetes_clusters")["data"]["items"][0] assert item["name"] == "prod" and "nodegroups" in item def test_service_control_policies(aws): org = client("organizations", "us-east-1") org.create_organization(FeatureSet="ALL") org.create_policy(Name="deny-root", Description="d", Type="SERVICE_CONTROL_POLICY", Content=json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Deny", "Action": "*", "Resource": "*"}]})) items = call("aws_list_organization_policies")["data"]["items"] named = [i for i in items if i.get("name") == "deny-root"] assert named and named[0]["layer"] == "organisation" and named[0]["document"]["Statement"][0]["Effect"] == "Deny" def test_config_query_must_be_a_select(aws): assert call("aws_query_resources", {"query": "DELETE FROM x"})["error"]["code"] == "invalid_argument" def test_unknown_kind_lists_the_options(aws): assert "vpcs" in call("aws_get_network_topology", {"kind": "nope"})["error"]["message"] def test_clients_retry_adaptively(): assert 'mode": "adaptive"' in (Path(__file__).resolve().parents[1] / "server.py").read_text()