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
fix(s3): GetBucketLocation returns the bucket's stored region (#1347)
iot-rockete515544f5803
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1b3c090e..6295e0f8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,11 +7,11 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]-### Fixed- **CloudFormation — resources unchanged by a stack update are left alone** — every previously-provisioned resource was reprocessed on every stack update regardless of whether its properties changed, and any resource type with no dedicated update handler fell back to calling create again — a fallback whose own name-generation regenerated a fresh random suffix on every call, and whose caller passed the wrong id into it, on top of that. An auto-named resource's "idempotent" create (the type framework's own documented expectation) silently produced a brand new, empty resource under a new identity on every single update, orphaning the real one — and anything referencing it via `Ref`/`Fn::GetAtt` picked up that new, wrong identity the moment it was reprocessed later in the same update, since real CloudFormation does propagate a changed reference. Found via a DynamoDB table silently duplicating on an unrelated update to a real multi-stack deploy. A genuinely unchanged resource is no longer touched at all, matching real CloudFormation; auto-generated names are now a deterministic hash of (stack name, logical id) rather than random, so the remaining case — a resource's properties *did* change but its type still has no update handler — reproduces the same name it started with. Also fixes the same symptom for `AWS::Events::EventBus` (previously failed a stack update outright with "already exists" once created) and any other resource type with no update handler and no name-collision guard of its own. Contributed by @ryan-bennett.- **CloudFormation — `AWS::ApiGatewayV2::Authorizer` survives a property update** — the type had no update handler, so changing e.g. `JwtConfiguration.Audience` (trusting an additional app client) fell back to create — whose `authorizerId` is a random id on every call, with no stable name to derive from — minting a second, orphaned authorizer while every `Route`'s own (unchanged) `AuthorizerId` kept pointing at the original, now-stale one. A real update handler now mutates the existing authorizer record in place, matching API Gateway's own `UpdateAuthorizer`. Contributed by @ryan-bennett.- **CloudFormation — `AWS::SSM::Parameter::Value<...>` template parameters now resolve against SSM Parameter Store** — a template parameter typed `AWS::SSM::Parameter::Value<String>` (or `<List<String>>` / `<AWS::EC2::Image::Id>`) takes an SSM parameter *name* as its Default/provided value; real CloudFormation resolves that name against Parameter Store before `Ref` ever sees it — the mechanism behind, e.g., CDK's `StringParameter.valueForStringParameter`. MiniStack treated these like any other AWS-specific parameter type and passed the literal name straight through, so `Ref` returned the parameter's name instead of its stored value, and any resource property built from it (or a nested stack composing two independently-deployed stacks through a shared parameter) silently received the wrong string. Resolution now looks the name up in the SSM store at parameter-resolution time; a name that doesn't exist fails `CreateStack`/`UpdateStack` synchronously with a `ValidationError`, matching AWS. Contributed by @ryan-bennett.+- **S3 — `GetBucketLocation` returns the bucket's stored region** — two defects hid the region: a bucket created without a `CreateBucketConfiguration` stored no region at all (even when the request was signed for one), and the response suppressed the region whenever it equalled `MINISTACK_REGION`, so with the emulator homed in, say, `eu-central-1` a bucket in that region answered an empty `LocationConstraint` — which S3 clients read as us-east-1 and then mis-sign follow-up requests with. A bucket created with no explicit constraint now lands in the request's SigV4 signing region, as on AWS, and `GetBucketLocation` returns the empty `LocationConstraint` only for buckets literally in `us-east-1`, echoing every other region verbatim.- **S3 — versioned objects retain their custom metadata** — in a versioning-enabled bucket the per-version record stored only the wire basics (etag/size/storage class), dropping the object's `x-amz-meta-*` user metadata, preserved headers, and content-encoding; on top of that a `GetObject?versionId=` hand-built a five-header response that bypassed the only `x-amz-meta-*` emitter. A `PutObject` with `Metadata` followed by a `GetObject`/`HeadObject` of that version therefore came back with the metadata missing. Every version now stores its own metadata (across put, POST-form, copy, and multipart-complete), and versioned reads route through the shared header builder, so each version returns the metadata it was written with — matching S3, where metadata is per-version. Reported by @Kaphaalor.- **API Gateway (REST) — custom Lambda authorizers are invoked and enforced on the request path** — a method with `authorizationType: CUSTOM` stored its authorizer but never called it: requests reached the integration unauthenticated and `requestContext.authorizer` was never populated. `TOKEN` and `REQUEST` authorizers are now invoked on the data path with the AWS event shape (`type`/`authorizationToken`/`methodArn`, or the REQUEST parameter shape); a missing identity source returns `401` without invoking, the returned IAM policy is evaluated against the method ARN (explicit `Deny` and no-matching-`Allow` both `403`, an authorizer raising `Unauthorized` `401`), `authorizerResultTtlInSeconds` caches the decision, and on allow the returned `context` (values stringified) plus `principalId` are injected into `requestContext.authorizer`. `AWS_IAM` methods reject a request with no `Authorization` header (`403`); the SigV4 signature itself is not verified. Reported by @iot-rocket.- **Route 53 — a change is born `PENDING` and flips to `INSYNC`** — every `ChangeResourceRecordSets` / `CreateHostedZone` change was created `INSYNC`, so `GetChange` never returned `PENDING` and any waiter or poll loop (e.g. the `ResourceRecordSetsChanged` waiter) completed on its first read without exercising its retry path. Changes are now submitted `PENDING` and flip to `INSYNC` on the first `GetChange` read thereafter, reproducing the observable `PENDING`→`INSYNC` transition without a background timer. Reported by @jayjanssen.diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex d4166e07..605073db 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -1145,6 +1145,9 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):if err is not None:return err+ # No explicit LocationConstraint: the bucket lands in the region the+ # request was signed for, like real AWS.+ region = region or get_region()_buckets[name] = {"created": now_iso(), "objects": {}, "region": region}if tags:_bucket_tags[name] = tags@@ -1216,9 +1219,10 @@ def _get_bucket_location(name: str):if name not in _buckets:return _no_such_bucket(name)root = Element("LocationConstraint", xmlns=S3_NS)- region = _buckets[name].get("region")- # AWS returns empty LocationConstraint for us-east-1.- if region and region != os.environ.get("MINISTACK_REGION", "us-east-1"):+ region = _buckets[name].get("region") or os.environ.get("MINISTACK_REGION", "us-east-1")+ # AWS returns an empty LocationConstraint only for us-east-1 buckets;+ # every other region is echoed back verbatim.+ if region != "us-east-1":root.text = regionreturn 200, {"Content-Type": "application/xml"}, _xml_body(root)diff --git a/tests/test_s3.py b/tests/test_s3.pyindex 07da10a4..923b1af3 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -688,6 +688,48 @@ def test_s3_create_bucket_with_tags_and_location(s3):loc = s3.get_bucket_location(Bucket=bkt)assert loc["LocationConstraint"] == "us-west-2"+def test_s3_get_bucket_location_explicit_constraint(s3):+ """A bucket created with an explicit LocationConstraint must echo it back+ from GetBucketLocation."""+ bkt = f"intg-s3-loc-explicit-{_uuid_mod.uuid4().hex[:8]}"+ s3.create_bucket(+ Bucket=bkt,+ CreateBucketConfiguration={"LocationConstraint": "eu-west-1"},+ )+ loc = s3.get_bucket_location(Bucket=bkt)+ assert loc["LocationConstraint"] == "eu-west-1"++def test_s3_get_bucket_location_us_east_1_is_none(s3):+ """AWS returns an empty LocationConstraint for us-east-1 buckets, which+ boto3 surfaces as None."""+ bkt = f"intg-s3-loc-useast1-{_uuid_mod.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bkt)+ loc = s3.get_bucket_location(Bucket=bkt)+ assert loc["LocationConstraint"] is None++def test_s3_get_bucket_location_defaults_to_signing_region(s3):+ """A bucket created WITHOUT CreateBucketConfiguration lands in the region+ the request was signed for — GetBucketLocation must echo that region."""+ import boto3+ from botocore.config import Config++ west_s3 = boto3.client(+ "s3",+ endpoint_url=ENDPOINT,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name="eu-west-1",+ config=Config(+ region_name="eu-west-1",+ retries={"mode": "standard"},+ max_pool_connections=50,+ ),+ )+ bkt = f"intg-s3-loc-signing-{_uuid_mod.uuid4().hex[:8]}"+ west_s3.create_bucket(Bucket=bkt)+ loc = west_s3.get_bucket_location(Bucket=bkt)+ assert loc["LocationConstraint"] == "eu-west-1"+def test_s3_create_bucket_without_tags_has_no_tag_set(s3):"""A CreateBucket with no tags must not create an empty tag set — aGetBucketTagging should still return NoSuchTagSet."""