Skip to content

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

listobject copyobject sfn (#575)

Nahuel Nucera12eee9b70c99
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5dfa379a..4d86bc8c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -830,6 +830,9 @@ These services stored per-tenant data in plain `dict` / `list`, so `List*` / `De
- **Dynamic RDS storage** — new `RDS_PERSIST=1` env var switches database containers from fixed-size tmpfs to Docker named volumes for auto-growing persistent storage. Default (`RDS_PERSIST=0`) remains ephemeral tmpfs for CI/CD. Reported by @macario1983 (#248).
- **Dual Docker Hub publishing** — Docker images now publish to both `nahuelnucera/ministack` and `ministackorg/ministack` on tag push.
+### Fixed
+- **Step Functions `aws-sdk:s3` integration** — `arn:aws:states:::aws-sdk:s3:listObjectsV2`, `:copyObject`, and other S3 control-plane operations now dispatch correctly. Previously, S3 was tagged as `rest`-protocol with no dispatcher and every call failed with `States.Runtime`: "aws-sdk integration for rest-protocol service 's3' is not yet implemented". A REST-XML dispatcher now drives a hand-tabled spec for list/head/copy/delete/tagging operations, mapping each `Parameters` field to its botocore-modelled URI/querystring/header location and returning XML responses normalised to the SFN PascalCase convention. Reported by @LeTrungNguyen1703 (#573). Phase 1 covers `ListBuckets`, `CreateBucket`, `DeleteBucket`, `HeadBucket`, `GetBucketVersioning`, `ListObjectsV2`, `ListObjects`, `HeadObject`, `CopyObject`, `DeleteObject`, `GetObjectTagging`, `PutObjectTagging`. `GetObject`/`PutObject` (Body-bearing operations) deferred to Phase 2.
+
---
## [1.2.0] — 2026-04-11
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 83044d9e..2c5a9c5a 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -2386,8 +2386,9 @@ _AWS_SDK_SERVICE_MAP = {
"cloudwatch": {"protocol": "query", "service_key": "monitoring"},
# REST-JSON services: path-based routing with JSON body
"rdsdata": {"protocol": "rest-json", "service_key": "rds-data"},
+ # REST-XML services: per-op path templates, header/querystring routing, XML responses
+ "s3": {"protocol": "rest-xml", "service_key": "s3"},
# REST services (not yet supported via aws-sdk dispatcher)
- "s3": {"protocol": "rest"},
"lambda": {"protocol": "rest"},
}
@@ -3021,6 +3022,332 @@ def _dispatch_aws_sdk_rest_json(service_info, service_name, action, input_data):
return decoded
+# ---------------------------------------------------------------------------
+# REST-XML aws-sdk dispatch (S3)
+# ---------------------------------------------------------------------------
+#
+# Per-operation spec table. Each entry mirrors botocore's S3 service-2.json
+# routing for one operation. Avoids a botocore runtime dependency.
+#
+# Fields:
+# method: HTTP verb sent to the s3 handler.
+# path: path template; "{Bucket}" and "{Key+}" substituted from input.
+# query_params: {InputFieldPascalCase: querystring-name}.
+# Static "list-type=2" style flags are appended below.
+# header_params: {InputFieldPascalCase: HTTP-header-name}.
+# static_query: static query-string pairs always appended (e.g. "list-type=2").
+# result_root: XML element name unwrapped from the response body. None means
+# return the raw parsed dict.
+# list_fields: tuple of dict-keys whose XML "<X><Member/></X>" or repeated
+# child element should be normalised to a Python list (S3 XML is
+# inconsistent: ListBucketResult.Contents is a repeated element,
+# not a wrapped list).
+# header_outputs:{HTTP-header-name: OutputFieldPascalCase} response headers
+# to fold into the result dict (e.g. ETag from PUT/COPY).
+#
+# Phase 1 covers non-Body operations (no GetObject/PutObject). Body shape for
+# aws-sdk:s3:getObject/putObject is convention-based (Java SDK V2 → base64) and
+# not currently doc-cited; defer until verified.
+_S3_OP_SPECS = {
+ "ListBuckets": {
+ "method": "GET", "path": "/",
+ "result_root": "ListAllMyBucketsResult",
+ "list_fields": ("Buckets",),
+ },
+ "CreateBucket": {
+ "method": "PUT", "path": "/{Bucket}",
+ "header_params": {"ACL": "x-amz-acl"},
+ "result_root": None,
+ "header_outputs": {"location": "Location"},
+ },
+ "DeleteBucket": {
+ "method": "DELETE", "path": "/{Bucket}",
+ "result_root": None,
+ },
+ "HeadBucket": {
+ "method": "HEAD", "path": "/{Bucket}",
+ "result_root": None,
+ },
+ "GetBucketVersioning": {
+ "method": "GET", "path": "/{Bucket}",
+ "static_query": (("versioning", ""),),
+ "result_root": "VersioningConfiguration",
+ },
+ "ListObjectsV2": {
+ "method": "GET", "path": "/{Bucket}",
+ "static_query": (("list-type", "2"),),
+ "query_params": {
+ "Prefix": "prefix",
+ "Delimiter": "delimiter",
+ "MaxKeys": "max-keys",
+ "ContinuationToken": "continuation-token",
+ "StartAfter": "start-after",
+ "EncodingType": "encoding-type",
+ "FetchOwner": "fetch-owner",
+ },
+ "result_root": "ListBucketResult",
+ "list_fields": ("Contents", "CommonPrefixes"),
+ },
+ "ListObjects": {
+ "method": "GET", "path": "/{Bucket}",
+ "query_params": {
+ "Prefix": "prefix",
+ "Delimiter": "delimiter",
+ "MaxKeys": "max-keys",
+ "Marker": "marker",
+ "EncodingType": "encoding-type",
+ },
+ "result_root": "ListBucketResult",
+ "list_fields": ("Contents", "CommonPrefixes"),
+ },
+ "HeadObject": {
+ "method": "HEAD", "path": "/{Bucket}/{Key+}",
+ "query_params": {"VersionId": "versionId"},
+ "result_root": None,
+ "header_outputs": {
+ "etag": "ETag",
+ "content-length": "ContentLength",
+ "content-type": "ContentType",
+ "last-modified": "LastModified",
+ "x-amz-version-id": "VersionId",
+ },
+ },
+ "CopyObject": {
+ "method": "PUT", "path": "/{Bucket}/{Key+}",
+ "header_params": {
+ "CopySource": "x-amz-copy-source",
+ "MetadataDirective": "x-amz-metadata-directive",
+ "TaggingDirective": "x-amz-tagging-directive",
+ "ACL": "x-amz-acl",
+ "StorageClass": "x-amz-storage-class",
+ },
+ "result_root": "CopyObjectResult",
+ "header_outputs": {"x-amz-version-id": "VersionId"},
+ },
+ "DeleteObject": {
+ "method": "DELETE", "path": "/{Bucket}/{Key+}",
+ "query_params": {"VersionId": "versionId"},
+ "result_root": None,
+ "header_outputs": {
+ "x-amz-version-id": "VersionId",
+ "x-amz-delete-marker": "DeleteMarker",
+ },
+ },
+ "GetObjectTagging": {
+ "method": "GET", "path": "/{Bucket}/{Key+}",
+ "static_query": (("tagging", ""),),
+ "query_params": {"VersionId": "versionId"},
+ "result_root": "Tagging",
+ "list_fields": ("TagSet",),
+ },
+ "PutObjectTagging": {
+ "method": "PUT", "path": "/{Bucket}/{Key+}",
+ "static_query": (("tagging", ""),),
+ "query_params": {"VersionId": "versionId"},
+ "body_field": "Tagging",
+ "body_root": "Tagging",
+ "result_root": None,
+ },
+}
+
+
+def _s3_substitute_path(template, input_data):
+ """Substitute {Bucket} and {Key+} placeholders. {Key+} preserves slashes."""
+ out = template
+ if "{Bucket}" in out:
+ bucket = input_data.get("Bucket", "")
+ out = out.replace("{Bucket}", bucket)
+ if "{Key+}" in out:
+ key = input_data.get("Key", "")
+ out = out.replace("{Key+}", key)
+ return out
+
+
+def _s3_build_xml_body(root_name, payload):
+ """Build a minimal XML body for the small handful of ops that need one."""
+ import xml.etree.ElementTree as ET
+ root = ET.Element(root_name)
+
+ def _emit(parent, name, value):
+ if isinstance(value, dict):
+ child = ET.SubElement(parent, name)
+ for k, v in value.items():
+ _emit(child, k, v)
+ elif isinstance(value, list):
+ for item in value:
+ _emit(parent, name, item)
+ else:
+ child = ET.SubElement(parent, name)
+ child.text = "" if value is None else str(value)
+
+ if isinstance(payload, dict):
+ for k, v in payload.items():
+ _emit(root, k, v)
+ return ET.tostring(root, encoding="utf-8", short_empty_elements=False)
+
+
+def _s3_normalize_lists(parsed, list_fields):
+ """Force fields named in list_fields to be Python lists in the parsed dict.
+
+ S3's XML mixes two list patterns: ``<Buckets><Bucket>..</Bucket>..</Buckets>``
+ (wrapped) and ``<Contents>..</Contents><Contents>..</Contents>`` (repeated
+ siblings). Both arrive here as the parent value being one of:
+ empty-string (no items), dict (single item, possibly wrapped under "Bucket"
+ or similar), or list (multiple items). Always normalise to a list.
+ """
+ if not isinstance(parsed, dict) or not list_fields:
+ return parsed
+ for field in list_fields:
+ if field not in parsed:
+ continue
+ value = parsed[field]
+ if value in (None, ""):
+ parsed[field] = []
+ elif isinstance(value, dict):
+ # Wrapped form: {"Bucket": [...]} or {"Bucket": {...}} → unwrap.
+ if len(value) == 1:
+ inner = next(iter(value.values()))
+ if isinstance(inner, list):
+ parsed[field] = inner
+ else:
+ parsed[field] = [inner] if inner not in (None, "") else []
+ else:
+ parsed[field] = [value]
+ # If already a list, leave alone.
+ return parsed
+
+
+def _dispatch_aws_sdk_rest_xml(service_info, service_name, action, input_data):
+ """Dispatch an aws-sdk integration call to a REST-XML protocol service (S3)."""
+ import xml.etree.ElementTree as ET
+ from urllib.parse import urlencode, quote
+
+ from ministack import app
+
+ service_key = service_info.get("service_key", service_name)
+ handler = app.SERVICE_HANDLERS.get(service_key)
+ if not handler:
+ raise _ExecutionError(
+ "States.Runtime",
+ f"Service '{service_key}' is not available in MiniStack",
+ )
+
+ pascal_action = action[0].upper() + action[1:] if action else action
+ spec = _S3_OP_SPECS.get(pascal_action)
+ if not spec:
+ raise _ExecutionError(
+ "States.Runtime",
+ f"aws-sdk:{service_name}:{action} is not yet implemented in MiniStack "
+ "(rest-xml dispatcher Phase 1 covers list/head/copy/delete/tagging operations)",
+ )
+
+ input_data = input_data or {}
+ method = spec["method"]
+ path = _s3_substitute_path(spec["path"], input_data)
+
+ # S3 handler routes by the query_params dict, not by parsing the path —
+ # so build the dict and ALSO append a query string for handlers that
+ # inspect the raw path. Both forms stay in sync.
+ query_dict = {}
+ query_pairs = []
+ for key, qname in (spec.get("query_params") or {}).items():
+ if key in input_data and input_data[key] is not None:
+ query_dict[qname] = str(input_data[key])
+ query_pairs.append((qname, str(input_data[key])))
+ for qname, qvalue in spec.get("static_query") or ():
+ query_dict[qname] = qvalue
+ query_pairs.append((qname, qvalue))
+ if query_pairs:
+ path_with_query = f"{path}?{urlencode(query_pairs, quote_via=quote)}"
+ else:
+ path_with_query = path
+
+ headers = {
+ "host": f"{service_key}.{REGION}.amazonaws.com",
+ "authorization": (
+ f"AWS4-HMAC-SHA256 Credential=test/20260101/{REGION}/{service_key}/aws4_request"
+ ),
+ }
+ for key, hname in (spec.get("header_params") or {}).items():
+ if key in input_data and input_data[key] is not None:
+ headers[hname.lower()] = str(input_data[key])
+
+ body = b""
+ body_field = spec.get("body_field")
+ if body_field and body_field in input_data:
+ body = _s3_build_xml_body(spec.get("body_root", body_field), input_data[body_field])
+ headers["content-type"] = "application/xml"
+ headers["content-length"] = str(len(body))
+
+ # S3's path parser splits on "/" without stripping the query string —
+ # passing the raw path with "?..." would treat "?list-type=2" as part of
+ # the bucket name. Send the query-less path; the dict is the source of
+ # truth for query routing.
+ coro = handler(method, path, headers, body, query_dict)
+ try:
+ coro.send(None)
+ except StopIteration as stop:
+ status, resp_headers, resp_body = stop.value
+ else:
+ coro.close()
+ loop = asyncio.new_event_loop()
+ try:
+ status, resp_headers, resp_body = loop.run_until_complete(
+ handler(method, path, headers, body, query_dict)
+ )
+ finally:
+ loop.close()
+
+ decoded = resp_body.decode("utf-8") if isinstance(resp_body, bytes) else (resp_body or "")
+ norm_resp_headers = {k.lower(): v for k, v in (resp_headers or {}).items()}
+
+ if status >= 400:
+ code = "S3Exception"
+ message = decoded or f"S3 returned status {status}"
+ if decoded:
+ try:
+ err_root = ET.fromstring(decoded)
+ code_el = err_root.find("Code")
+ msg_el = err_root.find("Message")
+ if code_el is not None and code_el.text:
+ code = code_el.text
+ if msg_el is not None and msg_el.text:
+ message = msg_el.text
+ except ET.ParseError:
+ pass
+ raise _ExecutionError(f"S3.{code}", message)
+
+ result = {}
+ if decoded.strip():
+ try:
+ root = ET.fromstring(decoded)
+ _, parsed = _xml_element_to_dict(root)
+ if isinstance(parsed, dict):
+ result = parsed
+ elif parsed in (None, ""):
+ result = {}
+ else:
+ result = {"Result": parsed}
+ except ET.ParseError:
+ result = {}
+
+ for hname, output_key in (spec.get("header_outputs") or {}).items():
+ if hname in norm_resp_headers:
+ value = norm_resp_headers[hname]
+ if output_key in ("ContentLength",):
+ try:
+ value = int(value)
+ except (TypeError, ValueError):
+ pass
+ elif output_key == "DeleteMarker":
+ value = str(value).lower() == "true"
+ result[output_key] = value
+
+ result = _s3_normalize_lists(result, spec.get("list_fields") or ())
+
+ return _convert_keys_to_sfn_convention(result)
+
+
def _invoke_aws_sdk_integration(resource, input_data):
"""Dispatch arn:aws:states:::aws-sdk:<service>:<action> to the target MiniStack service."""
# Parse service and action from ARN
@@ -3046,6 +3373,8 @@ def _invoke_aws_sdk_integration(resource, input_data):
return _dispatch_aws_sdk_query(service_info, service_name, action, input_data)
elif protocol == "rest-json":
return _dispatch_aws_sdk_rest_json(service_info, service_name, action, input_data)
+ elif protocol == "rest-xml":
+ return _dispatch_aws_sdk_rest_xml(service_info, service_name, action, input_data)
else:
raise _ExecutionError(
"States.Runtime",
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 5174a7fe..58082f27 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -2692,6 +2692,195 @@ def test_sfn_aws_sdk_rdsdata_path_mapping():
assert rds_data_paths["BeginTransaction"] == "/BeginTransaction"
assert rds_data_paths["CommitTransaction"] == "/CommitTransaction"
assert rds_data_paths["RollbackTransaction"] == "/RollbackTransaction"
+
+
+# ---------------------------------------------------------------------------
+# REST-XML aws-sdk dispatch (S3) — Issue #573
+# ---------------------------------------------------------------------------
+
+
+def test_sfn_aws_sdk_s3_list_objects_v2(sfn_sync, s3):
+ """aws-sdk:s3:listObjectsV2 returns object listing through REST-XML dispatch."""
+ import uuid as _uuid
+
+ bucket = f"sfn-s3-list-{_uuid.uuid4().hex[:8]}"
+ sm_name = f"sdk-s3-list-{_uuid.uuid4().hex[:8]}"
+ sm_arn = None
+ try:
+ s3.create_bucket(Bucket=bucket)
+ s3.put_object(Bucket=bucket, Key="alpha/one.txt", Body=b"a")
+ s3.put_object(Bucket=bucket, Key="alpha/two.txt", Body=b"b")
+ s3.put_object(Bucket=bucket, Key="beta/three.txt", Body=b"c")
+
+ definition = json.dumps({
+ "StartAt": "List",
+ "States": {
+ "List": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::aws-sdk:s3:listObjectsV2",
+ "Parameters": {"Bucket": bucket, "Prefix": "alpha/"},
+ "End": True,
+ },
+ },
+ })
+
+ sm_arn = sfn_sync.create_state_machine(
+ name=sm_name,
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/sfn-role",
+ )["stateMachineArn"]
+
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input=json.dumps({}))
+ assert resp["status"] == "SUCCEEDED", f"{resp.get('error')} — {resp.get('cause')}"
+ output = json.loads(resp["output"])
+ keys = sorted(item["Key"] for item in output.get("Contents", []))
+ assert keys == ["alpha/one.txt", "alpha/two.txt"]
+ finally:
+ for k in ("alpha/one.txt", "alpha/two.txt", "beta/three.txt"):
+ try:
+ s3.delete_object(Bucket=bucket, Key=k)
+ except Exception:
+ pass
+ try:
+ s3.delete_bucket(Bucket=bucket)
+ except Exception:
+ pass
+ if sm_arn:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_aws_sdk_s3_copy_object(sfn_sync, s3):
+ """aws-sdk:s3:copyObject duplicates an object via x-amz-copy-source header."""
+ import uuid as _uuid
+
+ bucket = f"sfn-s3-copy-{_uuid.uuid4().hex[:8]}"
+ sm_name = f"sdk-s3-copy-{_uuid.uuid4().hex[:8]}"
+ sm_arn = None
+ try:
+ s3.create_bucket(Bucket=bucket)
+ s3.put_object(Bucket=bucket, Key="src.txt", Body=b"hello")
+
+ definition = json.dumps({
+ "StartAt": "Copy",
+ "States": {
+ "Copy": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::aws-sdk:s3:copyObject",
+ "Parameters": {
+ "Bucket": bucket,
+ "Key": "dst.txt",
+ "CopySource": f"{bucket}/src.txt",
+ },
+ "End": True,
+ },
+ },
+ })
+
+ sm_arn = sfn_sync.create_state_machine(
+ name=sm_name,
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/sfn-role",
+ )["stateMachineArn"]
+
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input=json.dumps({}))
+ assert resp["status"] == "SUCCEEDED", f"{resp.get('error')} — {resp.get('cause')}"
+
+ copied = s3.get_object(Bucket=bucket, Key="dst.txt")["Body"].read()
+ assert copied == b"hello"
+ finally:
+ for k in ("src.txt", "dst.txt"):
+ try:
+ s3.delete_object(Bucket=bucket, Key=k)
+ except Exception:
+ pass
+ try:
+ s3.delete_bucket(Bucket=bucket)
+ except Exception:
+ pass
+ if sm_arn:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_aws_sdk_s3_list_buckets(sfn_sync, s3):
+ """aws-sdk:s3:listBuckets returns the bucket list via REST-XML."""
+ import uuid as _uuid
+
+ marker_bucket = f"sfn-s3-marker-{_uuid.uuid4().hex[:8]}"
+ sm_name = f"sdk-s3-listbuckets-{_uuid.uuid4().hex[:8]}"
+ sm_arn = None
+ try:
+ s3.create_bucket(Bucket=marker_bucket)
+
+ definition = json.dumps({
+ "StartAt": "ListBuckets",
+ "States": {
+ "ListBuckets": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::aws-sdk:s3:listBuckets",
+ "Parameters": {},
+ "End": True,
+ },
+ },
+ })
+
+ sm_arn = sfn_sync.create_state_machine(
+ name=sm_name,
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/sfn-role",
+ )["stateMachineArn"]
+
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input=json.dumps({}))
+ assert resp["status"] == "SUCCEEDED", f"{resp.get('error')} — {resp.get('cause')}"
+ output = json.loads(resp["output"])
+ names = [b["Name"] for b in output.get("Buckets", [])]
+ assert marker_bucket in names
+ finally:
+ try:
+ s3.delete_bucket(Bucket=marker_bucket)
+ except Exception:
+ pass
+ if sm_arn:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_aws_sdk_s3_unsupported_op_returns_helpful_error(sfn_sync):
+ """aws-sdk:s3:getObject (Phase 2) returns a clear 'not yet implemented' error."""
+ import uuid as _uuid
+
+ sm_name = f"sdk-s3-unsupported-{_uuid.uuid4().hex[:8]}"
+
+ definition = json.dumps({
+ "StartAt": "Get",
+ "States": {
+ "Get": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::aws-sdk:s3:getObject",
+ "Parameters": {"Bucket": "x", "Key": "y"},
+ "End": True,
+ },
+ },
+ })
+
+ sm_arn = sfn_sync.create_state_machine(
+ name=sm_name,
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/sfn-role",
+ )["stateMachineArn"]
+
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input=json.dumps({}))
+ assert resp["status"] == "FAILED"
+ cause = (resp.get("cause") or "").lower()
+ assert "not yet implemented" in cause and "getobject" in cause
+
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_aws_sdk_s3_op_specs_cover_issue_573_request():
+ """The two ops the original bug report named must be in the Phase 1 spec table."""
+ from ministack.services.stepfunctions import _S3_OP_SPECS
+
+ assert "ListObjectsV2" in _S3_OP_SPECS
+ assert "CopyObject" in _S3_OP_SPECS
# ---------------------------------------------------------------------------
# Terraform compatibility tests
# ---------------------------------------------------------------------------