Skip to content

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

fix(s3control): authorize MRAP instance requests by the served route (#2356)

iot-rocket16aea1f170a0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3710e80..e127dc35 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **CloudFront — VPC origins** — `CreateVpcOrigin`, `GetVpcOrigin`, `UpdateVpcOrigin`, `DeleteVpcOrigin` and `ListVpcOrigins` replace the empty `ListVpcOrigins` stub, so Terraform's `aws_cloudfront_vpc_origin` and a distribution's `vpc_origin_config` apply. As on AWS, a create, update or delete answers `Deploying`; MiniStack then finishes it at once, so the next read shows `Deployed` with the next `ETag`, or 404 after a delete. Names are unique per account, endpoints are not, and an origin a distribution names can't be deleted or changed. Validation, its order, the `TLSv1`/`TLSv1.1`/`TLSv1.2` default, `IpAddressType`, the list paging (no `Marker` or `IsTruncated`) and the IAM resources follow AWS captures. The endpoint has to be a load balancer or instance that exists in MiniStack, and viewer requests are not routed to it. Contributed by @kharabasz.
### Fixed
+- **S3 Control — Multi-Region Access Point requests authorize the operation they run** — the action was read from the end of the path, so an MRAP named `policy` was authorized as its policy and a trailing slash after `/policy` or `/routes` was authorized for that operation and served as `GetMultiRegionAccessPoint`; the action now comes from the route the handler serves, a method a resource lacks answers 405 `MethodNotAllowed` with `Method` and `ResourceType`, and a path S3 Control cannot parse 400 `InvalidURI`. Contributed by @iot-rocket.
- **S3 Control — access point requests authorize the operation they run** — access point and Object Lambda Access Point requests were authorized by a second reading of the path, so a POST on a policy returned it, an extra segment or a double slash deleted the Object Lambda Access Point or set its policy without the action, and an access point named `policy` was authorized as its policy; the action now comes from the route the handler serves, a method a resource lacks answers 405 `MethodNotAllowed` with `Method` and `ResourceType`, and a path S3 Control cannot parse 400 `InvalidURI`. Contributed by @iot-rocket.
- **Lambda — the local Node executor's SDK stubs sign their calls** — the `@aws-sdk/client-lambda` stub and the JSON-RPC `@aws-sdk/client-*` stubs sent their requests without credentials, so a call landed in the default account whatever account the function belongs to, and under `AUTH=true` it ran as the account root. They now sign with the function's credentials, as the real SDK does: with `AUTH` unset a call lands in the function's own account, under `AUTH=true` it runs as the execution role. Contributed by @iot-rocket.
- **IoT — `#` does not match the level above it** — a subscription or topic rule with a filter ending in `/#` (`a/c2/#`) also got messages published to the level above (`a/c2`), as the MQTT specification allows; AWS IoT Core delivers only `a/c2/` and deeper, and so does the broker now, for subscriptions and rules. A republish topic at that level is still refused, as on AWS. Contributed by @iot-rocket.
diff --git a/ministack/app.py b/ministack/app.py
index 23ced209..0a76c45e 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -1574,9 +1574,8 @@ def _s3control_mrap_arn(s3, path: str) -> str:
from ministack.core.responses import get_account_id
account = get_account_id()
- ref = unquote(path).rstrip("/").removeprefix("/v20180820/mrap/instances").strip("/")
- ref = ref.removesuffix("/routes").removesuffix("/policy")
- record = s3.find_mrap(ref) if ref and not path.startswith("/v20180820/async-requests/") else None
+ route = None if path.startswith("/v20180820/async-requests/") else s3.mrap_control_route(path)
+ record = s3.find_mrap(route[0]) if route and route[0] else None
return f"arn:aws:s3::{account}:accesspoint/{record['Alias'] if record else '*'}"
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 6e24fab6..989b7856 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -280,29 +280,23 @@ def s3control_action(method: str, path: str) -> str | None:
from ministack.services import s3
- # Access point actions come from the route the handler serves.
+ # Access point and MRAP instance actions come from the route the handler serves.
for in_family, route_of in ((s3.is_object_lambda_control_path, s3.object_lambda_control_route),
(s3.is_access_point_control_path, s3.access_point_control_route)):
if in_family(path):
route = route_of(path)
return route[3].get(method) if route else None
+ instances = "/v20180820/mrap/instances"
+ if unquote(path) == instances or unquote(path).startswith(instances + "/"):
+ route = s3.mrap_control_route(path)
+ return route[3].get(method) if route else None
path = unquote(path).rstrip("/")
async_prefix = "/v20180820/async-requests/mrap/"
- instances = "/v20180820/mrap/instances"
if path.startswith(async_prefix):
tail = path[len(async_prefix):]
if method == "POST":
return _S3CONTROL_MRAP_ASYNC_ACTIONS.get(tail)
return "s3:DescribeMultiRegionAccessPointOperation" if method == "GET" else None
- if path == instances:
- return "s3:ListMultiRegionAccessPoints" if method == "GET" else None
- if path.startswith(instances + "/"):
- if path.endswith("/routes"):
- return {"GET": "s3:GetMultiRegionAccessPointRoutes",
- "PATCH": "s3:SubmitMultiRegionAccessPointRoutes"}.get(method)
- if path.endswith("/policy"):
- return "s3:GetMultiRegionAccessPointPolicy" if method == "GET" else None
- return "s3:GetMultiRegionAccessPoint" if method == "GET" else None
return None
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 133f54ac..280a0020 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -9459,6 +9459,37 @@ def _mrap_submit_routes(record: dict, body: bytes) -> tuple:
return 200, {"Content-Type": "application/xml"}, b""
+# Each Multi-Region Access Point instance resource, by the segment after the
+# reference (None for the collection): its ResourceType and the IAM action per
+# method. A documented resource MiniStack does not emulate has no ResourceType.
+_MRAP_RESOURCES = {
+ None: ("MULTI_REGION_ACCESS_POINTS", {"GET": "s3:ListMultiRegionAccessPoints"}),
+ "": ("MULTI_REGION_ACCESS_POINT", {"GET": "s3:GetMultiRegionAccessPoint"}),
+ "policy": ("GET_MULTI_REGION_ACCESS_POINT_POLICY", {"GET": "s3:GetMultiRegionAccessPointPolicy"}),
+ "policystatus": (None, {"GET": "s3:GetMultiRegionAccessPointPolicyStatus"}),
+ "routes": ("MULTI_REGION_ACCESS_POINT_ROUTES", {"GET": "s3:GetMultiRegionAccessPointRoutes",
+ "PATCH": "s3:SubmitMultiRegionAccessPointRoutes"}),
+}
+
+
+def mrap_control_route(path: str) -> tuple | None:
+ """``(reference, sub-resource, resource type, IAM actions by method)`` of an MRAP instances path, or None."""
+ rest = url_unquote(path)[len(_MRAP_INSTANCES_PREFIX):]
+ if not rest:
+ ref, sub = "", None
+ elif not rest.startswith("/") or not all(segments := rest[1:].split("/")):
+ return None
+ elif len(segments) > 1 and segments[-1] == "routes": # routes take the MRAP's ARN, which holds a slash
+ ref, sub = "/".join(segments[:-1]), "routes"
+ elif len(segments) == 1:
+ ref, sub = segments[0], ""
+ elif len(segments) == 2 and segments[1] in ("policy", "policystatus"):
+ ref, sub = segments
+ else:
+ return None
+ return ref, sub, *_MRAP_RESOURCES[sub]
+
+
def handle_mrap_control(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:
"""S3 Control's Multi-Region Access Point operations (``/v20180820/mrap/``
and ``/v20180820/async-requests/mrap/``). Management is served from
@@ -9466,7 +9497,9 @@ def handle_mrap_control(method: str, path: str, headers: dict, body: bytes, quer
without a signing region is let through, as S3's own region check does."""
signed = _signed_region(headers, query_params)
decoded = url_unquote(path)
- is_routes = decoded.startswith(_MRAP_INSTANCES_PREFIX + "/") and decoded.endswith("/routes")
+ is_instances = decoded == _MRAP_INSTANCES_PREFIX or decoded.startswith(_MRAP_INSTANCES_PREFIX + "/")
+ route = mrap_control_route(path) if is_instances else None
+ is_routes = route is not None and route[1] == "routes"
if signed is not None:
if is_routes and signed not in _MRAP_ROUTE_REGIONS:
return _mrap_region_error(path, routes=True)
@@ -9479,12 +9512,13 @@ def handle_mrap_control(method: str, path: str, headers: dict, body: bytes, quer
return _mrap_async(tail, body, signed)
if method == "GET":
return _mrap_describe(tail)
- elif decoded.rstrip("/") == _MRAP_INSTANCES_PREFIX and method == "GET":
- return _mrap_list(query_params)
- elif decoded.startswith(_MRAP_INSTANCES_PREFIX + "/"):
- ref = decoded[len(_MRAP_INSTANCES_PREFIX) + 1:]
- if is_routes:
- ref = ref[: -len("/routes")]
+ elif is_instances:
+ if route is None or method not in route[3]:
+ return _control_route_error(method, path, route)
+ ref, sub = route[0], route[1]
+ if sub is None:
+ return _mrap_list(query_params)
+ if sub == "routes":
if not ref.startswith("arn:"):
return s3control_error("InvalidRequest", "Request invalid", 400)
record = find_mrap(ref)
@@ -9492,18 +9526,17 @@ def handle_mrap_control(method: str, path: str, headers: dict, body: bytes, quer
return _no_such_mrap(ref.rsplit("/", 1)[-1])
if method == "GET":
return _mrap_get_routes(ref, record)
- if method == "PATCH":
- return _mrap_submit_routes(record, body)
- elif ref.endswith("/policy") and method == "GET":
- record = find_mrap(ref[: -len("/policy")])
- return _mrap_policy(record) if record else _no_such_mrap(ref[: -len("/policy")])
- elif method == "GET":
- record = find_mrap(ref)
- if record is None:
- return _no_such_mrap(ref)
- out = Element("GetMultiRegionAccessPointResult", xmlns=S3CONTROL_NS)
- _mrap_report_xml(out, record)
- return _s3control_response(out)
+ return _mrap_submit_routes(record, body)
+ if route[2] is None:
+ return _no_such_mrap(f"{ref}/{sub}")
+ record = find_mrap(ref)
+ if record is None:
+ return _no_such_mrap(ref)
+ if sub == "policy":
+ return _mrap_policy(record)
+ out = Element("GetMultiRegionAccessPointResult", xmlns=S3CONTROL_NS)
+ _mrap_report_xml(out, record)
+ return _s3control_response(out)
return s3control_error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405)
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 24d0b9f6..64901ed2 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -6097,6 +6097,16 @@ def test_stage_policy_is_enforced_on_dispatch(monkeypatch, prefix, suffix, case,
"s3:GetMultiRegionAccessPointRoutes"),
("PATCH", "/v20180820/mrap/instances/arn%3Aaws%3As3%3A%3A000000000000%3Aaccesspoint/a.mrap/routes",
"s3:SubmitMultiRegionAccessPointRoutes"),
+ ("GET", "/v20180820/mrap/instances/policy", "s3:GetMultiRegionAccessPoint"),
+ ("GET", "/v20180820/mrap/instances/routes", "s3:GetMultiRegionAccessPoint"),
+ ("GET", "/v20180820/mrap/instances/m1/policystatus", "s3:GetMultiRegionAccessPointPolicyStatus"),
+ ("GET", "/v20180820/mrap/instances/", None),
+ ("GET", "/v20180820/mrap/instances/m1/", None),
+ ("GET", "/v20180820/mrap/instances/m1/policy/", None),
+ ("GET", "/v20180820/mrap/instances/m1/x", None),
+ ("POST", "/v20180820/mrap/instances/m1/policy", None),
+ ("GET", "/v20180820/mrap/instances/arn%3Aaws%3As3%3A%3A000000000000%3Aaccesspoint/a.mrap", None),
+ ("GET", "/v20180820/mrap/instances/arn%3Aaws%3As3%3A%3A000000000000%3Aaccesspoint/a.mrap/routes/", None),
])
def test_s3control_mrap_iam_action(method, path, action):
from ministack.core.iam_actions import s3control_action
diff --git a/tests/test_s3.py b/tests/test_s3.py
index e80fac4a..0e32a17d 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -9806,6 +9806,77 @@ def test_s3_mrap_control_read_get_list_policy(s3control_dns, mrap_members):
assert (err["MultiRegionAccessPointName"], err["AccountId"]) == (names[0], _ACCOUNT)
+def _mrap_control_raw(method, path, key=("test", "test")):
+ """A SigV4-signed S3 Control request for us-west-2, the path sent as given: status and body."""
+ import http.client
+
+ from botocore.auth import S3SigV4Auth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ req = AWSRequest(method=method, url=f"{ENDPOINT}{path}", headers={"x-amz-account-id": _ACCOUNT})
+ req.headers["x-amz-content-sha256"] = hashlib.sha256(b"").hexdigest()
+ S3SigV4Auth(Credentials(*key), "s3", "us-west-2").add_auth(req)
+ parsed = urlparse(ENDPOINT)
+ conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)
+ conn.request(method, path, headers=dict(req.headers.items()))
+ resp = conn.getresponse()
+ data = resp.read()
+ conn.close()
+ return resp.status, data
+
+
+_MRAP_ARN_PATH = f"arn%3Aaws%3As3%3A%3A{_ACCOUNT}%3Aaccesspoint/nope.mrap"
+
+
[email protected]("method,path,status,fields", [
+ ("POST", "", 405, {"Method": "POST", "ResourceType": "MULTI_REGION_ACCESS_POINTS"}),
+ ("DELETE", "/m1", 405, {"Method": "DELETE", "ResourceType": "MULTI_REGION_ACCESS_POINT"}),
+ ("POST", "/m1/policy", 405, {"Method": "POST", "ResourceType": "GET_MULTI_REGION_ACCESS_POINT_POLICY"}),
+ ("POST", f"/{_MRAP_ARN_PATH}/routes", 405, {"Method": "POST", "ResourceType": "MULTI_REGION_ACCESS_POINT_ROUTES"}),
+ ("GET", "/", 400, {"URI": "mrap/instances/"}),
+ ("GET", "/m1/", 400, {}),
+ ("GET", "//m1", 400, {}),
+ ("GET", "/m1/policy/", 400, {}),
+ ("GET", "/m1/x", 400, {"URI": "mrap/instances/m1/x"}),
+ ("GET", "/m1/policy/x", 400, {}),
+ ("GET", f"/{_MRAP_ARN_PATH}", 400, {}),
+ ("GET", f"/{_MRAP_ARN_PATH}/routes/", 400, {}),
+ ("GET", "/routes", 404, {"MultiRegionAccessPointName": "routes"}),
+ ("GET", "/m1/policystatus", 404, {}),
+])
+def test_s3_mrap_control_unserved_requests(method, path, status, fields):
+ """Unserved methods answer 405, unparsed paths 400 InvalidURI; "routes" alone names an MRAP."""
+ got, data = _mrap_control_raw(method, "/v20180820/mrap/instances" + path)
+ code = {405: "MethodNotAllowed", 400: "InvalidURI", 404: "NoSuchMultiRegionAccessPoint"}[status]
+ assert (got, re.search(rb"<Code>(\w+)</Code>", data).group(1).decode()) == (status, code)
+ for tag, value in fields.items():
+ assert f"<{tag}>{value}</{tag}>".encode() in data
+
+
+def test_s3_mrap_named_policy_needs_the_get_action(auth_enabled, iam_user, s3control_dns, mrap_members):
+ """/v20180820/mrap/instances/policy names an MRAP called "policy"."""
+ _, use1_bucket, _, euw1_bucket = mrap_members
+ ctl = _regional_client("s3control", "us-west-2")
+ assert _mrap_create(ctl, "policy", [use1_bucket, euw1_bucket])["RequestStatus"] == "SUCCEEDED"
+ try:
+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Action": "s3:GetMultiRegionAccessPointPolicy", "Resource": "*"}]}).client(
+ "s3control", region="us-west-2")
+ assert "Policy" in user.get_multi_region_access_point_policy(AccountId=_ACCOUNT, Name="policy")
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ user.get_multi_region_access_point(AccountId=_ACCOUNT, Name="policy")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
+ assert exc.value.response["Error"]["Code"] == "AccessDenied"
+ else:
+ assert user.get_multi_region_access_point(AccountId=_ACCOUNT, Name="policy")["AccessPoint"]["Name"] == (
+ "policy")
+ finally:
+ _mrap_delete(ctl, "policy")
+
+
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")