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
feat(s3): resolve S3 request condition keys under AUTH=true (#2279)
iot-rocketbed2f9bf7178
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9aed34e7..ab099a8f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **Auth — bucket policies see S3's request condition keys under `AUTH=true`** — `s3:x-amz-server-side-encryption`, `s3:x-amz-acl` and `s3:ExistingObjectTag/<key>` were absent from every request but a signed browser POST, so the common "require encryption" Deny refused even an `AES256` upload; a write now carries its encryption and canned ACL headers (an upload part and the completion the encryption header of their `CreateMultipartUpload`), and `GetObject` / `HeadObject` the object's tags, for bucket and identity policies alike. Contributed by @iot-rocket.### Fixed- **API Gateway — presigned calls to `AWS_IAM` REST methods under `AUTH=true`** — a request signed in its query string (`X-Amz-Signature`) with an IAM user or STS session key answered 403 `MissingAuthenticationTokenException` on an `AWS_IAM` method even when correctly signed; under `AUTH=true`, which verifies that signature, it now reaches the method as on AWS. Contributed by @iot-rocket.### Addeddiff --git a/ministack/app.py b/ministack/app.pyindex 5ad2539a..5dd7962c 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2293,7 +2293,7 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: ds3_resource = extract_resource_arn("s3", method, vhost_path, headers, body, query_params, "", "")denied = _enforce_data_plane("s3", f"s3:{s3_action}", headers, query_params, "", resource_arn=s3_resource,- service_context=s3_service_context(f"s3:{s3_action}", query_params),+ service_context=s3_service_context(f"s3:{s3_action}", query_params, vhost_path, headers),)if denied:return denied@@ -2811,7 +2811,7 @@ async def _dispatch_service_request()service_context = (dynamodb_service_context(body) if service == "dynamodb"- else s3_service_context(iam_action, query_params) if service == "s3"+ else s3_service_context(iam_action, query_params, path, headers) if service == "s3"else None)if service == "logs":diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex fb6dae89..50cd918a 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -1910,8 +1910,11 @@ def dynamodb_transaction_checks(return checks-def s3_service_context(iam_action: str, query_params: dict | None) -> dict:- """The s3:prefix, s3:delimiter and s3:max-keys a ListBucket or ListBucketVersions request sends."""+def s3_service_context(iam_action: str, query_params: dict | None, path: str = "",+ headers: dict | None = None) -> dict:+ """The S3 condition keys a request carries: listing keys, a write's encryption and ACL, a read's object tags."""+ if iam_action in ("s3:PutObject", "s3:GetObject", "s3:GetObjectVersion"):+ return _s3_object_context(iam_action, query_params or {}, path, headers or {})if iam_action not in ("s3:ListBucket", "s3:ListBucketVersions"):return {}context = {}@@ -1924,6 +1927,28 @@ def s3_service_context(iam_action: str, query_params: dict | None) -> dict:return context+def _s3_object_context(iam_action: str, query_params: dict, path: str, headers: dict) -> dict:+ """s3:x-amz-server-side-encryption and s3:x-amz-acl of a write, s3:ExistingObjectTag/<key> of a read."""+ from ministack.services import s3 as s3_svc++ bucket, _, key = path.lstrip("/").partition("/")+ context: dict = {}+ if not key:+ return context+ if iam_action == "s3:PutObject":+ # A part and the completion carry no headers: the upload's own request decides.+ upload_id = _query_param(query_params, "uploadId")+ sse = s3_svc.upload_encryption_header(upload_id) if upload_id else headers.get("x-amz-server-side-encryption")+ if sse:+ context["s3:x-amz-server-side-encryption"] = sse+ if not upload_id and headers.get("x-amz-acl"):+ context["s3:x-amz-acl"] = headers["x-amz-acl"]+ else:+ for name, value in s3_svc.object_tags_for_condition(bucket, key, query_params).items():+ context[f"s3:ExistingObjectTag/{name}"] = value+ return context++def dynamodb_service_context(body: bytes) -> dict:"""The DynamoDB condition keys a request carries.diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex a11e58b3..b4316730 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -1064,6 +1064,20 @@ def bucket_policy_for_arn(resource_arn: str) -> tuple[str, str] | None:return _bucket_policies.get_scoped(owner, None, bucket) or "", owner+def object_tags_for_condition(bucket_name: str, key: str, query_params: dict) -> dict:+ """The tags of the object version a read names, for ``s3:ExistingObjectTag`` in the identity check."""+ bucket = _buckets.get(bucket_name)+ if bucket is None:+ return {}+ return _object_tags.get((bucket_name, key, _resolve_subresource_version(query_params, bucket, key)), {})+++def upload_encryption_header(upload_id: str) -> str | None:+ """The ``x-amz-server-side-encryption`` its CreateMultipartUpload carried, for the identity check of a part."""+ upload = _multipart_uploads.get(upload_id)+ return upload.get("requested_sse") if upload else None++def _foreign_bucket_allows(owner_account: str, bucket_name: str, key: str,method: str, query_params: dict, caller: str) -> bool:"""Whether a caller who does not own the bucket may have this request.@@ -7665,6 +7679,7 @@ def _create_multipart_upload(bucket_name: str, key: str, headers: dict):"content_type": content_type,"content_encoding": content_encoding,"preserved_headers": preserved,+ "requested_sse": headers.get("x-amz-server-side-encryption"),"storage_class": storage_class,"checksum_algorithm": checksum_algorithm,"created": now_iso(),diff --git a/tests/test_s3.py b/tests/test_s3.pyindex c56b1d4c..a5b902cd 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -9225,6 +9225,101 @@ def test_s3_read_permission_contract(auth_enabled, iam_user, auth_s3_objects, peassert body.read() == b"auth-contract"+def auth_condition_bucket(s3):+ """A bucket whose policy denies a user an object action under a condition; emptied and removed after."""+ bucket = f"auth-cond-{uuid.uuid4().hex}"+ s3.create_bucket(Bucket=bucket)++ def deny(user_arn, action, condition):+ s3.put_bucket_policy(Bucket=bucket, Policy=json.dumps({"Version": "2012-10-17", "Statement": [{+ "Effect": "Deny", "Principal": {"AWS": user_arn}, "Action": action,+ "Resource": f"arn:aws:s3:::{bucket}/*", "Condition": condition}]}))+ return bucket++ yield deny+ for upload in s3.list_multipart_uploads(Bucket=bucket).get("Uploads", []):+ s3.abort_multipart_upload(Bucket=bucket, Key=upload["Key"], UploadId=upload["UploadId"])+ for item in s3.list_objects_v2(Bucket=bucket).get("Contents", []):+ s3.delete_object(Bucket=bucket, Key=item["Key"])+ s3.delete_bucket(Bucket=bucket)+++_ALLOW_ALL_S3 = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]}+++def _assert_s3_condition(auth_enabled, allowed, call):+ """Under AUTH a refused call answers 403 AccessDenied; anything else succeeds."""+ if auth_enabled and not allowed:+ with pytest.raises(ClientError) as exc:+ call()+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ assert exc.value.response["Error"]["Code"] in ("AccessDenied", "403")+ else:+ assert call()["ResponseMetadata"]["HTTPStatusCode"] in (200, 204)++[email protected]_contract[email protected]("condition", [+ {"StringNotEquals": {"s3:x-amz-server-side-encryption": "AES256"}},+ {"Null": {"s3:x-amz-server-side-encryption": "true"}},+], ids=["string-not-equals", "null"])+def test_s3_encryption_condition_contract(auth_enabled, iam_user, s3, auth_condition_bucket, condition):+ """A bucket policy on s3:x-amz-server-side-encryption sees the header of a PutObject and a CopyObject."""+ user = iam_user(policy=_ALLOW_ALL_S3)+ bucket = auth_condition_bucket(user.arn, "s3:PutObject", condition)+ s3.put_object(Bucket=bucket, Key="source", Body=b"x")+ client = user.client("s3")+ for sse in (None, "AES256"):+ extra = {"ServerSideEncryption": sse} if sse else {}+ _assert_s3_condition(auth_enabled, sse is not None,+ lambda: client.put_object(Bucket=bucket, Key=f"put-{sse}", Body=b"x", **extra))+ _assert_s3_condition(auth_enabled, sse is not None, lambda: client.copy_object(+ Bucket=bucket, Key=f"copy-{sse}", CopySource={"Bucket": bucket, "Key": "source"}, **extra))++[email protected]_contract+def test_s3_multipart_encryption_condition_contract(auth_enabled, iam_user, s3, auth_condition_bucket):+ """A part and the completion carry the encryption header their CreateMultipartUpload sent."""+ user = iam_user(policy=_ALLOW_ALL_S3)+ bucket = auth_condition_bucket(user.arn, "s3:PutObject", {"Null": {"s3:x-amz-server-side-encryption": "true"}})+ client = user.client("s3")+ upload_id = client.create_multipart_upload(Bucket=bucket, Key="sealed", ServerSideEncryption="AES256")["UploadId"]+ etag = client.upload_part(Bucket=bucket, Key="sealed", UploadId=upload_id, PartNumber=1, Body=b"x")["ETag"]+ client.complete_multipart_upload(Bucket=bucket, Key="sealed", UploadId=upload_id,+ MultipartUpload={"Parts": [{"ETag": etag, "PartNumber": 1}]})+ plain = s3.create_multipart_upload(Bucket=bucket, Key="plain")["UploadId"]+ _assert_s3_condition(auth_enabled, False, lambda: client.upload_part(+ Bucket=bucket, Key="plain", UploadId=plain, PartNumber=1, Body=b"x"))++[email protected]_contract+def test_s3_canned_acl_condition_contract(auth_enabled, iam_user, auth_condition_bucket):+ """A bucket policy on s3:x-amz-acl sees the canned ACL of a PutObject."""+ user = iam_user(policy=_ALLOW_ALL_S3)+ bucket = auth_condition_bucket(user.arn, "s3:PutObject",+ {"StringNotEquals": {"s3:x-amz-acl": "bucket-owner-full-control"}})+ client = user.client("s3")+ for acl in (None, "bucket-owner-full-control", "private"):+ extra = {"ACL": acl} if acl else {}+ _assert_s3_condition(auth_enabled, acl == "bucket-owner-full-control",+ lambda: client.put_object(Bucket=bucket, Key=f"acl-{acl}", Body=b"x", **extra))++[email protected]_contract+def test_s3_existing_object_tag_condition_contract(auth_enabled, iam_user, s3, auth_condition_bucket):+ """A bucket policy on s3:ExistingObjectTag sees the tags of the object a GetObject or HeadObject reads."""+ user = iam_user(policy=_ALLOW_ALL_S3)+ bucket = auth_condition_bucket(user.arn, "s3:GetObject", {"StringEquals": {"s3:ExistingObjectTag/class": "secret"}})+ for name, tagging in (("secret", "class=secret"), ("public", "class=public"), ("untagged", "")):+ s3.put_object(Bucket=bucket, Key=name, Body=b"x", **({"Tagging": tagging} if tagging else {}))+ client = user.client("s3")+ _assert_s3_condition(auth_enabled, False, lambda: client.get_object(Bucket=bucket, Key="secret"))+ _assert_s3_condition(auth_enabled, False, lambda: client.head_object(Bucket=bucket, Key="secret"))+ _assert_s3_condition(auth_enabled, True, lambda: client.get_object(Bucket=bucket, Key="public"))+ _assert_s3_condition(auth_enabled, True, lambda: client.get_object(Bucket=bucket, Key="untagged"))++@pytest.mark.auth_contract@pytest.mark.parametrize("addressing_style", ["path", "virtual"])@pytest.mark.parametrize("allow_source_read", [False, True], ids=["no-source-read", "source-read"])