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
ci: exercise HTTP authorization contracts in both auth modes (#2221)
Johannes Grumböckb257efe6d795
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex aae9102a..11f65162 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -70,6 +70,7 @@ jobs:shard_count: 2env:+ AUTH: "false"# Control-plane tests must not contact the Docker daemon.DOCKER_HOST: unix:///no-existent/docker.sock@@ -133,9 +134,9 @@ jobs:exit 0fiif [ "${{ matrix.mode }}" = "serial" ]; then- pytest ${{ steps.shard.outputs.files }} -v --tb=short -m "serial and not data_plane" --durations=10+ pytest ${{ steps.shard.outputs.files }} -v --tb=short -m "serial and not data_plane and not auth_contract" --durations=10else- pytest ${{ steps.shard.outputs.files }} -v -n 3 --dist=loadfile -m "not serial and not data_plane" --durations=25+ pytest ${{ steps.shard.outputs.files }} -v -n 3 --dist=loadfile -m "not serial and not data_plane and not auth_contract" --durations=25fi- name: Upload MiniStack log@@ -145,6 +146,69 @@ jobs:name: ministack-${{ matrix.mode }}-shard-${{ matrix.shard_index }}.logpath: ministack.log+ authorization:+ name: authorization (AUTH=${{ matrix.auth }})+ runs-on: ubuntu-latest+ timeout-minutes: 10+ strategy:+ fail-fast: false+ matrix:+ auth: ["false", "true"]+ env:+ AUTH: ${{ matrix.auth }}+ DOCKER_HOST: unix:///no-existent/docker.sock+ IOT_MTLS_ENABLED: "0"+ steps:+ - uses: actions/checkout@v6++ - name: Set up Python+ uses: actions/setup-python@v6+ with:+ python-version: "3.13"++ - uses: astral-sh/[email protected]+ with:+ enable-cache: true++ - name: Install dependencies+ run: uv pip install --system -e ".[test]" -r requirements.txt++ - name: Start MiniStack+ run: |+ mkdir -p test-results+ python -m hypercorn ministack.app:app --bind 0.0.0.0:4566 --keep-alive 75 > test-results/ministack.log 2>&1 &+ echo "MINISTACK_PID=$!" >> "$GITHUB_ENV"+ for i in $(seq 1 15); do+ curl -sf http://localhost:4566/_ministack/health && break+ sleep 2+ done+ curl -sf http://localhost:4566/_ministack/health++ - name: Run authorization contracts+ run: |+ pytest tests/ -v --tb=short -m auth_contract \+ --junitxml=test-results/authorization.xml \+ --basetemp=test-results/pytest --durations=10++ - name: Stop MiniStack+ if: always()+ run: |+ if [ -n "${MINISTACK_PID:-}" ] && kill -0 "$MINISTACK_PID" 2>/dev/null; then+ kill -TERM "$MINISTACK_PID"+ for i in $(seq 1 10); do+ kill -0 "$MINISTACK_PID" 2>/dev/null || exit 0+ sleep 1+ done+ kill -KILL "$MINISTACK_PID" 2>/dev/null || true+ fi++ - name: Upload authorization logs and results+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: authorization-${{ matrix.auth }}+ path: test-results/+data-plane:name: data plane (docker, ${{ matrix.shard_index }}, ${{ matrix.shard_count }})runs-on: ubuntu-latest@@ -160,6 +224,7 @@ jobs:shard_index: 1shard_count: 2env:+ AUTH: "false"DOCKER_NETWORK: ministack-data-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.shard_index }}LAMBDA_EXECUTOR: dockerOPENSEARCH_DATAPLANE: "1"@@ -231,7 +296,7 @@ jobs:echo "No tests for this shard"exit 0fi- pytest ${{ steps.shard.outputs.files }} -v --tb=short -m "data_plane" --durations=25+ pytest ${{ steps.shard.outputs.files }} -v --tb=short -m "data_plane and not auth_contract" --durations=25- name: Upload MiniStack logif: always()@@ -301,7 +366,7 @@ jobs:test-result:name: test- needs: [control-plane, data-plane, no-image-build]+ needs: [control-plane, data-plane, authorization, no-image-build]if: always()runs-on: ubuntu-latesttimeout-minutes: 5@@ -309,4 +374,5 @@ jobs:- run: |test "${{ needs['control-plane'].result }}" = "success"test "${{ needs['data-plane'].result }}" = "success"+ test "${{ needs.authorization.result }}" = "success"test "${{ needs['no-image-build'].result }}" = "success"diff --git a/AGENTS.md b/AGENTS.mdindex 7b148eba..cfd91c0e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -61,6 +61,13 @@ before changing a service; it has the contribution process and examples.require the server at `localhost:4566`.- Run the relevant test file, then `pytest tests/` when routing, registry, orservice behavior changed. Run `ruff check ministack/`, the CI lint gate.+- Test AWS permission behavior with SDK/HTTP clients in the service's test+ file, marked `@pytest.mark.auth_contract`. Use `iam_user(policy=...)` for+ caller credentials and `auth_enabled` for mode-dependent assertions. CI runs+ these contracts with both `AUTH=false` and `AUTH=true`; permission changes+ need strict enforcement and permissive compatibility assertions. Do not+ patch `app.AUTH` or IAM enforcement in new permission contracts. Keep focused+ evaluator unit tests for policy logic. See `CONTRIBUTING.md` for local runs.- Tests that alter global server state or depend on ordering belong in`_SERIAL_TESTS` in `tests/conftest.py`; keep them out of parallel runs.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 91368097..c51f0f5a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -80,6 +80,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **IoT — job rollout rates** — `jobExecutionsRolloutConfig` was stored but every execution was created at once; a job now creates `maximumPerMinute` executions a minute, or a rate that starts at `baseRatePerMinute` and grows by `incrementFactor` for every `rateIncreaseCriteria` step of notified or succeeded things, notifies each thing when its execution is created, reports `isConcurrent` until the last batch and stops when the job is canceled or deleted. Contributed by @iot-rocket.- **IoT — MQTT publish, subscribe and receive evaluate IoT policies under `AUTH=true`** — after the CONNECT a certificate session could publish, subscribe and receive on any topic; it now needs `iot:Publish` on the topic (and `iot:RetainPublish` for a retained message or will), `iot:Subscribe` per topic filter and `iot:Receive` per delivered message. A refused PUBLISH or SUBSCRIBE closes an MQTT 3.1.1 connection (disconnect reason `CLIENT_ERROR`), MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 at QoS 0 (`AUTH_ERROR`) or 0x87 for the refused filter, which the `subscribed` event leaves out (no event when none is granted), a refused will refuses the CONNECT, and a message the subscriber may not receive is dropped. Contributed by @iot-rocket.- **IoT — MQTT connections evaluate `iot:Connect` under `AUTH=true`** — a device certificate on the mTLS listener connected under any client id, with or without a policy; with `AUTH=true` the CONNECT now needs an attached policy that allows `iot:Connect` on `client/<client id>` and none that denies it, with `${iot:ClientId}`, `${iot:Connection.Thing.ThingName}`, `iot:Connection.Thing.IsAttached` and `${iot:Certificate.Subject.CommonName}` resolved. A refusal closes an MQTT 3.1.1 connection without a CONNACK, answers MQTT 5 with CONNACK 0x87 and publishes `$aws/events/presence/connect_failed/{clientId}`. Contributed by @iot-rocket.++- **Authorization CI contracts** — marked SDK/HTTP tests run against both `AUTH=false` and `AUTH=true`, covering IAM allow/deny behavior and S3 copy source permissions. Shared IAM user fixtures create and clean up resources through MiniStack's IAM API, and health responses expose the effective `auth` state (`enabled`/`disabled`) so tests fail on mode mismatches.+### Fixed- **IoT — republish inside the rule's own topic filter** — `CreateTopicRule` and `ReplaceTopicRule` accepted a `republish` action whose topic the rule's `FROM` filter matches, so the rule fed on its own output; they now refuse it with AWS's `InvalidRequestException`, and an `AWS::IoT::TopicRule` with such an action fails its stack. Contributed by @iot-rocket.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 3194f0d6..ff874997 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -183,14 +183,14 @@ pip install boto3 pytest pytest-xdist duckdb docker cbor2pytest tests/ -v# Control-plane parallel lane: excludes serial and live-container tests-pytest tests/ -v -n 4 --dist=loadfile -m "not serial and not data_plane"+pytest tests/ -v -n 4 --dist=loadfile -m "not serial and not data_plane and not auth_contract"# Control-plane serial/global-state lane-pytest tests/ -v -m "serial and not data_plane"+pytest tests/ -v -m "serial and not data_plane and not auth_contract"# Docker-backed data-plane lane (requires a Docker daemon and network)DOCKER_NETWORK=ministack-data-local LAMBDA_EXECUTOR=docker \-pytest tests/ -v -m data_plane+pytest tests/ -v -m "data_plane and not auth_contract"# Run a specific servicepytest tests/ -v -k "cognito"@@ -198,6 +198,79 @@ pytest tests/ -v -k "cognito"---+## Testing Permission Behavior++When testing whether an AWS operation is allowed or denied, write an SDK/HTTP+integration test in `tests/test_<service>.py` and mark it `auth_contract`.+CI runs the same marked tests against fresh servers with `AUTH=false` and+`AUTH=true`; the existing control-plane and data-plane jobs exclude them.+The initial authorization matrix runs without Docker.++Use the shared `iam_user` factory to create users through IAM APIs. It grants+no permissions by default. Pass `policy={...}` to attach an explicit inline+policy, then use `user.client("service")` for the request under test. Existing+service fixtures such as `s3` use admin credentials for resource setup and+cleanup. The user factory removes its users, keys, policies, and clients after+each test, including after failures. Service resources need their own cleanup.++```python+import pytest+from botocore.exceptions import ClientError++[email protected]_contract+def test_list_buckets_without_permission(auth_enabled, iam_user):+ client = iam_user().client("s3")+ if auth_enabled:+ with pytest.raises(ClientError) as exc:+ client.list_buckets()+ assert exc.value.response["Error"]["Code"] == "AccessDenied"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ else:+ assert "Buckets" in client.list_buckets()+```++Every marked test verifies that the server's health response reports the expected+mode, even if it doesn't request `auth_enabled` explicitly. The fixture observes+configuration; it never changes the server's mode. A mismatch fails the test.+Health reports `auth` as `enabled` or `disabled`; `auth_enabled` exposes that+state as a boolean to tests.++For local runs, start the server in one terminal:++```bash+AUTH=false DOCKER_HOST=unix:///no-existent/docker.sock IOT_MTLS_ENABLED=0 \+python -m hypercorn ministack.app:app --bind 127.0.0.1:4566 --keep-alive 75+```++Run the contracts in another terminal with the same mode:++```bash+AUTH=false pytest tests/ -m auth_contract -v+# Or focus on one service:+AUTH=false pytest tests/test_s3.py -m auth_contract -v+```++Stop the server, restart it with `AUTH=true`, and rerun with `AUTH=true` in the+test command. Set `MINISTACK_ENDPOINT` for pytest if using another address.+CI also checks a separate server started with `AUTH` unset to protect the+permissive default.++Permission changes should assert both enforcement and permissive compatibility:+a valid request lacking permission succeeds with `AUTH=false` and is denied+with `AUTH=true`. Include a permitted case as a control, and verify error codes,+HTTP status, and relevant resource state. Input validation and service-specific+authentication requirements may still apply in permissive mode.++Keep focused evaluator unit tests for policy logic. Existing tests that patch+`app.AUTH` should migrate when they test externally observable behavior; remove+redundant patched tests once the replacement covers their behavior. The legacy+`inprocess_iam_user` helper supports remaining internal tests, not new permission+contracts. More involved scenarios, such as role sessions and Docker-backed+execution roles, can add shared fixtures and CI support when exercised.++---+## Code Conventions- **Imports** — always `from ministack.core.responses import ...`, never `from core.responses import ...`diff --git a/ministack/app.py b/ministack/app.pyindex fbc595ef..c765c8b8 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -882,6 +882,7 @@ def _handle_health_request(path: str, request_id: str):json.dumps({"services": {s: "available" for s in SERVICE_HANDLERS},+ "auth": "enabled" if AUTH else "disabled","edition": os.environ.get("MINISTACK_EDITION", "light"),"version": _version(),"iot_mtls": _iot_mtls_state,diff --git a/pyproject.toml b/pyproject.tomlindex 762a67af..d467664a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -103,6 +103,7 @@ python_files = ["test_*.py"]python_functions = ["test_*"]addopts = "--dist=loadfile"markers = [+ "auth_contract: SDK/HTTP permission contracts run against both server AUTH modes","serial: tests that mutate global server state and must run alone","data_plane: tests that require live Docker-backed service behavior",]diff --git a/scripts/_collect_plan_plugin.py b/scripts/_collect_plan_plugin.pyindex 58b54f1d..b3ae98f8 100644--- a/scripts/_collect_plan_plugin.py+++ b/scripts/_collect_plan_plugin.py@@ -24,6 +24,9 @@ def pytest_collection_finish(session):out = rootpath / COLLECT_PLAN_FILENAMEcounts: dict[str, dict[str, int]] = {}for item in session.items:+ # Auth contracts belong to the separate two-mode matrix, not these shards.+ if item.get_closest_marker("auth_contract"):+ continuetry:path = item.path.relative_to(rootpath).as_posix()except ValueError:diff --git a/tests/conftest.py b/tests/conftest.pyindex ebc1142b..3e3f83e9 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -14,6 +14,7 @@ import timeimport urllib.requestimport uuidimport zipfile+from types import SimpleNamespacefrom urllib.parse import unquote, urlparseimport boto3@@ -62,8 +63,10 @@ def patch_endpoint_dns():return _real_getaddrinfo(host, port, *args, **kwargs)socket.getaddrinfo = _patched- yield- socket.getaddrinfo = _real_getaddrinfo+ try:+ yield+ finally:+ socket.getaddrinfo = _real_getaddrinfodef make_client(service, additional_config_kwargs=None):@@ -113,7 +116,78 @@ def iot_test_ca(registration_code, common_name="ministack-test-ca"):return ca_pem, ca_key_pem, verification_pem-def iam_user(identity_policy=None):[email protected](scope="session")+def auth_enabled():+ """Verify the running server's IAM mode before exercising auth contracts."""+ expected = os.environ.get("AUTH", "false").lower()+ if expected not in {"true", "false"}:+ pytest.fail("Auth contracts require AUTH=true or AUTH=false.", pytrace=False)+ try:+ with urllib.request.urlopen(f"{ENDPOINT.rstrip('/')}/_ministack/health", timeout=5) as response:+ actual = json.load(response).get("auth")+ except (OSError, ValueError) as exc:+ pytest.fail(f"Cannot read MiniStack auth mode at {ENDPOINT}: {exc}", pytrace=False)+ if actual not in ("enabled", "disabled"):+ pytest.fail("MiniStack health response lacks auth=enabled/disabled; restart with current code.", pytrace=False)+ expected_state = "enabled" if expected == "true" else "disabled"+ if actual != expected_state:+ pytest.fail(+ f"Auth mode mismatch: tests expect AUTH={expected}, but {ENDPOINT} reports "+ f"auth={actual}. Restart the server with the expected mode.",+ pytrace=False,+ )+ return actual == "enabled"++[email protected](autouse=True)+def _verify_auth_contract_mode(request):+ # Verify even marked tests that don't need different expectations per mode.+ if request.node.get_closest_marker("auth_contract"):+ request.getfixturevalue("auth_enabled")+++def iam_user(auth_enabled):+ """Factory for API-created IAM users; no permissions unless explicitly supplied.++ Returns an object with name, arn, and client(service, region=..., config=...).+ Only this fixture's users, keys, policies, and clients are cleaned up.+ """+ with contextlib.ExitStack() as cleanup:+ admin = make_client("iam")+ cleanup.callback(admin.close)++ def create(*, policy=None):+ name = f"auth-user-{uuid.uuid4().hex}"+ user = admin.create_user(UserName=name)["User"]+ cleanup.callback(admin.delete_user, UserName=name)+ key = admin.create_access_key(UserName=name)["AccessKey"]+ cleanup.callback(admin.delete_access_key, UserName=name, AccessKeyId=key["AccessKeyId"])+ if policy is not None:+ admin.put_user_policy(UserName=name, PolicyName="test-policy", PolicyDocument=json.dumps(policy))+ cleanup.callback(admin.delete_user_policy, UserName=name, PolicyName="test-policy")++ session = boto3.Session(+ aws_access_key_id=key["AccessKeyId"],+ aws_secret_access_key=key["SecretAccessKey"],+ region_name=REGION,+ )++ def client(service, *, region=REGION, config=None):+ defaults = Config(retries={"total_max_attempts": 1}, connect_timeout=5, read_timeout=10)+ result = session.client(+ service, endpoint_url=ENDPOINT, region_name=region,+ config=defaults.merge(config) if config is not None else defaults,+ )+ cleanup.callback(result.close)+ return result++ return SimpleNamespace(name=name, arn=user["Arn"], client=client)++ yield create+++def inprocess_iam_user(identity_policy=None):"""An in-process IAM user with an access key in the default account: ``((key id, secret), arn)``."""from ministack.core.responses import get_account_id, request_scopefrom ministack.services import iam as iam_svcdiff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.pyindex 436dbb04..ab3e93fa 100644--- a/tests/test_apigatewayv1.py+++ b/tests/test_apigatewayv1.py@@ -11,7 +11,7 @@ from urllib.parse import urlparseimport pytestimport yamlfrom botocore.exceptions import ClientError-from conftest import iam_user, routed_request+from conftest import inprocess_iam_user, routed_requestfrom ministack.core.responses import set_request_regionfrom ministack.services import apigateway_v1@@ -1389,21 +1389,21 @@ _ALLOW_INVOKE = {"Statement": [{"Effect": "Allow", "Action": "execute-api:Invokedef test_api_policy_naming_the_user_allows_without_identity_policy(auth):- key, user = iam_user()+ key, user = inprocess_iam_user()api_id = _policy_api(_api_policy(("Allow", {"AWS": user})))assert _invoke(api_id, "iam", key)[0] == 200def test_api_policy_naming_the_account_needs_an_identity_policy(auth):api_id = _policy_api(_api_policy(("Allow", _ACCOUNT)))- key, _user = iam_user()+ key, _user = inprocess_iam_user()assert _invoke(api_id, "iam", key)[0] == 403- key, _user = iam_user(_ALLOW_INVOKE)+ key, _user = inprocess_iam_user(_ALLOW_INVOKE)assert _invoke(api_id, "iam", key)[0] == 200def test_api_policy_deny_beats_an_identity_allow(auth):- key, user = iam_user(_ALLOW_INVOKE)+ key, user = inprocess_iam_user(_ALLOW_INVOKE)api_id = _policy_api(_api_policy(("Allow", _ACCOUNT), ("Deny", {"AWS": user})))status, _headers, body = _invoke(api_id, "iam", key)assert status == 403@@ -1414,7 +1414,7 @@ def test_api_policy_deny_beats_an_identity_allow(auth):def test_api_policy_applies_to_a_call_signed_for_another_region(auth):- key, user = iam_user(_ALLOW_INVOKE)+ key, user = inprocess_iam_user(_ALLOW_INVOKE)try:api_id = _policy_api(_api_policy(("Allow", _ACCOUNT), ("Deny", {"AWS": user})), region="eu-west-1")finally:diff --git a/tests/test_ci_sharding.py b/tests/test_ci_sharding.pynew file mode 100644index 00000000..b8246b7c--- /dev/null+++ b/tests/test_ci_sharding.py@@ -0,0 +1,37 @@+"""Exercise CI collection with real pytest markers, including auth exclusions."""++import json+import os+import subprocess+import sys+from pathlib import Path+++def test_auth_contracts_are_excluded_from_existing_shards(tmp_path):+ (tmp_path / "pytest.ini").write_text(+ "[pytest]\nmarkers =\n serial\n data_plane\n auth_contract\n"+ )+ (tmp_path / "test_lanes.py").write_text(+ "import pytest\n"+ "def test_parallel(): pass\n"+ "@pytest.mark.serial\ndef test_serial(): pass\n"+ "@pytest.mark.data_plane\ndef test_data_plane(): pass\n"+ "@pytest.mark.auth_contract\n"+ "@pytest.mark.parametrize('value', [1, 2])\ndef test_auth(value): pass\n"+ "@pytest.mark.auth_contract\[email protected]\ndef test_auth_serial(): pass\n"+ "@pytest.mark.auth_contract\[email protected]_plane\ndef test_auth_data_plane(): pass\n"+ )+ (tmp_path / "test_auth_only.py").write_text(+ "import pytest\[email protected]_contract\ndef test_only_auth(): pass\n"+ )+ scripts = Path(__file__).resolve().parents[1] / "scripts"+ env = {**os.environ, "PYTHONPATH": str(scripts)}+ # Parent pytest flags must not change the nested collection's selection.+ env.pop("PYTEST_ADDOPTS", None)+ result = subprocess.run(+ [sys.executable, "-m", "pytest", "--collect-only", "-q", "-p", "_collect_plan_plugin"],+ cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ counts = json.loads((tmp_path / ".pytest_collect_plan.json").read_text())+ assert counts == {"test_lanes.py": {"parallel": 1, "serial": 1, "data_plane": 1}}diff --git a/tests/test_ecr.py b/tests/test_ecr.pyindex e5417e6b..f3954bf2 100644--- a/tests/test_ecr.py+++ b/tests/test_ecr.py@@ -7,7 +7,7 @@ import boto3import pytestimport requestsfrom botocore.exceptions import ClientError-from conftest import iam_user, routed_request+from conftest import inprocess_iam_user, routed_requestfrom ministack.core.responses import (get_account_id,@@ -174,20 +174,20 @@ _ALLOW_ECR = {"Statement": [{"Effect": "Allow", "Action": "ecr:*", "Resource": "def test_repository_policy_naming_the_user_allows_without_identity_policy(auth):- key, user = iam_user()+ key, user = inprocess_iam_user()assert _list_images(key, _policy_repository("Allow", user)) == (200, None)def test_repository_policy_naming_the_account_needs_an_identity_policy(auth):name = _policy_repository("Allow", "arn:aws:iam::000000000000:root")- key, _user = iam_user()+ key, _user = inprocess_iam_user()assert _list_images(key, name) == (403, "AccessDeniedException")- key, _user = iam_user(_ALLOW_ECR)+ key, _user = inprocess_iam_user(_ALLOW_ECR)assert _list_images(key, name) == (200, None)def test_repository_policy_deny_beats_an_identity_allow(auth):- key, user = iam_user(_ALLOW_ECR)+ key, user = inprocess_iam_user(_ALLOW_ECR)name = _policy_repository("Deny", user)assert _list_images(key, name) == (403, "AccessDeniedException")assert _list_images(key, name, "message") == (403, (diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex 40a3930b..8d7a3a93 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -3633,8 +3633,6 @@ class TestS3EnforcementSites:"Effect": "Allow", "Action": "s3:DeleteObject", "Resource": "arn:aws:s3:::iam-sites-b/a.txt"}]}_EVERY_KEY = {"Statement": [{"Effect": "Allow", "Action": "s3:DeleteObject", "Resource": "arn:aws:s3:::iam-sites-b/*"}]}- _WRITE_ONLY = {"Statement": [{- "Effect": "Allow", "Action": "s3:PutObject", "Resource": "arn:aws:s3:::iam-sites-dst/*"}]}def test_vhost_batch_delete_is_denied_on_the_second_key(self, monkeypatch):seen = self._stub_evaluator(monkeypatch, self._ONLY_FIRST_KEY)@@ -3650,15 +3648,6 @@ class TestS3EnforcementSites:assert status != 403assert [a for a, _ in seen] == ["s3:DeleteObject", "s3:DeleteObject"]- def test_vhost_copy_without_read_on_the_source_is_denied(self, monkeypatch):- seen = self._stub_evaluator(monkeypatch, self._WRITE_ONLY)- status, _headers, body = self._vhost(- "iam-sites-dst", "/k", "PUT", {"x-amz-copy-source": "/iam-sites-src/k"}, b"", {})- assert status == 403- assert b"AccessDenied" in body- assert seen == [("s3:PutObject", "arn:aws:s3:::iam-sites-dst/k"),- ("s3:GetObject", "arn:aws:s3:::iam-sites-src/k")]-def test_path_style_batch_delete_is_denied_on_the_second_key(self, monkeypatch):seen = self._stub_evaluator(monkeypatch, self._ONLY_FIRST_KEY)status, _headers, body = self._path_style("POST", "/iam-sites-b", {}, self._BATCH, {"delete": ""})@@ -3673,15 +3662,6 @@ class TestS3EnforcementSites:assert status != 403assert [a for a, _ in seen] == ["s3:DeleteObject", "s3:DeleteObject"]- def test_path_style_copy_without_read_on_the_source_is_denied(self, monkeypatch):- seen = self._stub_evaluator(monkeypatch, self._WRITE_ONLY)- status, _headers, body = self._path_style(- "PUT", "/iam-sites-dst/k", {"x-amz-copy-source": "/iam-sites-src/k"}, b"", {})- assert status == 403- assert b"AccessDenied" in body- assert seen == [("s3:PutObject", "arn:aws:s3:::iam-sites-dst/k"),- ("s3:GetObject", "arn:aws:s3:::iam-sites-src/k")]-def test_a_primary_denial_stops_before_the_extra_checks(self, monkeypatch):seen = self._stub_evaluator(monkeypatch, {"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]})diff --git a/tests/test_kms.py b/tests/test_kms.pyindex 5f276b49..69d27d7b 100644--- a/tests/test_kms.py+++ b/tests/test_kms.py@@ -10,7 +10,7 @@ import boto3import pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError, ParamValidationError-from conftest import iam_user, routed_request+from conftest import inprocess_iam_user, routed_requestENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")@@ -1076,28 +1076,28 @@ _DENIED = (403, "AccessDeniedException")def test_key_policy_naming_the_user_allows_without_identity_policy(auth_key):- access_key, user = iam_user()+ access_key, user = inprocess_iam_user()key_id = auth_key(("Allow", user, "kms:Encrypt"))assert _kms_call(access_key, "Encrypt", key_id) == (200, None)assert _kms_call(access_key, "GenerateDataKey", key_id) == _DENIEDdef test_key_policy_that_names_neither_user_nor_account_denies_an_identity_allow(auth_key):- access_key, user = iam_user(_ALLOW_KMS)+ access_key, user = inprocess_iam_user(_ALLOW_KMS)key_id = auth_key(("Allow", "arn:aws:iam::000000000000:user/someone-else", "kms:*"))assert _kms_call(access_key, "GenerateDataKey", key_id) == _DENIEDdef test_default_key_policy_hands_the_decision_to_identity_policies(auth_key):key_id = auth_key()- access_key, _user = iam_user()+ access_key, _user = inprocess_iam_user()assert _kms_call(access_key, "GenerateDataKey", key_id) == _DENIED- access_key, _user = iam_user(_ALLOW_KMS)+ access_key, _user = inprocess_iam_user(_ALLOW_KMS)assert _kms_call(access_key, "GenerateDataKey", key_id) == (200, None)def test_key_policy_deny_beats_an_identity_allow(auth_key):- access_key, user = iam_user(_ALLOW_KMS)+ access_key, user = inprocess_iam_user(_ALLOW_KMS)key_id = auth_key(("Allow", "arn:aws:iam::000000000000:root", "kms:*"), ("Deny", user, "kms:GenerateDataKey"))assert _kms_call(access_key, "GenerateDataKey", key_id) == _DENIEDassert _kms_call(access_key, "GenerateDataKey", key_id, "message") == (403, (diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 6ffa1f61..dc49f87a 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -26,7 +26,7 @@ from conftest import (ENDPOINT,LoopProbe,concurrent_burst,- iam_user,+ inprocess_iam_user,make_probe_lambda,patch_endpoint_dns,routed_request,@@ -4995,7 +4995,7 @@ def granted_function(monkeypatch):def test_function_policy_naming_the_user_allows_without_identity_policy(granted_function):- key, user = iam_user()+ key, user = inprocess_iam_user()name = granted_function(user)assert routed_request(key, "lambda", "GET", f"/2015-03-31/functions/{name}")[0] == 200status, _headers, body = routed_request(key, "lambda", "GET", f"/2015-03-31/functions/{name}/configuration")@@ -5003,7 +5003,7 @@ def test_function_policy_naming_the_user_allows_without_identity_policy(granted_def test_function_policy_applies_to_a_call_naming_the_function_by_arn(granted_function):- key, user = iam_user()+ key, user = inprocess_iam_user()name = granted_function(user)arn = quote(f"arn:aws:lambda:us-east-1:000000000000:function:{name}", safe="")assert routed_request(key, "lambda", "GET", f"/2015-03-31/functions/{arn}")[0] == 200@@ -5011,10 +5011,10 @@ def test_function_policy_applies_to_a_call_naming_the_function_by_arn(granted_fudef test_function_policy_naming_the_account_needs_an_identity_policy(granted_function):name = granted_function("000000000000")- key, _user = iam_user()+ key, _user = inprocess_iam_user()status, _headers, body = routed_request(key, "lambda", "GET", f"/2015-03-31/functions/{name}")assert (status, json.loads(body)["__type"]) == (403, "AccessDeniedException")- key, _user = iam_user({"Statement": [{"Effect": "Allow", "Action": "lambda:GetFunction", "Resource": "*"}]})+ key, _user = inprocess_iam_user({"Statement": [{"Effect": "Allow", "Action": "lambda:GetFunction", "Resource": "*"}]})assert routed_request(key, "lambda", "GET", f"/2015-03-31/functions/{name}")[0] == 200diff --git a/tests/test_ministack.py b/tests/test_ministack.pyindex 741024b1..6281fd7d 100644--- a/tests/test_ministack.py+++ b/tests/test_ministack.py@@ -61,6 +61,8 @@ def test_ministack_health_endpoints():assert resp_health.status == 200data_health = json.loads(resp_health.read())assert "services" in data_health+ assert data_health["auth"] in {"enabled", "disabled"}+ assert "auth_enabled" not in data_healthassert "s3" in data_health["services"]assert data_health["edition"] == "light"@@ -1273,3 +1275,59 @@ def test_failed_docker_hub_pull_falls_back_to_a_mirror_and_keeps_the_name(monkeywith pytest.raises(APIError, match="registry unavailable"):ImageCollection.pull(None, "public.ecr.aws/lambda/python:3.12")assert pulled == ["public.ecr.aws/lambda/python:3.12"]++[email protected]_contract+def test_ministack_auth_unset_is_permissive(tmp_path):+ """Exercise a fresh HTTP server without AUTH, even in the strict CI job."""+ import socket+ import subprocess+ import sys+ import time+ import urllib.request+ from contextlib import closing+ from pathlib import Path++ import boto3+ from botocore.config import Config++ with socket.socket() as listener:+ listener.bind(("127.0.0.1", 0))+ port = listener.getsockname()[1]+ endpoint = f"http://127.0.0.1:{port}"+ env = {**os.environ, "IOT_MTLS_ENABLED": "0", "PERSIST_STATE": "0", "S3_PERSIST": "0"}+ env.pop("AUTH", None)+ env.pop("LOCALSTACK_PERSISTENCE", None)+ log_path = tmp_path / "auth-unset.log"+ with log_path.open("w") as log:+ process = subprocess.Popen(+ [sys.executable, "-m", "hypercorn", "ministack.app:app", "--bind", f"127.0.0.1:{port}"],+ cwd=Path(__file__).resolve().parents[1], env=env, stdout=log, stderr=subprocess.STDOUT,+ )+ try:+ deadline = time.monotonic() + 30+ while time.monotonic() < deadline:+ if process.poll() is not None:+ pytest.fail(f"Default-mode server exited: {log_path.read_text()}")+ try:+ with urllib.request.urlopen(f"{endpoint}/_ministack/health", timeout=1) as response:+ health = json.load(response)+ break+ except OSError:+ time.sleep(0.1)+ else:+ pytest.fail(f"Default-mode server did not start: {log_path.read_text()}")+ assert health["auth"] == "disabled"+ with closing(boto3.client(+ "s3", endpoint_url=endpoint, region_name="us-east-1",+ aws_access_key_id="unregistered-auth-contract-key", aws_secret_access_key="dummy-secret",+ config=Config(retries={"total_max_attempts": 1}, connect_timeout=5, read_timeout=5),+ )) as client:+ assert "Buckets" in client.list_buckets()+ finally:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)diff --git a/tests/test_s3.py b/tests/test_s3.pyindex 44e4b08c..9d50ee1f 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -1,4 +1,5 @@import base64+import contextlibimport hashlibimport jsonimport os@@ -11,8 +12,9 @@ from datetime import datetimefrom urllib.parse import urlparseimport pytest+from botocore.config import Configfrom botocore.exceptions import ClientError-from conftest import iam_user, make_client, patch_endpoint_dns, routed_request, sqs_policy_allow_s3+from conftest import inprocess_iam_user, make_client, patch_endpoint_dns, routed_request, sqs_policy_allow_s3ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")@@ -1251,24 +1253,24 @@ _ALLOW_S3 = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action"def test_bucket_policy_naming_the_user_allows_without_identity_policy(auth):- key, user = iam_user()+ key, user = inprocess_iam_user()bucket = _policy_bucket("Allow", user)assert routed_request(key, "s3", "GET", f"/{bucket}/k")[0] == 200def test_bucket_policy_naming_the_account_needs_an_identity_policy(auth):bucket = _policy_bucket("Allow", "arn:aws:iam::000000000000:root")- key, _user = iam_user()+ key, _user = inprocess_iam_user()status, _headers, body = routed_request(key, "s3", "GET", f"/{bucket}/k")assert status == 403 and b"<Code>AccessDenied</Code>" in body- key, _user = iam_user(_ALLOW_S3)+ key, _user = inprocess_iam_user(_ALLOW_S3)assert routed_request(key, "s3", "GET", f"/{bucket}/k")[0] == 200def test_bucket_policy_deny_beats_an_identity_allow(auth):import xml.etree.ElementTree as ET- key, user = iam_user(_ALLOW_S3)+ key, user = inprocess_iam_user(_ALLOW_S3)bucket = _policy_bucket("Deny", user)status, _headers, body = routed_request(key, "s3", "GET", f"/{bucket}/k")assert status == 403 and b"<Code>AccessDenied</Code>" in body@@ -8235,777 +8237,73 @@ def test_s3_create_owned_bucket_again(s3):s3.delete_bucket(Bucket=west)-# Under AUTH=true a request without credentials is anonymous. S3 answers it only-# through the bucket owner's public grants (AllUsers ACL grants or a bucket policy-# for Principal "*", unless Public Access Block shuts them off); otherwise 403-# AccessDenied. Source: the S3 User Guide on anonymous requests and Block Public-# Access; not measured against AWS here.--def _anonymous_bucket(monkeypatch, auth=True, **bucket_headers):- import ministack.app as app_mod-- monkeypatch.setattr(app_mod, "AUTH", auth)- bucket = f"anon-{uuid.uuid4().hex[:10]}"- assert _lock_call("PUT", f"/{bucket}", bucket_headers)[0] == 200- assert _lock_call("PUT", f"/{bucket}/k", {}, b"secret")[0] == 200- return bucket---def _anonymous_call(method, path, headers=None, body=b"", internal=False):- import asyncio-- from ministack.core.responses import request_scope- from ministack.services import s3 as s3mod-- with request_scope("000000000000", "us-east-1"):- return asyncio.run(s3mod.handle_request(method, path, headers or {}, body, {}, internal=internal))---def _public_read_policy(bucket):- return json.dumps({"Version": "2012-10-17", "Statement": [{- "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject",- "Resource": f"arn:aws:s3:::{bucket}/*",- }]}).encode()---def test_anonymous_request_to_a_private_bucket_is_denied_under_auth(monkeypatch):- bucket = _anonymous_bucket(monkeypatch)- for method, path, body in [("GET", f"/{bucket}/k", b""), ("HEAD", f"/{bucket}/k", b""),- ("GET", f"/{bucket}/missing", b""), ("GET", f"/{bucket}", b""),- ("PUT", f"/{bucket}/new", b"x"), ("DELETE", f"/{bucket}/k", b"")]:- status, _, resp = _anonymous_call(method, path, body=body)- assert status == 403, (method, path)- if method != "HEAD":- assert b"<Code>AccessDenied</Code>" in resp- # The owner still reads it, and the object is still there.- status, _, resp = _lock_call("GET", f"/{bucket}/k")- assert (status, resp) == (200, b"secret")---def test_anonymous_request_reads_a_public_object_under_auth(monkeypatch):- bucket = _anonymous_bucket(monkeypatch)- assert _lock_call("PUT", f"/{bucket}/pub", {"x-amz-acl": "public-read"}, b"open")[0] == 200- status, _, resp = _anonymous_call("GET", f"/{bucket}/pub")- assert (status, resp) == (200, b"open")- assert _anonymous_call("GET", f"/{bucket}/k")[0] == 403---def test_anonymous_request_follows_a_public_bucket_policy_and_public_access_block(monkeypatch):- bucket = _anonymous_bucket(monkeypatch)- import asyncio-- from ministack.core.responses import request_scope- from ministack.services import s3 as s3mod-- with request_scope("000000000000", "us-east-1"):- status, _, _ = asyncio.run(s3mod.handle_request(- "PUT", f"/{bucket}", {"authorization": _ROOT_AUTHORIZATION}, _public_read_policy(bucket),- {"policy": [""]}))- assert status == 204- status, _, resp = _anonymous_call("GET", f"/{bucket}/k")- assert (status, resp) == (200, b"secret")- # The policy allows only s3:GetObject.- assert _anonymous_call("PUT", f"/{bucket}/k", body=b"overwrite")[0] == 403-- block = (b"<PublicAccessBlockConfiguration><RestrictPublicBuckets>true</RestrictPublicBuckets>"- b"</PublicAccessBlockConfiguration>")- with request_scope("000000000000", "us-east-1"):- status, _, _ = asyncio.run(s3mod.handle_request(- "PUT", f"/{bucket}", {"authorization": _ROOT_AUTHORIZATION}, block, {"publicAccessBlock": [""]}))- assert status == 200- assert _anonymous_call("GET", f"/{bucket}/k")[0] == 403---def test_anonymous_request_is_served_without_auth(monkeypatch):- bucket = _anonymous_bucket(monkeypatch, auth=False)- status, _, resp = _anonymous_call("GET", f"/{bucket}/k")- assert (status, resp) == (200, b"secret")---def test_internal_call_without_credentials_is_not_anonymous(monkeypatch):- bucket = _anonymous_bucket(monkeypatch)- assert _anonymous_call("PUT", f"/{bucket}/delivered", body=b"x", internal=True)[0] == 200-# ----------------------------------------------------------------------------# Bucket home region (#2158)-# -----------------------------------------------------------------------------[email protected]("headers,query,expected", [- ({"authorization": "AWS4-HMAC-SHA256 Credential=AKID/20261012/eu-west-1/s3/aws4_request, "- "SignedHeaders=host, Signature=abc"}, {}, "eu-west-1"),- ({}, {"X-Amz-Algorithm": ["AWS4-HMAC-SHA256"],- "X-Amz-Credential": ["AKID/20261012/us-west-2/s3/aws4_request"]}, "us-west-2"),- ({"authorization": "AWS4-HMAC-SHA256 Credential=AKID/20261012/eu-west-1/sqs/aws4_request, "- "SignedHeaders=host, Signature=abc"}, {}, None),- ({"authorization": "AWS4-ECDSA-P256-SHA256 Credential=AKID/20261012/s3/aws4_request, "- "SignedHeaders=host, Signature=abc", "x-amz-region-set": "eu-west-1"}, {}, None),- ({"authorization": "AWS AKID:sig"}, {}, None),- ({}, {}, None),- ({"authorization": "AWS4-HMAC-SHA256 Credential=broken"}, {}, None),-])-def test_s3_signed_region(headers, query, expected):- from ministack.services import s3 as s3_svc-- assert s3_svc._signed_region(headers, query) == expected---def test_s3_error_extra_elements_and_headers():- from xml.etree.ElementTree import fromstring-- from ministack.services import s3 as s3_svc-- status, headers, body = s3_svc._error("Plain", "msg", 400, "/b")- assert status == 400 and headers == {"Content-Type": "application/xml"}- assert [c.tag for c in fromstring(body)] == ["Code", "Message", "Resource", "RequestId"]-- status, headers, body = s3_svc._error(- "PermanentRedirect", "moved", 301, "/b",- extra={"Endpoint": "b.s3-eu-west-1.amazonaws.com", "Bucket": "b"},- headers={"x-amz-bucket-region": "eu-west-1"},- )- root = fromstring(body)- assert status == 301- assert headers == {"Content-Type": "application/xml", "x-amz-bucket-region": "eu-west-1"}- assert [c.tag for c in root] == ["Code", "Message", "Resource", "Endpoint", "Bucket", "RequestId"]- assert root.findtext("Endpoint") == "b.s3-eu-west-1.amazonaws.com"---def test_s3_list_buckets_region_filter(s3):- tag = _uuid_mod.uuid4().hex[:8]- east = [f"lbr-{tag}-e{i}" for i in range(2)]- west = [f"lbr-{tag}-w{i}" for i in range(3)]- for name in east:- s3.create_bucket(Bucket=name)- for name in west:- s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})- euw1 = _regional_client("s3", "eu-west-1")- prefix = f"lbr-{tag}-"- try:- listed = euw1.list_buckets(Prefix=prefix, BucketRegion="eu-west-1")["Buckets"]- assert [b["Name"] for b in listed] == west- assert {b["BucketRegion"] for b in listed} == {"eu-west-1"}-- listed = s3.list_buckets(Prefix=prefix, BucketRegion="us-east-1")["Buckets"]- assert [b["Name"] for b in listed] == east-- # Pagination stays within the filter.- names, token = [], None- while True:- kwargs = {"Prefix": prefix, "BucketRegion": "eu-west-1", "MaxBuckets": 1}- if token:- kwargs["ContinuationToken"] = token- page = euw1.list_buckets(**kwargs)- names += [b["Name"] for b in page["Buckets"]]- token = page.get("ContinuationToken")- if not token:- break- assert names == west-- # No filter lists every region.- listed = euw1.list_buckets(Prefix=prefix)["Buckets"]- assert [b["Name"] for b in listed] == sorted(east + west)- finally:- for name in east:- s3.delete_bucket(Bucket=name)- for name in west:- euw1.delete_bucket(Bucket=name)---def test_s3_list_buckets_region_filter_must_match_endpoint(s3):- with pytest.raises(ClientError) as exc:- s3.list_buckets(BucketRegion="eu-west-1")- err = exc.value.response["Error"]- assert err["Code"] == "InvalidArgument"- assert err["Message"] == ("Requests with bucket-region specified must be made to the "- "corresponding regional endpoint")- assert err["ArgumentName"] == "bucket-region"- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400---def _raw_signed(method, path, region, host=None, presign=False, body=b""):- """Send a SigV4-signed S3 request without any client-side redirect- handling. ``host`` overrides the Host header (signed as sent)."""- import http.client-- from botocore.auth import S3SigV4Auth, S3SigV4QueryAuth- from botocore.awsrequest import AWSRequest- from botocore.credentials import Credentials-- parsed = urlparse(ENDPOINT)- netloc = host or parsed.netloc- req = AWSRequest(method=method, url=f"http://{netloc}{path}", data=body)- creds = Credentials("test", "test")- if presign:- S3SigV4QueryAuth(creds, "s3", region, expires=300).add_auth(req)- else:- req.headers["x-amz-content-sha256"] = hashlib.sha256(body).hexdigest()- S3SigV4Auth(creds, "s3", region).add_auth(req)- target = urlparse(req.url)- conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)- headers = {k: v for k, v in req.headers.items()}- headers["Host"] = netloc- conn.request(method, target.path + (f"?{target.query}" if target.query else ""), body=body or None,- headers=headers)- resp = conn.getresponse()- data = resp.read()- conn.close()- return resp.status, {k.lower(): v for k, v in resp.getheaders()}, data---def _xml_error(body):- from xml.etree.ElementTree import fromstring-- root = fromstring(body)- return {child.tag: child.text for child in root}---def euw1_bucket(s3):- name = f"home-euw1-{_uuid_mod.uuid4().hex[:8]}"- s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})- euw1 = _regional_client("s3", "eu-west-1")- euw1.put_object(Bucket=name, Key="k.txt", Body=b"hello")- yield name- for obj in euw1.list_objects_v2(Bucket=name).get("Contents", []):- euw1.delete_object(Bucket=name, Key=obj["Key"])- euw1.delete_bucket(Bucket=name)---_REDIRECT_MSG = ("The bucket you are attempting to access must be addressed using the specified "- "endpoint. Please send all future requests to this endpoint.")---def test_s3_wrong_region_get_is_permanent_redirect(euw1_bucket):- for presign in (False, True):- status, headers, body = _raw_signed("GET", f"/{euw1_bucket}/k.txt", "us-west-2", presign=presign)- assert status == 301, body- assert headers["x-amz-bucket-region"] == "eu-west-1"- err = _xml_error(body)- assert err["Code"] == "PermanentRedirect"- assert err["Message"] == _REDIRECT_MSG- assert err["Endpoint"] == f"{euw1_bucket}.s3-eu-west-1.amazonaws.com"- assert err["Bucket"] == euw1_bucket-- # A us-east-1 client on the global host is pointed at the global endpoint.- status, headers, body = _raw_signed("PUT", f"/{euw1_bucket}/new.txt", "us-east-1", body=b"x")- assert status == 301- assert _xml_error(body)["Endpoint"] == f"{euw1_bucket}.s3.amazonaws.com"- assert headers["x-amz-bucket-region"] == "eu-west-1"---def test_s3_wrong_region_head_is_bodiless_redirect(euw1_bucket):- for path in (f"/{euw1_bucket}", f"/{euw1_bucket}/k.txt"):- status, headers, body = _raw_signed("HEAD", path, "us-east-1")- assert (status, body) == (301, b"")- assert headers["x-amz-bucket-region"] == "eu-west-1"---def test_s3_wrong_region_at_home_endpoint_is_authorization_error(euw1_bucket):- host = f"s3.eu-west-1.{urlparse(ENDPOINT).netloc}"- status, headers, body = _raw_signed("GET", f"/{euw1_bucket}/k.txt", "us-east-1", host=host)- assert status == 400- err = _xml_error(body)- assert err["Code"] == "AuthorizationHeaderMalformed"- assert err["Message"] == ("The authorization header is malformed; the region 'us-east-1' is wrong; "- "expecting 'eu-west-1'")- assert err["Region"] == "eu-west-1"- assert "x-amz-bucket-region" not in headers-- vhost = f"{euw1_bucket}.s3.eu-west-1.{urlparse(ENDPOINT).netloc}"- status, headers, body = _raw_signed("GET", "/k.txt", "us-east-1", host=vhost, presign=True)- assert status == 400- err = _xml_error(body)- assert err["Code"] == "AuthorizationQueryParametersError"- assert err["Message"] == ("Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is "- "wrong; expecting 'eu-west-1'")- assert err["Region"] == "eu-west-1"-- status, headers, body = _raw_signed("HEAD", f"/{euw1_bucket}", "us-east-1", host=host)- assert (status, body) == (400, b"")- assert headers["x-amz-bucket-region"] == "eu-west-1"- status, headers, body = _raw_signed("HEAD", f"/{euw1_bucket}/k.txt", "us-east-1", host=host)- assert (status, body) == (400, b"")- assert "x-amz-bucket-region" not in headers---def test_s3_wrong_region_exemptions_and_match(euw1_bucket):- status, _, body = _raw_signed("GET", f"/{euw1_bucket}?location", "us-east-1")- assert status == 200 and b"eu-west-1" in body- status, _, body = _raw_signed("GET", "/", "ap-south-1")- assert status == 200 and euw1_bucket.encode() in body- status, _, body = _raw_signed("GET", f"/{euw1_bucket}/k.txt", "eu-west-1")- assert (status, body) == (200, b"hello")- status, _, _ = _raw_signed("GET", f"/no-such-{euw1_bucket}/k.txt", "us-west-2")- assert status == 404---def test_s3_unsigned_region_request_is_not_redirected(euw1_bucket):- """Anonymous requests carry no signing region, so a public-read object in- eu-west-1 answers 200 wherever the request lands."""- import urllib.request-- _regional_client("s3", "eu-west-1").put_object(Bucket=euw1_bucket, Key="public.txt", Body=b"open",- ACL="public-read")- with urllib.request.urlopen(f"{ENDPOINT}/{euw1_bucket}/public.txt") as resp:- assert (resp.status, resp.read()) == (200, b"open")---def test_s3_cross_region_boto3_follows_redirect(s3):- """boto3 configured for us-east-1 reaches a us-west-2 bucket through the- PermanentRedirect + x-amz-bucket-region it gets back."""- name = f"redir-usw2-{_uuid_mod.uuid4().hex[:8]}"- usw2 = _regional_client("s3", "us-west-2")- usw2.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})- try:- s3.put_object(Bucket=name, Key="a.txt", Body=b"redirected")- assert s3.get_object(Bucket=name, Key="a.txt")["Body"].read() == b"redirected"- assert [o["Key"] for o in s3.list_objects_v2(Bucket=name)["Contents"]] == ["a.txt"]- assert s3.head_bucket(Bucket=name)["ResponseMetadata"]["HTTPHeaders"]["x-amz-bucket-region"] == "us-west-2"- assert s3.head_object(Bucket=name, Key="a.txt")["ContentLength"] == 10- s3.delete_object(Bucket=name, Key="a.txt")- assert usw2.list_objects_v2(Bucket=name)["KeyCount"] == 0- finally:- usw2.delete_bucket(Bucket=name)---def test_s3_cross_region_copy_and_upload_part_copy(s3):- tag = _uuid_mod.uuid4().hex[:8]- src, dst = f"copy-src-usw2-{tag}", f"copy-dst-euw1-{tag}"- usw2, euw1 = _regional_client("s3", "us-west-2"), _regional_client("s3", "eu-west-1")- usw2.create_bucket(Bucket=src, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})- euw1.create_bucket(Bucket=dst, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})- part = b"p" * (5 * 1024 * 1024)- try:- usw2.put_object(Bucket=src, Key="obj", Body=b"copy me")- usw2.put_object(Bucket=src, Key="big", Body=part)- euw1.copy_object(Bucket=dst, Key="copied", CopySource={"Bucket": src, "Key": "obj"})- assert euw1.get_object(Bucket=dst, Key="copied")["Body"].read() == b"copy me"-- upload = euw1.create_multipart_upload(Bucket=dst, Key="multi")- etag = euw1.upload_part_copy(Bucket=dst, Key="multi", UploadId=upload["UploadId"], PartNumber=1,- CopySource={"Bucket": src, "Key": "big"})["CopyPartResult"]["ETag"]- euw1.complete_multipart_upload(Bucket=dst, Key="multi", UploadId=upload["UploadId"],- MultipartUpload={"Parts": [{"PartNumber": 1, "ETag": etag}]})- assert euw1.head_object(Bucket=dst, Key="multi")["ContentLength"] == len(part)- finally:- for client, bucket in ((usw2, src), (euw1, dst)):- for obj in client.list_objects_v2(Bucket=bucket).get("Contents", []):- client.delete_object(Bucket=bucket, Key=obj["Key"])- client.delete_bucket(Bucket=bucket)---# ----------------------------------------------------------------------------# Cross-Region Replication (#2158)-# -----------------------------------------------------------------------------_REPL_ROLE = "arn:aws:iam::000000000000:role/repl"---def _versioned_bucket(region, slug):- client = _regional_client("s3", region)- name = f"crr-{slug}-{_uuid_mod.uuid4().hex[:8]}"- kwargs = {} if region == "us-east-1" else {"CreateBucketConfiguration": {"LocationConstraint": region}}- client.create_bucket(Bucket=name, **kwargs)- client.put_bucket_versioning(Bucket=name, VersioningConfiguration={"Status": "Enabled"})- return client, name---def _replicate(client, src, dst, **rule):- rule = {"ID": "r1", "Status": "Enabled", "Destination": {"Bucket": f"arn:aws:s3:::{dst}"}, **rule}- client.put_bucket_replication(Bucket=src, ReplicationConfiguration={"Role": _REPL_ROLE, "Rules": [rule]})---def _purge(client, bucket):- lv = client.list_object_versions(Bucket=bucket)- for v in lv.get("Versions", []) + lv.get("DeleteMarkers", []):- client.delete_object(Bucket=bucket, Key=v["Key"], VersionId=v["VersionId"])- client.delete_bucket(Bucket=bucket)---def crr_pair():- """A us-east-1 source and an eu-west-1 destination, both versioned."""- use1, src = _versioned_bucket("us-east-1", "src")- euw1, dst = _versioned_bucket("eu-west-1", "dst")- yield use1, src, euw1, dst- _purge(use1, src)- _purge(euw1, dst)---def test_s3_replication_cross_region_replica_readable_in_destination(crr_pair):- use1, src, euw1, dst = crr_pair- _replicate(use1, src, dst, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Disabled"})- use1.put_object(Bucket=src, Key="a.txt", Body=b"across regions")- assert use1.head_object(Bucket=src, Key="a.txt")["ReplicationStatus"] == "COMPLETED"- replica = euw1.get_object(Bucket=dst, Key="a.txt")- assert replica["ReplicationStatus"] == "REPLICA"- assert replica["Body"].read() == b"across regions"---def _delete_markers(client, bucket, key):- return [m for m in client.list_object_versions(Bucket=bucket).get("DeleteMarkers", []) if m["Key"] == key]---def test_s3_delete_marker_replication_enabled_v2_rule(crr_pair):- use1, src, euw1, dst = crr_pair- _replicate(use1, src, dst, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Enabled"})- use1.put_object(Bucket=src, Key="gone.txt", Body=b"x")- use1.put_object(Bucket=src, Key="batch.txt", Body=b"y")- use1.delete_object(Bucket=src, Key="gone.txt")- use1.delete_objects(Bucket=src, Delete={"Objects": [{"Key": "batch.txt"}]})- for key in ("gone.txt", "batch.txt"):- assert len(_delete_markers(euw1, dst, key)) == 1- with pytest.raises(ClientError) as exc:- euw1.get_object(Bucket=dst, Key=key)- assert exc.value.response["Error"]["Code"] == "NoSuchKey"---def test_s3_delete_marker_replication_version_id_delete_stays_local(crr_pair):- use1, src, euw1, dst = crr_pair- _replicate(use1, src, dst, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Enabled"})- vid = use1.put_object(Bucket=src, Key="v.txt", Body=b"x")["VersionId"]- use1.delete_object(Bucket=src, Key="v.txt", VersionId=vid)- assert euw1.get_object(Bucket=dst, Key="v.txt")["Body"].read() == b"x"- assert _delete_markers(euw1, dst, "v.txt") == []--[email protected]("rule", [- {"Filter": {"Prefix": ""}, "DeleteMarkerReplication": {"Status": "Disabled"}},- {"Prefix": ""},- {"Filter": {"Tag": {"Key": "keep", "Value": "yes"}}, "DeleteMarkerReplication": {"Status": "Enabled"}},-], ids=["disabled", "v1-rule", "tag-filter"])-def test_s3_delete_marker_replication_not_replicated(crr_pair, rule):- use1, src, euw1, dst = crr_pair- _replicate(use1, src, dst, **rule)- use1.put_object(Bucket=src, Key="k.txt", Body=b"x", Tagging="keep=yes")- assert euw1.get_object(Bucket=dst, Key="k.txt")["Body"].read() == b"x"- use1.delete_object(Bucket=src, Key="k.txt")- assert _delete_markers(euw1, dst, "k.txt") == []- assert euw1.get_object(Bucket=dst, Key="k.txt")["Body"].read() == b"x"---def _replicated_keys(client, bucket):- return sorted(o["Key"] for o in client.list_objects_v2(Bucket=bucket).get("Contents", []))---def test_s3_replication_tag_filter_single_tag(crr_pair):- use1, src, euw1, dst = crr_pair- _replicate(use1, src, dst, Filter={"Tag": {"Key": "replicate", "Value": "yes"}},- DeleteMarkerReplication={"Status": "Disabled"})- use1.put_object(Bucket=src, Key="tagged", Body=b"1", Tagging="replicate=yes&other=1")- use1.put_object(Bucket=src, Key="wrong-value", Body=b"2", Tagging="replicate=no")- use1.put_object(Bucket=src, Key="untagged", Body=b"3")- use1.copy_object(Bucket=src, Key="copy-replaced", CopySource={"Bucket": src, "Key": "untagged"},- TaggingDirective="REPLACE", Tagging="replicate=yes")- use1.copy_object(Bucket=src, Key="copy-kept", CopySource={"Bucket": src, "Key": "tagged"})- assert _replicated_keys(euw1, dst) == ["copy-kept", "copy-replaced", "tagged"]- assert "ReplicationStatus" not in use1.head_object(Bucket=src, Key="untagged")---def test_s3_replication_tag_filter_and(crr_pair):- use1, src, euw1, dst = crr_pair- _replicate(use1, src, dst,- Filter={"And": {"Prefix": "logs/", "Tags": [{"Key": "a", "Value": "1"}, {"Key": "b", "Value": "2"}]}},- DeleteMarkerReplication={"Status": "Disabled"})- use1.put_object(Bucket=src, Key="logs/both", Body=b"x", Tagging="a=1&b=2")- use1.put_object(Bucket=src, Key="logs/one", Body=b"x", Tagging="a=1")- use1.put_object(Bucket=src, Key="data/both", Body=b"x", Tagging="a=1&b=2")- assert _replicated_keys(euw1, dst) == ["logs/both"]---def test_s3_two_way_replication_has_no_loop():- use1, a = _versioned_bucket("us-east-1", "a")- euw1, b = _versioned_bucket("eu-west-1", "b")- try:- _replicate(use1, a, b, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Disabled"})- _replicate(euw1, b, a, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Disabled"})- use1.put_object(Bucket=a, Key="from-a", Body=b"a")- euw1.put_object(Bucket=b, Key="from-b", Body=b"b")- for client, bucket in ((use1, a), (euw1, b)):- versions = client.list_object_versions(Bucket=bucket)["Versions"]- assert sorted(v["Key"] for v in versions) == ["from-a", "from-b"]- assert euw1.head_object(Bucket=b, Key="from-a")["ReplicationStatus"] == "REPLICA"- assert use1.head_object(Bucket=a, Key="from-b")["ReplicationStatus"] == "REPLICA"- assert use1.head_object(Bucket=a, Key="from-a")["ReplicationStatus"] == "COMPLETED"- finally:- _purge(use1, a)- _purge(euw1, b)---# ----------------------------------------------------------------------------# Multi-Region Access Points through S3 Control (#2158)-# -----------------------------------------------------------------------------_ACCOUNT = "000000000000"--+# IAM contracts: real HTTP against the server mode selected by CI.+# Evidence: existing IAM/action extraction tests and local MiniStack SDK calls;+# these tests are not observations from a real AWS account.@pytest.fixture-def s3control_dns():- """boto3 prefixes S3 Control hosts with the account id."""- with patch_endpoint_dns():- yield---def mrap_members():- """One bucket in us-east-1 and one in eu-west-1, each holding who.txt."""- tag = _uuid_mod.uuid4().hex[:8]- use1, use1_bucket = _versioned_bucket("us-east-1", f"mrap-{tag}-use1")- euw1, euw1_bucket = _versioned_bucket("eu-west-1", f"mrap-{tag}-euw1")- use1.put_object(Bucket=use1_bucket, Key="who.txt", Body=b"use1")- euw1.put_object(Bucket=euw1_bucket, Key="who.txt", Body=b"euw1")- yield use1, use1_bucket, euw1, euw1_bucket- for client, bucket in ((use1, use1_bucket), (euw1, euw1_bucket)):- try:- _purge(client, bucket)- except ClientError:- pass---def _mrap_name():- return f"mrap-{_uuid_mod.uuid4().hex[:10]}"---def test_s3_mrap_routes_default_for_records_persisted_before_routes():- from ministack.services import s3 as s3_svc-- legacy = {"Name": "old", "Alias": "a.mrap", "Regions": ["b1", "b2"], "CreatedAt": "2026-01-01T00:00:00Z"}- assert s3_svc.mrap_routes(legacy) == {"b1": 100, "b2": 100}- assert s3_svc.mrap_routes({**legacy, "Routes": {"b1": 0}}) == {"b1": 0, "b2": 100}---def _mrap_create(ctl, name, buckets):- token = ctl.create_multi_region_access_point(- AccountId=_ACCOUNT, ClientToken=_uuid_mod.uuid4().hex,- Details={"Name": name, "Regions": [{"Bucket": b} for b in buckets]})["RequestTokenARN"]- return ctl.describe_multi_region_access_point_operation(- AccountId=_ACCOUNT, RequestTokenARN=token)["AsyncOperation"]---def _mrap_delete(ctl, name):- token = ctl.delete_multi_region_access_point(- AccountId=_ACCOUNT, ClientToken=_uuid_mod.uuid4().hex, Details={"Name": name})["RequestTokenARN"]- return ctl.describe_multi_region_access_point_operation(- AccountId=_ACCOUNT, RequestTokenARN=token)["AsyncOperation"]---def test_s3_mrap_control_async_create_describe_delete(s3control_dns, mrap_members):- _, use1_bucket, _, euw1_bucket = mrap_members- ctl = _regional_client("s3control", "us-west-2")- name = _mrap_name()- op = _mrap_create(ctl, name, [use1_bucket, euw1_bucket])- assert re.fullmatch(rf"arn:aws:s3:us-west-2:{_ACCOUNT}:async-request/mrap/create/.+", op["RequestTokenARN"])- assert op["Operation"] == "CreateMultiRegionAccessPoint"- assert op["RequestStatus"] == "SUCCEEDED"- assert op["RequestParameters"]["CreateMultiRegionAccessPointRequest"]["Name"] == name- regions = op["ResponseDetails"]["MultiRegionAccessPointDetails"]["Regions"]- assert sorted(r["Name"] for r in regions) == ["eu-west-1", "us-east-1"]-- again = _mrap_create(ctl, name, [use1_bucket, euw1_bucket])- assert again["RequestStatus"] == "FAILED"- assert again["ResponseDetails"]["ErrorDetails"]["Code"] == "MultiRegionAccessPointAlreadyOwnedByYou"- assert again["ResponseDetails"]["ErrorDetails"]["Message"] == (- "You must provide a unique name for each Multi-Region Access Point in your account. "- "A MRAP with this name already exists.")-- deleted = _mrap_delete(ctl, name)- assert (deleted["Operation"], deleted["RequestStatus"]) == ("DeleteMultiRegionAccessPoint", "SUCCEEDED")- with pytest.raises(ClientError) as exc:- ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)- assert exc.value.response["Error"]["Code"] == "NoSuchMultiRegionAccessPoint"---def test_s3_mrap_control_async_validation_failures(s3control_dns, mrap_members):- use1, use1_bucket, _, euw1_bucket = mrap_members- ctl = _regional_client("s3control", "us-west-2")- name = _mrap_name()- op = _mrap_create(ctl, name, [use1_bucket, f"missing-{use1_bucket}"])- assert op["RequestStatus"] == "FAILED"- err = op["ResponseDetails"]["ErrorDetails"]- assert (err["Code"], err["Message"], err["Resource"]) == (- "NoSuchBucket", "The specified bucket does not exist.", name)- assert op["ResponseDetails"]["MultiRegionAccessPointDetails"]["Regions"] == []-- second_use1 = f"{use1_bucket}-2"- use1.create_bucket(Bucket=second_use1)- try:- op = _mrap_create(ctl, name, [use1_bucket, second_use1])- assert op["ResponseDetails"]["ErrorDetails"]["Code"] == "MultiRegionAccessPointSameBucketRegion"- assert op["ResponseDetails"]["ErrorDetails"]["Message"] == (- "The buckets specified must be part of different Regions.")- finally:- use1.delete_bucket(Bucket=second_use1)- with pytest.raises(ClientError):- ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)---def test_s3_mrap_control_read_get_list_policy(s3control_dns, mrap_members):- use1, use1_bucket, _, euw1_bucket = mrap_members- ctl = _regional_client("s3control", "us-west-2")- names = [_mrap_name(), _mrap_name()]- for name in names:- assert _mrap_create(ctl, name, [use1_bucket, euw1_bucket])["RequestStatus"] == "SUCCEEDED"- try:- ap = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=names[0])["AccessPoint"]- assert ap["Name"] == names[0]- assert re.fullmatch(r"[a-z][a-z0-9]{12}\.mrap", ap["Alias"])- assert ap["Status"] == "READY"- assert {(r["Bucket"], r["Region"], r["BucketAccountId"]) for r in ap["Regions"]} == {- (use1_bucket, "us-east-1", _ACCOUNT), (euw1_bucket, "eu-west-1", _ACCOUNT)}-- listed, token = [], None- while True:- kwargs = {"AccountId": _ACCOUNT, "MaxResults": 1, **({"NextToken": token} if token else {})}- page = ctl.list_multi_region_access_points(**kwargs)- listed += [a["Name"] for a in page["AccessPoints"]]- token = page.get("NextToken")- if not token:- break- assert set(names) <= set(listed)-- policy = json.dumps({"Version": "2012-10-17", "Statement": [{- "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{_ACCOUNT}:root"},- "Action": "s3:GetObject", "Resource": f"arn:aws:s3::{_ACCOUNT}:accesspoint/{ap['Alias']}/object/*"}]})- token = ctl.put_multi_region_access_point_policy(- AccountId=_ACCOUNT, ClientToken="p", Details={"Name": names[0], "Policy": policy})["RequestTokenARN"]- op = ctl.describe_multi_region_access_point_operation(AccountId=_ACCOUNT, RequestTokenARN=token)- assert op["AsyncOperation"]["RequestStatus"] == "SUCCEEDED"- doc = ctl.get_multi_region_access_point_policy(AccountId=_ACCOUNT, Name=names[0])["Policy"]- assert doc["Established"]["Policy"] == policy- assert doc["Proposed"]["Policy"] == policy-- with pytest.raises(ClientError) as exc:- use1.delete_bucket(Bucket=use1_bucket)- assert exc.value.response["Error"]["Code"] == "BucketHasAccessPointsAttached"- assert exc.value.response["Error"]["Message"] == "Bucket has access points attached and cannot be deleted."- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400- finally:- for name in names:- _mrap_delete(ctl, name)-- with pytest.raises(ClientError) as exc:- ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=names[0])- err = exc.value.response["Error"]- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404- assert err["Message"] == "The specified Multi-Region Access Point does not exist."- assert (err["MultiRegionAccessPointName"], err["AccountId"]) == (names[0], _ACCOUNT)---def test_s3_mrap_control_read_routes(s3control_dns, mrap_members):- _, use1_bucket, _, euw1_bucket = mrap_members- ctl, routes_ctl = _regional_client("s3control", "us-west-2"), _regional_client("s3control", "eu-west-1")- name = _mrap_name()- _mrap_create(ctl, name, [use1_bucket, euw1_bucket])- try:- alias = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)["AccessPoint"]["Alias"]- arn = f"arn:aws:s3::{_ACCOUNT}:accesspoint/{alias}"- routes = routes_ctl.get_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=arn)- assert routes["Mrap"] == arn- assert {(r["Bucket"], r["Region"], r["TrafficDialPercentage"]) for r in routes["Routes"]} == {- (use1_bucket, "us-east-1", 100), (euw1_bucket, "eu-west-1", 100)}-- def submit_error(updates, mrap=arn):- with pytest.raises(ClientError) as exc:- routes_ctl.submit_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=mrap, RouteUpdates=updates)- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400- return exc.value.response["Error"]-- assert submit_error([{"Bucket": use1_bucket, "TrafficDialPercentage": 50}]) == {- "Code": "InvalidRequest", "Message": "Request invalid"}- assert submit_error([{"Bucket": f"x-{use1_bucket}", "TrafficDialPercentage": 0}])["Message"] == (- "The provided Region or bucket is not part of the Multi-Region Access Point.")- assert submit_error([{"Bucket": use1_bucket, "TrafficDialPercentage": 0},- {"Bucket": euw1_bucket, "TrafficDialPercentage": 0}])["Message"] == (- "At least one Region or bucket in the Multi-Region Access Point must be configured to receive "- "traffic. Set at least one Region or bucket to Active, and then try again.")- assert submit_error([{"Bucket": use1_bucket, "TrafficDialPercentage": 0}], mrap=name)["Message"] == (- "Request invalid")-- routes_ctl.submit_multi_region_access_point_routes(- AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": use1_bucket, "TrafficDialPercentage": 0}])- dials = {r["Bucket"]: r["TrafficDialPercentage"]- for r in routes_ctl.get_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=arn)["Routes"]}- assert dials == {use1_bucket: 0, euw1_bucket: 100}- finally:- _mrap_delete(ctl, name)---def test_s3_mrap_control_region_rules(s3control_dns, mrap_members):- """Management operations are served only from us-west-2 and route- operations from five regions; anything else is redirected (observed)."""- _, use1_bucket, _, euw1_bucket = mrap_members- with pytest.raises(ClientError) as exc:- _mrap_create(_regional_client("s3control", "us-east-1"), _mrap_name(), [use1_bucket, euw1_bucket])- err = exc.value.response["Error"]- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 301- assert err["Code"] == "PermanentRedirect"- assert err["Message"] == ("This API operation is only available in the following Regions: us-west-2. "- "Make sure to send all future requests to a supported Region.")- assert err["Endpoint"] == "https://s3-control.us-west-2.amazonaws.com/v20180820/async-requests/mrap/create"-- ctl = _regional_client("s3control", "us-west-2")- name = _mrap_name()- _mrap_create(ctl, name, [use1_bucket, euw1_bucket])- try:- alias = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)["AccessPoint"]["Alias"]- arn = f"arn:aws:s3::{_ACCOUNT}:accesspoint/{alias}"- with pytest.raises(ClientError) as exc:- _regional_client("s3control", "eu-central-1").submit_multi_region_access_point_routes(- AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": use1_bucket, "TrafficDialPercentage": 0}])- assert exc.value.response["Error"]["Message"] == (- "This API operation is only available in the following Regions: us-west-2, ap-southeast-2, "- "ap-northeast-1, eu-west-1 and us-east-1. Make sure to send all future requests to a supported Region.")- for region in ("us-east-1", "us-west-2", "eu-west-1", "ap-northeast-1", "ap-southeast-2"):- _regional_client("s3control", region).get_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=arn)-+def auth_s3_objects(s3):+ """Two private buckets with one source object; isolate and clean every test."""+ with contextlib.ExitStack() as cleanup:+ source = f"auth-source-{uuid.uuid4().hex}"+ destination = f"auth-dest-{uuid.uuid4().hex}"+ for bucket in (source, destination):+ s3.create_bucket(Bucket=bucket)+ cleanup.callback(s3.delete_bucket, Bucket=bucket)+ s3.put_object(Bucket=source, Key="source", Body=b"auth-contract")+ cleanup.callback(s3.delete_object, Bucket=source, Key="source")+ # Register before the test so even an unexpected successful write is removed.+ cleanup.callback(s3.delete_object, Bucket=destination, Key="copied")+ yield source, destination++[email protected]_contract[email protected]("permission", ["none", "allow", "explicit-deny", "other-resource"])+def test_s3_read_permission_contract(auth_enabled, iam_user, auth_s3_objects, permission):+ source, _ = auth_s3_objects+ statements = []+ if permission != "none":+ resource = f"arn:aws:s3:::{source}/" + ("other" if permission == "other-resource" else "source")+ statements.append({"Effect": "Allow", "Action": "s3:GetObject", "Resource": resource})+ if permission == "explicit-deny":+ statements.append({"Effect": "Deny", "Action": "s3:GetObject", "Resource": f"arn:aws:s3:::{source}/source"})+ policy = {"Version": "2012-10-17", "Statement": statements} if statements else None+ client = iam_user(policy=policy).client("s3")+ if auth_enabled and permission != "allow":with pytest.raises(ClientError) as exc:- ctl.get_multi_region_access_point(AccountId="111122223333", Name=name)+ client.get_object(Bucket=source, Key="source")assert exc.value.response["Error"]["Code"] == "AccessDenied"assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403- finally:- _mrap_delete(ctl, name)---def _mrap_request(alias, method, key, body=b""):- import http.client-- parsed = urlparse(ENDPOINT)- conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)- conn.request(method, f"/{key}", body=body or None,- headers={"Host": f"{alias}.accesspoint.s3-global.amazonaws.com"})- resp = conn.getresponse()- data = resp.read()- conn.close()- return resp.status, data---def test_s3_mrap_end_to_end_routing_failover_and_replication(s3control_dns, mrap_members):- use1, use1_bucket, euw1, euw1_bucket = mrap_members- _replicate(use1, use1_bucket, euw1_bucket, Filter={"Prefix": "data/"},- DeleteMarkerReplication={"Status": "Disabled"})- _replicate(euw1, euw1_bucket, use1_bucket, Filter={"Prefix": "data/"},- DeleteMarkerReplication={"Status": "Disabled"})- ctl, routes_ctl = _regional_client("s3control", "us-west-2"), _regional_client("s3control", "eu-west-1")- name = _mrap_name()- # Listed eu-west-1 first: the us-east-1 member wins on region, not position.- _mrap_create(ctl, name, [euw1_bucket, use1_bucket])- alias = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)["AccessPoint"]["Alias"]- arn = f"arn:aws:s3::{_ACCOUNT}:accesspoint/{alias}"- try:- for region in ("us-east-1", "eu-west-1", None):- assert _mrap_get(alias, "who.txt", region=region) == (200, "use1")+ else:+ response = client.get_object(Bucket=source, Key="source")+ with response["Body"] as body:+ assert body.read() == b"auth-contract"- routes_ctl.submit_multi_region_access_point_routes(- AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": use1_bucket, "TrafficDialPercentage": 0}])- assert _mrap_get(alias, "who.txt") == (200, "euw1")- with pytest.raises(ClientError):- routes_ctl.submit_multi_region_access_point_routes(- AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": euw1_bucket, "TrafficDialPercentage": 0}])- assert _mrap_get(alias, "who.txt") == (200, "euw1")- assert _mrap_request(alias, "PUT", "data/new.txt", b"through mrap")[0] == 200- assert euw1.get_object(Bucket=euw1_bucket, Key="data/new.txt")["ReplicationStatus"] == "COMPLETED"- assert use1.get_object(Bucket=use1_bucket, Key="data/new.txt")["Body"].read() == b"through mrap"- finally:- _mrap_delete(ctl, name)- assert _mrap_request(alias, "GET", "who.txt")[0] in (403, 404)[email protected]_contract[email protected]("addressing_style", ["path", "virtual"])[email protected]("allow_source_read", [False, True], ids=["no-source-read", "source-read"])+def test_s3_copy_permission_contract(+ auth_enabled, iam_user, s3, auth_s3_objects, addressing_style, allow_source_read,+):+ source, destination = auth_s3_objects+ statements = [{"Effect": "Allow", "Action": "s3:PutObject", "Resource": f"arn:aws:s3:::{destination}/*"}]+ if allow_source_read:+ statements.append({"Effect": "Allow", "Action": "s3:GetObject", "Resource": f"arn:aws:s3:::{source}/*"})+ client = iam_user(policy={"Version": "2012-10-17", "Statement": statements}).client(+ "s3", config=Config(signature_version="s3v4", s3={"addressing_style": addressing_style}),+ )+ request = {"Bucket": destination, "Key": "copied", "CopySource": {"Bucket": source, "Key": "source"}}+ with patch_endpoint_dns():+ if auth_enabled and not allow_source_read:+ with pytest.raises(ClientError) as exc:+ client.copy_object(**request)+ assert exc.value.response["Error"]["Code"] == "AccessDenied"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ # A rejected request must not leave the destination object behind.+ assert s3.list_objects_v2(Bucket=destination).get("Contents", []) == []+ else:+ response = client.copy_object(**request)+ assert response["ResponseMetadata"]["HTTPStatusCode"] == 200+ result = s3.get_object(Bucket=destination, Key="copied")+ with result["Body"] as body:+ assert body.read() == b"auth-contract"diff --git a/tests/test_secretsmanager.py b/tests/test_secretsmanager.pyindex b26699c5..5097325c 100644--- a/tests/test_secretsmanager.py+++ b/tests/test_secretsmanager.py@@ -7,7 +7,7 @@ import boto3import pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError-from conftest import iam_user, routed_request+from conftest import inprocess_iam_user, routed_requestdef _regional_sm(region_name):@@ -1012,20 +1012,20 @@ _ALLOW_SECRETS = {"Statement": [{"Effect": "Allow", "Action": "secretsmanager:*"def test_secret_policy_naming_the_user_allows_without_identity_policy(auth):- key, user = iam_user()+ key, user = inprocess_iam_user()assert _get_secret_value(key, _policy_secret("Allow", user)) == (200, None)def test_secret_policy_naming_the_account_needs_an_identity_policy(auth):arn = _policy_secret("Allow", "arn:aws:iam::000000000000:root")- key, _user = iam_user()+ key, _user = inprocess_iam_user()assert _get_secret_value(key, arn) == (403, "AccessDeniedException")- key, _user = iam_user(_ALLOW_SECRETS)+ key, _user = inprocess_iam_user(_ALLOW_SECRETS)assert _get_secret_value(key, arn) == (200, None)def test_secret_policy_deny_beats_an_identity_allow(auth):- key, user = iam_user(_ALLOW_SECRETS)+ key, user = inprocess_iam_user(_ALLOW_SECRETS)arn = _policy_secret("Deny", user)status, _headers, body = routed_request(key, "secretsmanager", "POST", "/", json.dumps({"SecretId": arn}).encode(),diff --git a/tests/test_sqs.py b/tests/test_sqs.pyindex b602cc71..3d94bff1 100644--- a/tests/test_sqs.py+++ b/tests/test_sqs.py@@ -12,7 +12,7 @@ import boto3import pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError-from conftest import REGION, iam_user, routed_request, sqs_policy_allow_s3, sqs_policy_allow_sns+from conftest import REGION, inprocess_iam_user, routed_request, sqs_policy_allow_s3, sqs_policy_allow_snsfrom ministack.core.iam_evaluator import EvalContext, evaluate_resource_policyfrom ministack.core.responses import get_account_id, request_scope@@ -2233,25 +2233,25 @@ class TestIdentityAndResourcePolicy:"""Same-account cases run in the default account, where IAM users live."""def test_queue_policy_naming_the_user_allows_without_identity_policy(self, auth):- key, user = iam_user()+ key, user = inprocess_iam_user()name = _uniq("rp-q")url = _make_queue(HOME, name, _grant("Allow", user, "sqs:SendMessage", _qarn(HOME, name)))assert _routed_send(key, url, "granted")[0] == 200assert _queue_bodies(_qarn(HOME, name)) == ["granted"]def test_queue_policy_naming_the_account_needs_an_identity_policy(self, auth):- key, _user = iam_user()+ key, _user = inprocess_iam_user()name = _uniq("rp-q")url = _make_queue(HOME, name, _grant("Allow", f"arn:aws:iam::{HOME}:root","sqs:SendMessage", _qarn(HOME, name)))status, headers, _body = _routed_send(key, url)assert status == 403assert headers["x-amzn-query-error"] == "AccessDenied;Sender"- key, _user = iam_user(_ALLOW_MESSAGING)+ key, _user = inprocess_iam_user(_ALLOW_MESSAGING)assert _routed_send(key, url)[0] == 200def test_queue_policy_deny_beats_an_identity_allow(self, auth):- key, user = iam_user(_ALLOW_MESSAGING)+ key, user = inprocess_iam_user(_ALLOW_MESSAGING)name = _uniq("rp-q")url = _make_queue(HOME, name, _grant("Deny", user, "sqs:SendMessage", _qarn(HOME, name)))status, headers, body = _routed_send(key, url)@@ -2263,21 +2263,21 @@ class TestIdentityAndResourcePolicy:assert _queue_bodies(_qarn(HOME, name)) == []def test_topic_policy_naming_the_user_allows_without_identity_policy(self, auth):- key, user = iam_user()+ key, user = inprocess_iam_user()arn = _make_topic(HOME, _uniq("rp-t"))_set_topic_policy(HOME, arn, _grant("Allow", user, "sns:Publish", arn))assert _resp_code(_routed_publish(key, arn)) == (200, "")def test_topic_policy_naming_the_account_needs_an_identity_policy(self, auth):- key, _user = iam_user()+ key, _user = inprocess_iam_user()arn = _make_topic(HOME, _uniq("rp-t"))_set_topic_policy(HOME, arn, _grant("Allow", HOME, "sns:Publish", arn))assert _resp_code(_routed_publish(key, arn)) == (403, "AuthorizationError")- key, _user = iam_user(_ALLOW_MESSAGING)+ key, _user = inprocess_iam_user(_ALLOW_MESSAGING)assert _resp_code(_routed_publish(key, arn)) == (200, "")def test_topic_policy_deny_beats_an_identity_allow(self, auth):- key, user = iam_user(_ALLOW_MESSAGING)+ key, user = inprocess_iam_user(_ALLOW_MESSAGING)arn = _make_topic(HOME, _uniq("rp-t"))_set_topic_policy(HOME, arn, _grant("Deny", user, "sns:Publish", arn))assert _resp_detail(_routed_publish(key, arn)) == (403, "AuthorizationError", (@@ -2285,27 +2285,27 @@ class TestIdentityAndResourcePolicy:"with an explicit deny in a resource-based policy"))def test_default_topic_policy_grants_nothing_to_a_user(self, auth):- key, _user = iam_user()+ key, _user = inprocess_iam_user()arn = _make_topic(HOME, _uniq("rp-t"))assert _resp_code(_routed_publish(key, arn)) == (403, "AuthorizationError")def test_cross_account_needs_both_policies(self, auth):name = _uniq("rp-q")- key, user = iam_user()+ key, user = inprocess_iam_user()url = _make_queue(ACCT_A, name, _grant("Allow", user, "sqs:SendMessage", _qarn(ACCT_A, name)))assert _routed_send(key, url)[0] == 403- key, user = iam_user(_ALLOW_MESSAGING)+ key, user = inprocess_iam_user(_ALLOW_MESSAGING)_as(ACCT_A, sqs_svc._act_set_queue_attributes, {"QueueUrl": url, "Attributes": {"Policy": json.dumps(_grant("Allow", user, "sqs:SendMessage", _qarn(ACCT_A, name)))}}, url)assert _routed_send(key, url)[0] == 200def test_cross_account_ignores_a_same_named_queue_of_the_caller(self, auth):name = _uniq("rp-q")- key, user = iam_user()+ key, user = inprocess_iam_user()home = _make_queue(HOME, name, _grant("Allow", user, "sqs:SendMessage", _qarn(HOME, name)))url = _make_queue(ACCT_A, name, _grant("Allow", user, "sqs:SendMessage", _qarn(ACCT_A, name)))assert _routed_send(key, url)[0] == 403- key, user = iam_user(_ALLOW_MESSAGING)+ key, user = inprocess_iam_user(_ALLOW_MESSAGING)_as(HOME, sqs_svc._act_set_queue_attributes, {"QueueUrl": home, "Attributes": {"Policy": json.dumps(_grant("Deny", user, "sqs:SendMessage", _qarn(HOME, name)))}}, home)_as(ACCT_A, sqs_svc._act_set_queue_attributes, {"QueueUrl": url, "Attributes": {