Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
Add tests around S3 vhost extraction and vhost/path test paths. (#504)
mgius-aebd267258a023
diff --git a/tests/conftest.py b/tests/conftest.pyindex ca6ed682..f08cf8f6 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1,7 +1,10 @@"""Pytest fixtures for MiniStack integration tests."""+import contextlibimport os+import socket+from urllib.parse import urlparseimport urllib.requestimport boto3@@ -9,24 +12,42 @@ import pytestfrom botocore.config import ConfigENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ENDPOINT_HOST = urlparse(ENDPOINT).hostnameREGION = "us-east-1"-_kwargs = dict(+_default_kwargs = dict(endpoint_url=ENDPOINT,aws_access_key_id="test",aws_secret_access_key="test",region_name=REGION,- # Hardcoded retry and pool settings to reduce transient connection flakes- config=Config(+)+ # Hardcoded retry and pool settings to reduce transient connection flakes+_default_config_kwargs = dict(region_name=REGION,retries={"mode": "standard"},max_pool_connections=50,- ),)-def make_client(service):- return boto3.client(service, **_kwargs)+def patch_endpoint_dns():+ """Make *.MINISTACK_ENDPOINT subdomains resolve to 127.0.0.1 for virtual-hosted S3 testing."""+ _real_getaddrinfo = socket.getaddrinfo++ def _patched(host, port, *args, **kwargs):+ if isinstance(host, str) and host.endswith(f".{ENDPOINT_HOST}"):+ host = ENDPOINT_HOST+ return _real_getaddrinfo(host, port, *args, **kwargs)++ socket.getaddrinfo = _patched+ yield+ socket.getaddrinfo = _real_getaddrinfo+++def make_client(service, additional_config_kwargs=None):+ if additional_config_kwargs is None:+ additional_config_kwargs = {}+ return boto3.client(service, **_default_kwargs, config=Config(**_default_config_kwargs, **additional_config_kwargs))_SERIAL_TESTS = {diff --git a/tests/test_ministack.py b/tests/test_ministack.pyindex a9ec4932..c031ad06 100644--- a/tests/test_ministack.py+++ b/tests/test_ministack.py@@ -636,3 +636,80 @@ def test_persistence_s3_writes_state_after_ownership_and_public_access_block(tmppers.save_state("roundtrip-bytes", state_with_bytes)loaded = pers.load_state("roundtrip-bytes")assert loaded["blob"] == b"\x00\x01\xff\xfe"+++# ---------------------------------------------------------------------------+# Unit tests for _S3_VHOST_RE / _S3_VHOST_EXCLUDE_RE / _NON_S3_VHOST_NAMES+# ---------------------------------------------------------------------------++from ministack.app import _S3_VHOST_EXCLUDE_RE, _NON_S3_VHOST_NAMES++class TestS3VhostExcludeRe:+ """_S3_VHOST_EXCLUDE_RE gates out sub-service hostnames that look like vhosts."""++ def test_excludes_execute_api(self):+ assert _S3_VHOST_EXCLUDE_RE.search("abc12345.execute-api.localhost")++ def test_excludes_alb(self):+ assert _S3_VHOST_EXCLUDE_RE.search("mybucket.alb.localhost")++ def test_excludes_emr(self):+ assert _S3_VHOST_EXCLUDE_RE.search("mybucket.emr.localhost")++ def test_excludes_efs(self):+ assert _S3_VHOST_EXCLUDE_RE.search("mybucket.efs.localhost")++ def test_excludes_elasticache(self):+ assert _S3_VHOST_EXCLUDE_RE.search("mybucket.elasticache.localhost")++ def test_excludes_s3_control(self):+ assert _S3_VHOST_EXCLUDE_RE.search("mybucket.s3-control.localhost")++ def test_does_not_exclude_plain_vhost(self):+ assert not _S3_VHOST_EXCLUDE_RE.search("mybucket.localhost")++ def test_does_not_exclude_s3_segment_vhost(self):+ assert not _S3_VHOST_EXCLUDE_RE.search("mybucket.s3.localhost")+++class TestNonS3VhostNames:+ """_NON_S3_VHOST_NAMES prevents service endpoint names from being treated as bucket names."""++ def test_s3_is_excluded(self):+ assert "s3" in _NON_S3_VHOST_NAMES++ def test_common_services_excluded(self):+ for svc in ("sqs", "sns", "dynamodb", "lambda", "iam", "sts", "secretsmanager"):+ assert svc in _NON_S3_VHOST_NAMES, f"{svc!r} should be in _NON_S3_VHOST_NAMES"++ def test_normal_bucket_name_not_excluded(self):+ assert "mybucket" not in _NON_S3_VHOST_NAMES+ assert "my-data" not in _NON_S3_VHOST_NAMES+++from ministack.app import _extract_s3_vhost_bucket+++class TestExtractS3VhostBucket:+ """_extract_s3_vhost_bucket extracts the bucket name from virtual-hosted S3 host headers."""+ def test_bare_bucket(self):+ assert _extract_s3_vhost_bucket("mybucket.localhost") == "mybucket"++ def test_single_segment_s3_nested_bucket(self):+ assert _extract_s3_vhost_bucket("mybucket.s3.localhost") == "mybucket"++ def test_single_segment_region_nested_bucket(self):+ assert _extract_s3_vhost_bucket("mybucket.s3.us-east-1.localhost") == "mybucket"++ def test_single_segment_region_nested_bucket_with_port(self):+ assert _extract_s3_vhost_bucket("mybucket.s3.us-east-1.localhost:4566") == "mybucket"++ @pytest.mark.skip(reason="Dotted Nested Bucket is not supported yet")+ def test_double_segment_s3_nested_bucket(self):+ assert _extract_s3_vhost_bucket("dotted.mybucket.s3.localhost") == "dotted.mybucket"++ def test_bare_s3_with_region(self):+ assert _extract_s3_vhost_bucket("s3.us-east-1.localhost") is None++ def test_bare_s3_without_region(self):+ assert _extract_s3_vhost_bucket("s3.localhost") is None\ No newline at end of filediff --git a/tests/test_s3.py b/tests/test_s3.pyindex 2e94baeb..18cac2ff 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -1,14 +1,11 @@-import ioimport json-import osimport time-import uuid as _uuid_mod-import zipfilefrom urllib.parse import urlparseimport pytestfrom botocore.exceptions import ClientError+from conftest import make_client, patch_endpoint_dns, ENDPOINT_HOSTdef test_s3_create_bucket(s3):s3.create_bucket(Bucket="intg-s3-create")@@ -454,6 +451,52 @@ def test_s3_control_list_tags_via_s3_control_host(s3):assert "env" in bodyassert "test" in body+class TestS3VhostGetPutObject:+ """+ Ensure vhost style and path style requests work correctly.++ Test with both a simple bucket name and a max length one with dot and hyphen+ """++ BKT = "intg-s3-vhost"+ # max length and dotted with hyphen+ BKT_DOTTED_BASE = "intg-s3.vhost-nested.bucket"+ BKT_DOTTED = BKT_DOTTED_BASE + "x" * (63 - len(BKT_DOTTED_BASE))++ @pytest.fixture(autouse=True)+ def _init_buckets(self, s3):+ self.s3 = s3+ print(s3)+ assert len(self.BKT_DOTTED) == 63+ self.s3_path = make_client("s3", additional_config_kwargs=dict(s3={"addressing_style": "path"}))+ self.s3_virtual = make_client("s3", additional_config_kwargs=dict(s3={"addressing_style": "virtual"}))++ s3.create_bucket(Bucket=self.BKT)+ s3.put_object(Bucket=self.BKT, Key="vhost-test.txt", Body=b"vhost content")++ s3.create_bucket(Bucket=self.BKT_DOTTED)+ s3.put_object(Bucket=self.BKT_DOTTED, Key="vhost-test.txt", Body=b"vhost content")++ def test_path_style_get(self):+ resp = self.s3_path.get_object(Bucket=self.BKT, Key="vhost-test.txt")+ assert resp["Body"].read() == b"vhost content"++ def test_virtual_hosted_style_get(self):+ with patch_endpoint_dns():+ resp = self.s3_virtual.get_object(Bucket=self.BKT, Key="vhost-test.txt")+ assert resp["Body"].read() == b"vhost content"++ @pytest.mark.skip(reason="Dotted Nested Bucket is not supported yet")+ def test_dotted_bucket_virtual_hosted_style_get(self):+ with patch_endpoint_dns():+ resp = self.s3_virtual.get_object(Bucket=self.BKT_DOTTED, Key="vhost-test.txt")+ assert resp["Body"].read() == b"vhost content"++ def test_dotted_bucket_path_style_get(self):+ resp = self.s3_path.get_object(Bucket=self.BKT_DOTTED, Key="vhost-test.txt")+ assert resp["Body"].read() == b"vhost content"++def test_s3_bucket_policy(s3):bkt = "intg-s3-policy"s3.create_bucket(Bucket=bkt)