Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(s3): keep user metadata on presigned uploads (#1487)

Dennis Martinez964e63fcfb4b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 392aa378..02dbaae6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **S3 — a presigned upload no longer drops the `x-amz-*` headers it was signed with** — a presigned URL is sent by a caller who has only the URL and a body, so SigV4 lets the `x-amz-*` headers an operation asked for be hoisted into the query string, where the signature covers them exactly as a signed header would. SDKs presign that way and real S3 applies those params as the headers they stand for. MiniStack only ever read headers, so a presigned `PutObject` carrying user metadata in its query string answered `200` and stored the object with no metadata at all. Hoisted `x-amz-*` params are now folded back into the request headers before routing (user metadata, storage class, tagging, ACL, SSE and copy source) while an explicitly sent header still wins over its hoisted twin, and the SigV4 signing params are never mistaken for one. Contributed by @dennmart.
- **CloudFormation — `Fn::Sub` honors the `${!Literal}` escape** — the leading `!` was not recognized, so the name fell through every lookup and rendered as `!Literal` with the braces consumed; `${!Literal}` now renders as the literal `${Literal}` and no longer registers a dependency on a resource of that name. An `AWS::IoT::Policy` pinned to `${!iot:Connection.Thing.ThingName}` deployed with a document matching nothing, so the policy denied every connect, publish and subscribe while the stack still reported `CREATE_COMPLETE`. Reported by @iot-rocket.
### Added
- **EC2 — opt-in launch options for instance containers (`EC2_DOCKER_FLAGS`)** — a registered image that boots an operating system (systemd as PID 1) needs container options the fixed launch arguments cannot express: unprivileged, `unshare` fails with `Operation not permitted` and the instance terminates at boot. `EC2_DOCKER_FLAGS` now takes a docker-CLI-style string (`--privileged`, `--cap-add`, `-e`, `-v`, `--tmpfs`, `--add-host`, `-m`, `--shm-size`) applied to every instance container; unset, nothing changes. `--init` is refused — instance containers always run with init. Contributed by @iot-rocket.
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 803f39be..40fcc095 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -1543,6 +1543,54 @@ def _verify_presigned_sigv4(method, path, headers, query_params):
return None
+# SigV4 / SigV2 presign machinery: query parameters that are part of the
+# signature itself, never a hoisted request header.
+_PRESIGN_SIGNING_PARAMS = {
+ "x-amz-algorithm",
+ "x-amz-credential",
+ "x-amz-date",
+ "x-amz-expires",
+ "x-amz-signedheaders",
+ "x-amz-signature",
+ "x-amz-security-token",
+ "x-amz-content-sha256",
+}
+
+
+def _merge_hoisted_amz_headers(headers: dict, query_params: dict) -> dict:
+ """Fold a presigned URL's hoisted ``x-amz-*`` query params into headers.
+
+ A presigned URL is handed to a caller who sends nothing but the URL and a
+ body, so the ``x-amz-*`` headers the operation asked for — user metadata
+ (``x-amz-meta-*``), ACL, storage class, tagging, SSE, copy source — cannot
+ travel as headers. SigV4 allows them to be *hoisted* into the query string
+ instead, where the signature covers them exactly as a signed header would,
+ and several SDKs presign that way (some hoist every ``x-amz-`` header, some
+ only what the operation set). Real S3 applies those params as the headers
+ they stand for.
+
+ MiniStack only ever looked at headers, so a presigned upload carrying
+ metadata in its query string stored the object without any: the PUT
+ succeeded and the metadata was silently dropped.
+
+ An explicitly sent header always wins over its hoisted twin.
+ """
+ hoisted = None
+ for name, values in query_params.items():
+ lname = name.lower()
+ if not lname.startswith("x-amz-") or lname in _PRESIGN_SIGNING_PARAMS:
+ continue
+ if lname in headers:
+ continue
+ value = values[0] if isinstance(values, list) else values
+ if value is None:
+ continue
+ if hoisted is None:
+ hoisted = dict(headers)
+ hoisted[lname] = value
+ return hoisted if hoisted is not None else headers
+
+
async def handle_request(
method: str, path: str, headers: dict, body: bytes, query_params: dict,
signed_path: str | None = None,
@@ -1562,6 +1610,11 @@ async def handle_request(
resp_headers.setdefault("x-amz-id-2", base64.b64encode(os.urandom(48)).decode())
return status, resp_headers, resp_body
+ # A presigned URL may carry its `x-amz-*` headers in the query string; fold
+ # them back in before routing so metadata, ACL, storage class and friends
+ # reach the handlers exactly as a header-signed request delivers them.
+ headers = _merge_hoisted_amz_headers(headers, query_params)
+
result = _dispatch(method, bucket, key, headers, body, query_params)
status, resp_headers, resp_body = result
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 0d0810c3..49bf6ac8 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -3798,6 +3798,94 @@ def test_s3_presigned_url_virtual_hosted_style_is_verified():
assert code in (200, 204), f"vhost presigned PUT rejected with {code}"
+def test_s3_presigned_put_metadata_hoisted_into_query(s3):
+ """A presigned URL is sent by a caller who has only the URL and a body, so
+ the `x-amz-*` headers the operation asked for may be hoisted into the query
+ string, where the signature covers them like a signed header. Real S3
+ applies them as the headers they stand for, so user metadata (and storage
+ class, tagging, ...) must land on the object rather than being dropped."""
+ import urllib.request
+
+ from botocore.auth import S3SigV4QueryAuth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ bucket = "presign-hoisted-bkt"
+ key = "uploads/report.pdf"
+ s3.create_bucket(Bucket=bucket)
+
+ # Mixed-case `X-Amz-Meta-` too: header names are case-insensitive, and
+ # SDKs differ on the casing they hoist with.
+ hoisted = "&".join([
+ "x-amz-meta-author=alice",
+ "X-Amz-Meta-Title=quarterly%20report",
+ "x-amz-storage-class=STANDARD_IA",
+ "x-amz-tagging=env%3Dqa",
+ ])
+ signed = AWSRequest(method="PUT", url=f"{ENDPOINT}/{bucket}/{key}?{hoisted}")
+ S3SigV4QueryAuth(
+ Credentials("test", "test"), "s3", "us-east-1", expires=300
+ ).add_auth(signed)
+
+ resp = urllib.request.urlopen(
+ urllib.request.Request(signed.url, data=b"file-bytes", method="PUT"))
+ assert resp.status == 200
+
+ head = s3.head_object(Bucket=bucket, Key=key)
+ assert head["Metadata"] == {"author": "alice", "title": "quarterly report"}
+ assert head["StorageClass"] == "STANDARD_IA"
+ assert s3.get_object_tagging(Bucket=bucket, Key=key)["TagSet"] == [
+ {"Key": "env", "Value": "qa"}
+ ]
+
+
+def test_s3_presigned_put_metadata_sent_as_signed_headers(s3):
+ """The other half of the contract: when the presigner leaves the metadata
+ in `X-Amz-SignedHeaders` instead of hoisting it, the uploader sends the
+ `x-amz-meta-*` headers itself and they must still land on the object."""
+ import urllib.request
+
+ bucket = "presign-meta-hdr-bkt"
+ key = "uploads/report.pdf"
+ s3.create_bucket(Bucket=bucket)
+
+ url = s3.generate_presigned_url(
+ "put_object",
+ Params={"Bucket": bucket, "Key": key,
+ "Metadata": {"author": "alice", "title": "quarterly report"}},
+ ExpiresIn=300,
+ )
+ resp = urllib.request.urlopen(urllib.request.Request(
+ url, data=b"file-bytes", method="PUT",
+ headers={"x-amz-meta-author": "alice",
+ "x-amz-meta-title": "quarterly report"}))
+ assert resp.status == 200
+
+ head = s3.head_object(Bucket=bucket, Key=key)
+ assert head["Metadata"] == {"author": "alice", "title": "quarterly report"}
+
+
+def test_s3_presigned_post_metadata_fields(s3):
+ """A browser POST upload carries its metadata as `x-amz-meta-*` form
+ fields, which the policy signs; they must land on the object too."""
+ import requests
+
+ bucket = "presign-meta-post-bkt"
+ s3.create_bucket(Bucket=bucket)
+
+ post = s3.generate_presigned_post(
+ Bucket=bucket, Key="uploads/report.pdf",
+ Fields={"x-amz-meta-author": "alice"},
+ Conditions=[{"x-amz-meta-author": "alice"}],
+ )
+ r = requests.post(post["url"], data=post["fields"],
+ files={"file": ("report.pdf", b"file-bytes")})
+ assert r.status_code == 204
+
+ head = s3.head_object(Bucket=bucket, Key="uploads/report.pdf")
+ assert head["Metadata"] == {"author": "alice"}
+
+
def test_s3_eventbridge_notification_on_delete(s3, sqs, eb):
"""S3 delete_object should send EventBridge event when EventBridgeConfiguration is enabled."""
bucket = "s3-eb-del-bkt"