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(s3control): authorize access point requests by the served route (#2355)
iot-rocket425414102368
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 625dd288..d3710e80 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 — 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.- **EventBridge — archive KMS keys** — `CreateArchive` and `UpdateArchive` dropped `KmsKeyIdentifier`, so `DescribeArchive` never returned it and Terraform re-planned `kms_key_identifier` on every run; the key is now stored and returned, an update that omits it keeps it, and an empty identifier on update clears it; `ListArchives` entries carry only the `Archive` summary fields. Contributed by @kharabasz.diff --git a/ministack/app.py b/ministack/app.pyindex ced48131..23ced209 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1583,14 +1583,12 @@ def _s3control_mrap_arn(s3, path: str) -> str:def _s3control_access_point_arn(s3, path: str) -> str:"""IAM resource for an access point request: its regional ARN, or theaccount's wildcard for ListAccessPoints."""- name = unquote(path).rstrip("/").removeprefix("/v20180820/accesspoint").strip("/").removesuffix("/policy")- return s3.access_point_arn(name or "*")+ return s3.access_point_arn(s3.access_point_control_route(path)[0] or "*")def _s3control_object_lambda_arn(s3, path: str) -> str:"""IAM resource for an Object Lambda Access Point request."""- name = unquote(path).rstrip("/").removeprefix("/v20180820/accesspointforobjectlambda").strip("/")- return s3.object_lambda_arn(name.split("/", 1)[0] or "*")+ return s3.object_lambda_arn(s3.object_lambda_control_route(path)[0] or "*")async def _handle_s3_control_request(path: str, method: str, body: bytes, query_params: dict, request_id: str,diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex b70297ad..6e24fab6 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -274,44 +274,19 @@ _S3CONTROL_MRAP_ASYNC_ACTIONS = {}-_S3CONTROL_ACCESS_POINT_ACTIONS = {- ("PUT", False): "s3:CreateAccessPoint",- ("GET", False): "s3:GetAccessPoint",- ("DELETE", False): "s3:DeleteAccessPoint",- ("PUT", True): "s3:PutAccessPointPolicy",- ("GET", True): "s3:GetAccessPointPolicy",- ("DELETE", True): "s3:DeleteAccessPointPolicy",-}---_S3CONTROL_OBJECT_LAMBDA_ACTIONS = {- ("PUT", ""): "s3:CreateAccessPointForObjectLambda",- ("GET", ""): "s3:GetAccessPointForObjectLambda",- ("DELETE", ""): "s3:DeleteAccessPointForObjectLambda",- ("PUT", "configuration"): "s3:PutAccessPointConfigurationForObjectLambda",- ("GET", "configuration"): "s3:GetAccessPointConfigurationForObjectLambda",- ("PUT", "policy"): "s3:PutAccessPointPolicyForObjectLambda",- ("GET", "policy"): "s3:GetAccessPointPolicyForObjectLambda",- ("DELETE", "policy"): "s3:DeleteAccessPointPolicyForObjectLambda",-}--def s3control_action(method: str, path: str) -> str | None:"""IAM action for an S3 Control Multi-Region Access Point or access point request, or None."""from urllib.parse import unquote+ from ministack.services import s3++ # Access point 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 Nonepath = unquote(path).rstrip("/")- object_lambda = "/v20180820/accesspointforobjectlambda"- if path == object_lambda:- return "s3:ListAccessPointsForObjectLambda" if method == "GET" else None- if path.startswith(object_lambda + "/"):- sub = path[len(object_lambda) + 1:].partition("/")[2]- return _S3CONTROL_OBJECT_LAMBDA_ACTIONS.get((method, sub))- access_points = "/v20180820/accesspoint"- if path == access_points:- return "s3:ListAccessPoints" if method == "GET" else None- if path.startswith(access_points + "/"):- return _S3CONTROL_ACCESS_POINT_ACTIONS.get((method, path.endswith("/policy")))async_prefix = "/v20180820/async-requests/mrap/"instances = "/v20180820/mrap/instances"if path.startswith(async_prefix):diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 1ab890c5..133f54ac 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -9658,30 +9658,74 @@ def is_access_point_control_path(path: str) -> bool:return path.rstrip("/") == _ACCESS_POINT_PREFIX or path.startswith(_ACCESS_POINT_PREFIX + "/")+# Each resource under an S3 Control prefix, by the segment after the name (None+# for the collection): its ResourceType and the IAM action per method. A+# documented resource MiniStack does not emulate has no ResourceType.+_ACCESS_POINT_RESOURCES = {+ None: ("ACCESSPOINTS", {"GET": "s3:ListAccessPoints"}),+ "": ("ACCESSPOINT", {"PUT": "s3:CreateAccessPoint", "GET": "s3:GetAccessPoint", "DELETE": "s3:DeleteAccessPoint"}),+ "policy": ("ACCESSPOINTPOLICY", {"PUT": "s3:PutAccessPointPolicy", "GET": "s3:GetAccessPointPolicy",+ "DELETE": "s3:DeleteAccessPointPolicy"}),+ "policyStatus": (None, {"GET": "s3:GetAccessPointPolicyStatus"}),+ "scope": (None, {"PUT": "s3express:PutAccessPointScope", "GET": "s3express:GetAccessPointScope",+ "DELETE": "s3express:DeleteAccessPointScope"}),+}+++def _control_route(path: str, prefix: str, resources: dict) -> tuple | None:+ """``(name, sub-resource, resource type, IAM actions by method)`` of a path under ``prefix``, or None."""+ parts = url_unquote(path)[len(prefix):].split("/")+ if parts == [""]:+ name, sub = "", None+ elif len(parts) in (2, 3) and not parts[0] and all(parts[1:]):+ name, sub = parts[1], parts[2] if len(parts) == 3 else ""+ else:+ return None+ if sub not in resources:+ return None+ return name, sub, *resources[sub]+++def access_point_control_route(path: str) -> tuple | None:+ """The route of an access point control request, as ``_control_route``."""+ return _control_route(path, _ACCESS_POINT_PREFIX, _ACCESS_POINT_RESOURCES)+++def _control_route_error(method: str, path: str, route: tuple | None) -> tuple:+ if route is None:+ return s3control_error("InvalidURI", "Couldn't parse the specified URI.", 400,+ {"URI": path.split("/v20180820/", 1)[-1]})+ extra = {"Method": method, "ResourceType": route[2]} if route[2] else {"Method": method}+ return s3control_error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405,+ extra)++def handle_access_point_control(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:"""S3 Control access point operations in the request's region."""- tail = url_unquote(path).rstrip("/")[len(_ACCESS_POINT_PREFIX):].strip("/")- if not tail:- if method == "GET":- return _access_point_list(query_params)- elif tail.endswith("/policy"):- return _access_point_policy(tail[: -len("/policy")], method, body)- elif method == "PUT":- return _access_point_create_request(tail, body)- elif method == "GET":- record = _access_points.get(tail)+ route = access_point_control_route(path)+ if route is None or method not in route[3]:+ return _control_route_error(method, path, route)+ name, sub = route[0], route[1]+ if route[2] is None:+ return _no_such_access_point(f"{name}/{sub}").response()+ if sub is None:+ return _access_point_list(query_params)+ if sub == "policy":+ return _access_point_policy(name, method, body)+ if method == "PUT":+ return _access_point_create_request(name, body)+ if method == "GET":+ record = _access_points.get(name)if record is None:- return _no_such_access_point(tail).response()+ return _no_such_access_point(name).response()out = Element("GetAccessPointResult", xmlns=S3CONTROL_NS)_access_point_xml(out, record, full=True)return _s3control_response(out)- elif method == "DELETE":- try:- delete_access_point(tail)- except AccessPointError as exc:- return exc.response()- return 204, {}, b""- return s3control_error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405)+ try:+ delete_access_point(name)+ except AccessPointError as exc:+ return exc.response()+ return 204, {}, b""# ---------------------------------------------------------------------------@@ -9808,6 +9852,26 @@ def is_object_lambda_control_path(path: str) -> bool:return path.rstrip("/") == _OBJECT_LAMBDA_PREFIX or path.startswith(_OBJECT_LAMBDA_PREFIX + "/")+_OBJECT_LAMBDA_RESOURCES = {+ None: ("OBJECT_LAMBDA_ACCESS_POINTS", {"GET": "s3:ListAccessPointsForObjectLambda"}),+ "": ("OBJECT_LAMBDA_ACCESS_POINT", {"PUT": "s3:CreateAccessPointForObjectLambda",+ "GET": "s3:GetAccessPointForObjectLambda",+ "DELETE": "s3:DeleteAccessPointForObjectLambda"}),+ "configuration": ("OBJECT_LAMBDA_ACCESS_POINT_CONFIGURATION", {+ "PUT": "s3:PutAccessPointConfigurationForObjectLambda",+ "GET": "s3:GetAccessPointConfigurationForObjectLambda"}),+ "policy": ("OBJECT_LAMBDA_ACCESS_POINT_POLICY", {"PUT": "s3:PutAccessPointPolicyForObjectLambda",+ "GET": "s3:GetAccessPointPolicyForObjectLambda",+ "DELETE": "s3:DeleteAccessPointPolicyForObjectLambda"}),+ "policyStatus": (None, {"GET": "s3:GetAccessPointPolicyStatusForObjectLambda"}),+}+++def object_lambda_control_route(path: str) -> tuple | None:+ """The route of an Object Lambda Access Point control request, as ``_control_route``."""+ return _control_route(path, _OBJECT_LAMBDA_PREFIX, _OBJECT_LAMBDA_RESOURCES)++def _object_lambda_request(name: str, method: str, body: bytes, sub: str) -> tuple:record = _object_lambda_access_points.get(name)if method == "PUT" and not sub:@@ -9865,11 +9929,13 @@ def _object_lambda_request(name: str, method: str, body: bytes, sub: str) -> tupdef handle_object_lambda_control(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:"""S3 Control Object Lambda Access Point operations in the request's region."""- tail = url_unquote(path).rstrip("/")[len(_OBJECT_LAMBDA_PREFIX):].strip("/")- if not tail:- if method != "GET":- return s3control_error("MethodNotAllowed", "The specified method is not allowed against this resource.",- 405)+ route = object_lambda_control_route(path)+ if route is None or method not in route[3]:+ return _control_route_error(method, path, route)+ name, sub = route[0], route[1]+ if route[2] is None:+ return _no_such_object_lambda(f"{name}/{sub}").response()+ if sub is None:records = sorted(_object_lambda_access_points.values(), key=lambda r: r["Name"])start = int(_qp(query_params, "nextToken", "0") or "0")max_results = int(_qp(query_params, "maxResults", "1000") or "1000")@@ -9883,7 +9949,6 @@ def handle_object_lambda_control(method: str, path: str, headers: dict, body: byif start + max_results < len(records):SubElement(out, "NextToken").text = str(start + max_results)return _s3control_response(out)- name, _, sub = tail.partition("/")return _object_lambda_request(name, method, body, sub)diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex 7a23a399..24d0b9f6 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -6186,6 +6186,16 @@ def test_s3_list_grants_scoped_by_prefix_condition(monkeypatch, addressing):("PUT", "/v20180820/accesspoint/ap1/policy", "s3:PutAccessPointPolicy"),("GET", "/v20180820/accesspoint/ap1/policy", "s3:GetAccessPointPolicy"),("DELETE", "/v20180820/accesspoint/ap1/policy", "s3:DeleteAccessPointPolicy"),+ ("GET", "/v20180820/accesspoint/policy", "s3:GetAccessPoint"),+ ("DELETE", "/v20180820/accesspoint/policy", "s3:DeleteAccessPoint"),+ ("POST", "/v20180820/accesspoint/ap1/policy", None),+ ("POST", "/v20180820/accesspoint", None),+ ("DELETE", "/v20180820/accesspoint/ap1/x", None),+ ("DELETE", "/v20180820/accesspoint/ap1/policy/x", None),+ ("PUT", "/v20180820/accesspoint//ap1/policy", None),+ ("GET", "/v20180820/accesspoint/ap1/", None),+ ("GET", "/v20180820/accesspoint/ap1/policyStatus", "s3:GetAccessPointPolicyStatus"),+ ("PUT", "/v20180820/accesspoint/ap1/scope", "s3express:PutAccessPointScope"),])def test_s3control_access_point_iam_action(method, path, action):from ministack.core.iam_actions import s3control_action@@ -6220,6 +6230,13 @@ def test_s3control_access_point_denied_without_the_action(monkeypatch):("PUT", "/v20180820/accesspointforobjectlambda/ol/policy", "s3:PutAccessPointPolicyForObjectLambda"),("GET", "/v20180820/accesspointforobjectlambda/ol/policy", "s3:GetAccessPointPolicyForObjectLambda"),("DELETE", "/v20180820/accesspointforobjectlambda/ol/policy", "s3:DeleteAccessPointPolicyForObjectLambda"),+ ("GET", "/v20180820/accesspointforobjectlambda/policy", "s3:GetAccessPointForObjectLambda"),+ ("POST", "/v20180820/accesspointforobjectlambda/ol/policy", None),+ ("DELETE", "/v20180820/accesspointforobjectlambda/ol/configuration", None),+ ("DELETE", "/v20180820/accesspointforobjectlambda/ol/x", None),+ ("PUT", "/v20180820/accesspointforobjectlambda//ol/policy", None),+ ("GET", "/v20180820/accesspointforobjectlambda/", None),+ ("GET", "/v20180820/accesspointforobjectlambda/ol/policyStatus", "s3:GetAccessPointPolicyStatusForObjectLambda"),])def test_s3control_object_lambda_iam_action(method, path, action):from ministack.core.iam_actions import s3control_actiondiff --git a/tests/test_s3_access_points.py b/tests/test_s3_access_points.pyindex 440b3a1b..15659126 100644--- a/tests/test_s3_access_points.py+++ b/tests/test_s3_access_points.py@@ -9,7 +9,7 @@ import boto3import pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError-from conftest import patch_endpoint_dns+from conftest import make_client, patch_endpoint_dnsENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")ACCOUNT = "000000000000"@@ -158,9 +158,90 @@ def test_access_point_control_policy_round_trip(access_point):assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404[email protected]("method,path,status,fields", [+ ("POST", "/{ap}/policy", 405, {"Method": "POST", "ResourceType": "ACCESSPOINTPOLICY"}),+ ("PATCH", "/{ap}/policy", 405, {"Method": "PATCH", "ResourceType": "ACCESSPOINTPOLICY"}),+ ("POST", "/{ap}", 405, {"Method": "POST", "ResourceType": "ACCESSPOINT"}),+ ("POST", "", 405, {"Method": "POST", "ResourceType": "ACCESSPOINTS"}),+ ("GET", "/{ap}/x", 400, {"URI": "accesspoint/{ap}/x"}),+ ("DELETE", "/{ap}/x", 400, {}),+ ("DELETE", "/{ap}/policy/x", 400, {}),+ ("GET", "/{ap}/", 400, {}),+ ("GET", "//{ap}", 400, {}),+ ("PUT", "//{ap}/policy", 400, {}),+ ("GET", "/", 400, {}), ("GET", "/{ap}/policyStatus", 404, {"AccessPointName": "{ap}/policyStatus"}),+ ("GET", "/{ap}/scope", 404, {}),+])+def test_access_point_control_unserved_requests(access_point, method, path, status, fields):+ """Unserved methods answer 405, unparsed paths 400, unemulated routes 404; none changes the access point."""+ name, _ = access_point+ ctl = _client("s3control", "us-east-1")+ policy = json.dumps({"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, "Action": "s3:GetObject",+ "Resource": f"arn:aws:s3:us-east-1:{ACCOUNT}:accesspoint/{name}/object/*"}]})+ ctl.put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=policy)+ body = b"<PutAccessPointPolicyRequest><Policy>{}</Policy></PutAccessPointPolicyRequest>"+ got, _, data = _raw(method, ENDPOINT.split("://", 1)[1], "/v20180820/accesspoint" + path.format(ap=name),+ "us-east-1", body if method == "PUT" else b"", headers={"x-amz-account-id": ACCOUNT})+ code = {405: "MethodNotAllowed", 400: "InvalidURI", 404: "NoSuchAccessPoint"}[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.format(ap=name)}</{tag}>".encode() in data+ assert ctl.get_access_point_policy(AccountId=ACCOUNT, Name=name)["Policy"] == policy++[email protected]_contract+def test_access_point_named_policy_needs_the_access_point_action(auth_enabled, iam_user, bucket):+ """/v20180820/accesspoint/policy names an access point called "policy"."""+ ctl = _client("s3control", "us-east-1")+ ctl.create_access_point(AccountId=ACCOUNT, Name="policy", Bucket=bucket)+ try:+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Action": ["s3:GetAccessPointPolicy", "s3:DeleteAccessPointPolicy"],+ "Resource": "*"}]}).client("s3control", region="us-east-1")+ user.delete_access_point_policy(AccountId=ACCOUNT, Name="policy")+ if auth_enabled:+ for call in (user.get_access_point, user.delete_access_point):+ with pytest.raises(ClientError) as exc:+ call(AccountId=ACCOUNT, Name="policy")+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ assert exc.value.response["Error"]["Code"] == "AccessDenied"+ assert ctl.get_access_point(AccountId=ACCOUNT, Name="policy")["Bucket"] == bucket+ else:+ assert user.get_access_point(AccountId=ACCOUNT, Name="policy")["Bucket"] == bucket+ user.delete_access_point(AccountId=ACCOUNT, Name="policy")+ finally:+ try:+ ctl.delete_access_point(AccountId=ACCOUNT, Name="policy")+ except ClientError:+ pass++[email protected]_contract+def test_access_point_policy_unserved_method_is_refused_before_authorization(auth_enabled, iam_user, access_point):+ """POST on an access point policy answers 405 to any caller and returns no policy."""+ name, _ = access_point+ _client("s3control", "us-east-1").put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=json.dumps({+ "Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, "Action": "s3:GetObject",+ "Resource": f"arn:aws:s3:us-east-1:{ACCOUNT}:accesspoint/{name}/object/*"}]}))+ user = iam_user()+ iam = make_client("iam")+ key = iam.create_access_key(UserName=user.name)["AccessKey"]+ try:+ signed = {"key": (key["AccessKeyId"], key["SecretAccessKey"]), "headers": {"x-amz-account-id": ACCOUNT}}+ host, path = ENDPOINT.split("://", 1)[1], f"/v20180820/accesspoint/{name}/policy"+ status, _, data = _raw("POST", host, path, "us-east-1", **signed)+ assert status == 405 and b"<ResourceType>ACCESSPOINTPOLICY</ResourceType>" in data+ assert b"<Policy>" not in data+ assert _raw("GET", host, path, "us-east-1", **signed)[0] == (403 if auth_enabled else 200)+ finally:+ iam.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])++# --- Data plane ---------------------------------------------------------------def _raw(method, host, path, region, body=b""):+def _raw(method, host, path, region, body=b"", key=("test", "test"), headers=None):"""A SigV4-signed request with an explicit Host, no redirect handling."""import hashlibimport http.client@@ -170,9 +251,9 @@ def _raw(method, host, path, region, body=b""):from botocore.awsrequest import AWSRequestfrom botocore.credentials import Credentials- req = AWSRequest(method=method, url=f"http://{host}{path}", data=body)+ req = AWSRequest(method=method, url=f"http://{host}{path}", data=body, headers=headers)req.headers["x-amz-content-sha256"] = hashlib.sha256(body).hexdigest()- S3SigV4Auth(Credentials("test", "test"), "s3", region).add_auth(req)+ S3SigV4Auth(Credentials(*key), "s3", region).add_auth(req)parsed = urlparse(ENDPOINT)conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)conn.request(method, path, body=body or None, headers={**dict(req.headers.items()), "Host": host})diff --git a/tests/test_s3_object_lambda.py b/tests/test_s3_object_lambda.pyindex f4faa8ae..fc7d88ba 100644--- a/tests/test_s3_object_lambda.py+++ b/tests/test_s3_object_lambda.py@@ -16,7 +16,7 @@ import boto3import pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError-from conftest import patch_endpoint_dns+from conftest import make_client, patch_endpoint_dnsENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")ACCOUNT = "000000000000"@@ -190,6 +190,102 @@ def test_object_lambda_control_validation(supporting_access_point, upper_functioassert exc.value.response["Error"]["Code"] == "InvalidRequest"+def control_olap(supporting_access_point):+ """An Object Lambda Access Point with a policy, for control-plane requests only."""+ _, supporting_arn = supporting_access_point+ ctl = _client("s3control")+ name = f"olap-{_uid()}"+ function_arn = f"arn:aws:lambda:us-east-1:{ACCOUNT}:function:olap-unused"+ arn = ctl.create_access_point_for_object_lambda(+ AccountId=ACCOUNT, Name=name, Configuration=_configuration(supporting_arn, function_arn),+ )["ObjectLambdaAccessPointArn"]+ policy = json.dumps({"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"},+ "Action": "s3-object-lambda:GetObject", "Resource": arn}]})+ ctl.put_access_point_policy_for_object_lambda(AccountId=ACCOUNT, Name=name, Policy=policy)+ yield name, policy+ try:+ ctl.delete_access_point_for_object_lambda(AccountId=ACCOUNT, Name=name)+ except ClientError:+ pass+++_OLAP_POLICY_BODY = (b"<PutAccessPointPolicyForObjectLambdaRequest><Policy>{}</Policy>"+ b"</PutAccessPointPolicyForObjectLambdaRequest>")+++def _control_raw(method, path, body=b"", key=("test", "test")):+ """A SigV4-signed S3 Control request, the path sent as given: status and body."""+ import hashlib+ import http.client+ from urllib.parse import urlparse++ from botocore.auth import S3SigV4Auth+ from botocore.awsrequest import AWSRequest+ from botocore.credentials import Credentials++ req = AWSRequest(method=method, url=f"{ENDPOINT}{path}", data=body, headers={"x-amz-account-id": ACCOUNT})+ req.headers["x-amz-content-sha256"] = hashlib.sha256(body).hexdigest()+ S3SigV4Auth(Credentials(*key), "s3", "us-east-1").add_auth(req)+ parsed = urlparse(ENDPOINT)+ conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)+ conn.request(method, path, body=body or None, headers=dict(req.headers.items()))+ resp = conn.getresponse()+ data = resp.read()+ conn.close()+ return resp.status, data++[email protected]("method,path,status,fields", [+ ("POST", "/{ol}/policy", 405, {"Method": "POST", "ResourceType": "OBJECT_LAMBDA_ACCESS_POINT_POLICY"}),+ ("POST", "/{ol}", 405, {"Method": "POST", "ResourceType": "OBJECT_LAMBDA_ACCESS_POINT"}),+ ("POST", "/{ol}/configuration", 405,+ {"Method": "POST", "ResourceType": "OBJECT_LAMBDA_ACCESS_POINT_CONFIGURATION"}),+ ("DELETE", "/{ol}/configuration", 405,+ {"Method": "DELETE", "ResourceType": "OBJECT_LAMBDA_ACCESS_POINT_CONFIGURATION"}),+ ("POST", "", 405, {"Method": "POST", "ResourceType": "OBJECT_LAMBDA_ACCESS_POINTS"}),+ ("DELETE", "/{ol}/x", 400, {"URI": "accesspointforobjectlambda/{ol}/x"}),+ ("GET", "/{ol}/x", 400, {}),+ ("PUT", "//{ol}/policy", 400, {}),+ ("GET", "//{ol}/policy", 400, {}),+ ("GET", "/", 400, {}), ("GET", "/{ol}/policyStatus", 404, {"AccessPointName": "{ol}/policyStatus"}),+])+def test_object_lambda_control_unserved_requests(control_olap, method, path, status, fields):+ """Unserved methods answer 405, unparsed paths 400, unemulated routes 404; none changes the access point."""+ name, policy = control_olap+ got, data = _control_raw(method, "/v20180820/accesspointforobjectlambda" + path.format(ol=name),+ _OLAP_POLICY_BODY if method == "PUT" else b"")+ code = {405: "MethodNotAllowed", 400: "InvalidURI", 404: "NoSuchAccessPoint"}[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.format(ol=name)}</{tag}>".encode() in data+ ctl = _client("s3control")+ assert ctl.get_access_point_policy_for_object_lambda(AccountId=ACCOUNT, Name=name)["Policy"] == policy+ assert ctl.get_access_point_configuration_for_object_lambda(AccountId=ACCOUNT, Name=name)["Configuration"]++[email protected]_contract+def test_object_lambda_control_unparsed_paths_change_nothing(auth_enabled, iam_user, control_olap):+ """An extra segment or a double slash neither deletes the access point nor sets its policy."""+ name, policy = control_olap+ user = iam_user()+ iam = make_client("iam")+ key = iam.create_access_key(UserName=user.name)["AccessKey"]+ creds = (key["AccessKeyId"], key["SecretAccessKey"])+ prefix = "/v20180820/accesspointforobjectlambda"+ try:+ assert _control_raw("DELETE", f"{prefix}/{name}/x", key=creds)[0] == 400+ assert _control_raw("PUT", f"{prefix}//{name}/policy", _OLAP_POLICY_BODY, key=creds)[0] == 400+ assert _control_raw("POST", f"{prefix}/{name}/policy", key=creds)[0] == 405+ assert _control_raw("GET", f"{prefix}/{name}", key=creds)[0] == (403 if auth_enabled else 200)+ finally:+ iam.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])+ ctl = _client("s3control")+ assert ctl.get_access_point_for_object_lambda(AccountId=ACCOUNT, Name=name)["Name"] == name+ assert ctl.get_access_point_policy_for_object_lambda(AccountId=ACCOUNT, Name=name)["Policy"] == policy++# --- Routing and WriteGetObjectResponse ------------------------------------def test_object_lambda_routing_unknown_name():