Skip to content

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

fix(s3): treat requests without credentials as anonymous under AUTH=true (#2215)

Gabriel Prando70d31899b484
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e08ed9e..0246da73 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -102,6 +102,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **IAM — `aws:RequestTag/*` and `aws:TagKeys` under `AUTH=true`** — only CloudWatch Logs filled them; a call whose API takes `Tags` or `TagKeys` (create, tag and untag calls such as `CreateQueue`, `CreateTable`, `CreateUser`, `PutParameter`, `CreateSecret`, `CreateKey`) now carries the tags it sets and the keys it names, `aws:TagKeys` is absent on a call that names none, and Lambda `TagResource`, `UntagResource` and `ListTags` are authorized against the ARN in the path instead of skipped. Contributed by @iot-rocket.
- **IAM — caller and transport condition keys under `AUTH=true`** — identity policies saw none of the caller's keys and a fixed `127.0.0.1` over plain HTTP; they now see `aws:username`, `aws:userid`, `aws:PrincipalTag/*` (the user's or role's tags, `AssumeRole` session tags taking precedence; in `rds-db:connect` too), for temporary credentials `aws:MultiFactorAuthPresent` and `aws:TokenIssueTime`, the client's address as `aws:SourceIp` and `aws:SecureTransport` as `true` over HTTPS or behind a proxy that sends `X-Forwarded-Proto: https`, and `AssumedRoleId` starts with the role's `RoleId` with or without `AUTH`. Contributed by @iot-rocket.
- **Cognito Identity — `GetOpenIdToken` claims** — the token was a user-pool ID token with an empty audience; it is now issued by `https://cognito-identity.amazonaws.com` with the identity pool id as `aud`, the identity id as `sub`, an `amr` list naming the login providers and the user-pool sign-in, the pool ARN in `https://cognito-identity.amazonaws.com/identity-pool-arn` and a 10-minute lifetime. An identity id that no pool knows gets `ResourceNotFoundException` instead of a token. Contributed by @iot-rocket.
+- **S3 — requests without credentials are anonymous under `AUTH=true`** — an unsigned request (no `Authorization` header, presigned query or POST form credential) ran as the root key, so a private bucket in the caller's own account answered 200 to anyone; it is now anonymous, and only the owner's public grants let it in: an `AllUsers` ACL grant or a bucket policy that allows `*`, unless Public Access Block shuts them off. Anything else answers 403 `AccessDenied`. A `public-read` object ACL is now also found for an unversioned object, which the grant check missed for cross-account callers too. Without `AUTH` nothing changes.
## [1.5.26] — 2026-10-11
diff --git a/ministack/services/firehose.py b/ministack/services/firehose.py
index 04e69850..b143f1bb 100644
--- a/ministack/services/firehose.py
+++ b/ministack/services/firehose.py
@@ -728,7 +728,7 @@ def _put_s3_object(bucket, key, body):
async def _put():
headers = {"content-type": "application/octet-stream", "content-length": str(len(body)),
"host": "s3.localhost"}
- await s3_svc.handle_request("PUT", f"/{bucket}/{key}", headers, body, {})
+ await s3_svc.handle_request("PUT", f"/{bucket}/{key}", headers, body, {}, internal=True)
try:
asyncio.get_running_loop().create_task(_put())
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 86359bc2..f6844ef2 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -958,10 +958,14 @@ def _foreign_bucket_allows(owner_account: str, bucket_name: str, key: str,
groups = [_ACL_GROUP_ALL_USERS] if not caller else [
_ACL_GROUP_ALL_USERS, _ACL_GROUP_AUTHENTICATED]
- for stored, granted in ((_bucket_acl.get_scoped(owner_account, None, bucket_name), wants),
- (object_acl, object_wants)):
- for uri, permission in _acl_grants(stored):
- if uri in groups and permission in granted:
+ acls = [_bucket_acl.get_scoped(owner_account, None, bucket_name)]
+ record = _buckets.get_scoped(owner_account, None, bucket_name)
+ if key and record is not None:
+ version_id = _resolve_subresource_version(query_params, record, key)
+ acls.append(_object_acl.get_scoped(owner_account, None, (bucket_name, key, version_id)))
+ for stored in acls:
+ for uri, permission in _acl_group_grants(stored):
+ if uri in groups and permission in wants:
return True
policy = _bucket_policies.get_scoped(owner_account, None, bucket_name)
@@ -1111,17 +1115,29 @@ def _check_bucket_region(method: str, bucket: str, key: str, headers: dict, quer
def _apply_bucket_scope(method: str, bucket: str, key: str, headers: dict,
- query_params: dict, body: bytes = b""):
+ query_params: dict, body: bytes = b"", internal: bool = False):
"""Resolve the request's bucket in the global namespace and gate it.
A bucket name identifies one bucket whoever asks, so a request for a name
another account owns is answered by that bucket — if its owner granted the
access. The scope is pinned to the owner for the rest of the request, so
every account-scoped lookup behind this reads the right tenant's state.
+
+ Under AUTH=true a request without credentials is anonymous, as on AWS: only
+ the owner's public grants let it in, whichever account owns the bucket. An
+ ``internal`` call another service makes in process is never anonymous.
"""
if not bucket:
return None
owner = _bucket_owner_account(bucket)
+ if owner is None:
+ return None
+ from ministack.app import AUTH
+ if AUTH and not internal and not _request_access_key(method, key, headers, query_params, body):
+ if not _foreign_bucket_allows(owner, bucket, key, method, query_params, ""):
+ return _error("AccessDenied", "Access Denied", 403, f"/{bucket}/{key}" if key else f"/{bucket}")
+ set_request_account_id(owner)
+ return None
caller = get_account_id()
if owner is None or owner == caller:
return None
@@ -2090,7 +2106,7 @@ async def handle_request(
body: bytes,
query_params: dict,
signed_path: str | None = None,
- enforce_bucket_region: bool = True,
+ internal: bool = False,
) -> tuple:
bucket, key = _parse_bucket_key(path, headers)
@@ -2111,10 +2127,7 @@ async def handle_request(
# reach the handlers exactly as a header-signed request delivers them.
headers = _merge_hoisted_amz_headers(headers, query_params)
- denied = _apply_bucket_scope(method, bucket, key, headers, query_params, body)
- if denied is None and enforce_bucket_region:
- # After the scope is pinned, so the owner's record names the home region.
- denied = _check_bucket_region(method, bucket, key, headers, query_params)
+ denied = _apply_bucket_scope(method, bucket, key, headers, query_params, body, internal)
if denied is not None:
status, resp_headers, resp_body = denied
resp_headers.setdefault("x-amz-request-id", new_uuid())
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 15786817..44e4b08c 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -7638,14 +7638,20 @@ RETENTION = "Access Denied because object protected by object lock retention."
LEGAL_HOLD = "Access Denied because object protected by object lock legal hold."
+_ROOT_AUTHORIZATION = (
+ "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=fake"
+)
+
+
def _lock_call(method, path, headers=None, body=b"", query=None):
import asyncio
from ministack.core.responses import request_scope
from ministack.services import s3 as s3mod
+ headers = {"authorization": _ROOT_AUTHORIZATION, **(headers or {})}
with request_scope("000000000000", "us-east-1"):
- return asyncio.run(s3mod.handle_request(method, path, headers or {}, body, query or {}))
+ return asyncio.run(s3mod.handle_request(method, path, headers, body, query or {}))
def _locked_in_process(**lock_headers):
@@ -8229,6 +8235,96 @@ 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)
# ---------------------------------------------------------------------------