Skip to content

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

fix(sfn): shape aws-sdk JSON-protocol results by the output model (#2165) (#2206)

Lucas38f6d2d45897
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 60874fea..abf5eae3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Auth — header signatures are verified for IAM user and STS session keys** — under `AUTH=true` a request signed with such a key and the wrong secret, or changed after signing, was served; it now answers `SignatureDoesNotMatch` (or the service's `InvalidSignatureException`), an `Authorization` header without its `Signature` or `SignedHeaders` answers `IncompleteSignature` (Lambda `MissingAuthenticationTokenException`, S3 `AuthorizationHeaderMalformed`) and a credential date other than the request date `SignatureDoesNotMatch` (S3 `AuthorizationHeaderMalformed`), S3 unsigned, streaming and signed-chunk payloads are checked the same way, and the root key still accepts any secret. Contributed by @iot-rocket.
### Fixed
+- **Step Functions — aws-sdk results for JSON-protocol services keep the SDK's shape at every depth** — only the result's top-level keys took the SDK's names, so nested members kept their wire casing (`Executions[].executionArn`, `SecretList[].ARN`), timestamps stayed epoch numbers and absent members came back as `null`; the result is now shaped by the service's output model as on AWS: structure members renamed at every depth (DynamoDB's `BOOL`, `NULL` and `SS` as `Bool`, `Nul` and `Ss`), map keys such as attribute names and tag keys kept as sent, timestamps as ISO 8601 with milliseconds, and absent members left out. Two-letter all-caps member names (`SS`, `NS`, `ID`) now take the SDK's casing in every aws-sdk result.
- **Step Functions — JSONata Fail and Wait fields are evaluated** — a JSONata Fail state raised its `Error` and `Cause` expressions as literal text, a JSONata Wait failed on a `Seconds` expression, ignored a `Timestamp` expression and dropped its `Output` and `Assign`, and JSONPath `ErrorPath`/`CausePath` were ignored; they are now evaluated, with AWS's `States.QueryEvaluationError` or `States.Runtime` for a result of the wrong type, a `Seconds` that is not a non-negative integer and an unparsable `Timestamp`.
- **S3 — presigned URLs keep AWS's time limits under `AUTH=true`** — an `X-Amz-Expires` over 604800 seconds or not a number, or a malformed `X-Amz-Date`, answers 400 `AuthorizationQueryParametersError`, and a URL dated more than 15 minutes ahead answers 403 `AccessDenied` `Request is not yet valid`, where they were served. Contributed by @iot-rocket.
- **Auth — credential failures in the service's protocol** — under `AUTH=true` an unknown, inactive or expired access key answered `UnrecognizedClientException` 403 from every service; it now gets the code, status and `Content-Type` AWS sends for the service's protocol, for example `InvalidClientTokenId` 403 from IAM and SQS, `UnrecognizedClientException` 400 from DynamoDB, `InvalidAccessKeyId` 403 from S3 and `AuthFailure` 401 from EC2. Contributed by @iot-rocket.
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index f9fb1ea1..365ac31c 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -52,6 +52,7 @@ from ministack.core.concurrency import run_reentrant
from ministack.core.responses import (
AccountRegionScopedDict,
AccountScopedDict,
+ _service_model,
error_response_json,
get_account_id,
get_region,
@@ -3752,11 +3753,45 @@ def _dispatch_aws_sdk_json(service_info, service_name, action, input_data):
and isinstance(result, dict) and "SecretBinary" in result):
result["SecretBinary"] = base64.b64decode(result["SecretBinary"]).decode("utf-8", errors="replace")
- # For JSON-protocol services, only convert top-level keys to avoid
- # mangling user-defined data (e.g. DynamoDB attribute names).
- if isinstance(result, dict):
- return {_api_name_to_sfn_key(k): v for k, v in result.items()}
- return result
+ return _sdk_json_result(service_key, pascal_action, result)
+
+
+# The AWS SDK for Java v2 renames a member it cannot use as named, and Step
+# Functions returns that name: DynamoDB's NULL attribute value is Nul.
+_SDK_MEMBER_NAME_OVERRIDES = {("AttributeValue", "NULL"): "Nul"}
+
+
+def _sdk_json_result(service_key, action, result):
+ """A JSON-protocol aws-sdk result as Step Functions returns it. Step
+ Functions parses the response with the AWS SDK for Java v2, so the
+ operation's output model decides the shape: structure members take the
+ SDK's names, map keys are data and stay as sent (DynamoDB attribute names,
+ tag keys), timestamps become ISO 8601 and absent members are left out."""
+ model = _service_model(service_key)
+ shape = (model.operation_model(action).output_shape
+ if model is not None and action in model.operation_names else None)
+ if shape is None:
+ if isinstance(result, dict):
+ return {_api_name_to_sfn_key(k): v for k, v in result.items()}
+ return result
+ return _sdk_json_value(result, shape)
+
+
+def _sdk_json_value(value, shape):
+ if shape.type_name == "structure" and isinstance(value, dict):
+ return {
+ _SDK_MEMBER_NAME_OVERRIDES.get((shape.name, key), _api_name_to_sfn_key(key)):
+ _sdk_json_value(item, shape.members[key]) if key in shape.members else item
+ for key, item in value.items() if item is not None
+ }
+ if shape.type_name == "list" and isinstance(value, list):
+ return [_sdk_json_value(item, shape.member) for item in value]
+ if shape.type_name == "map" and isinstance(value, dict):
+ return {key: _sdk_json_value(item, shape.value) for key, item in value.items()}
+ if shape.type_name == "timestamp" and _is_num(value):
+ moment = datetime.fromtimestamp(value, timezone.utc)
+ return moment.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ return value
def _flatten_query_params(data, prefix=""):
@@ -4090,17 +4125,14 @@ def _api_name_to_sfn_key(name):
SFN uses the Java SDK V2 naming convention: consecutive uppercase characters
(acronyms) are lowered except the last one when followed by a lowercase char.
Examples: DBClusters -> DbClusters, DBClusterArn -> DbClusterArn,
- IAMDatabaseAuthenticationEnabled -> IamDatabaseAuthenticationEnabled
+ IAMDatabaseAuthenticationEnabled -> IamDatabaseAuthenticationEnabled,
+ SS -> Ss
"""
if not name:
return name
result = []
i = 0
while i < len(name):
- if i == 0:
- result.append(name[i].upper())
- i += 1
- continue
if name[i].isupper():
j = i
while j < len(name) and name[j].isupper():
@@ -4119,7 +4151,8 @@ def _api_name_to_sfn_key(name):
else:
result.append(name[i])
i += 1
- return "".join(result)
+ key = "".join(result)
+ return key[0].upper() + key[1:]
def _convert_keys_to_sfn_convention(obj):
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index f37ca8b2..54729311 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -2571,6 +2571,80 @@ def test_sfn_aws_sdk_ec2_irregular_set_members_use_sdk_names(sfn_sync, ec2):
ec2.delete_key_pair(KeyName=f"sdk-key-{suffix}")
+_SDK_TIMESTAMP = r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$"
+
+
+def test_sfn_aws_sdk_sfn_list_executions_nested_shape(sfn_sync):
+ """Nested members of a JSON-protocol result take the SDK's names, timestamps
+ are ISO 8601 and an absent stopDate is left out, as on AWS."""
+ import re
+
+ suffix = _uuid_mod.uuid4().hex[:8]
+ with _machine(sfn_sync, "Wait", {"Wait": {"Type": "Wait", "Seconds": 3600, "End": True}}) as target:
+ sfn_sync.start_execution(stateMachineArn=target, name="single-1")
+ result = _run_sdk_task(sfn_sync, f"sdk-list-{suffix}", "sfn:listExecutions",
+ {"StateMachineArn": target, "StatusFilter": "RUNNING"})
+
+ [execution] = result["Executions"]
+ assert sorted(execution) == ["ExecutionArn", "Name", "StartDate", "StateMachineArn", "Status"]
+ assert execution["Name"] == "single-1"
+ assert execution["Status"] == "RUNNING"
+ assert re.match(_SDK_TIMESTAMP, execution["StartDate"]), execution["StartDate"]
+
+
+def test_sfn_aws_sdk_dynamodb_get_item_keeps_attribute_names(sfn_sync, ddb):
+ """Attribute names are map keys and stay as written at every depth, while the
+ AttributeValue members take the SDK's names. The expected item is what AWS
+ returned for the same put."""
+ table = f"sdk-item-{_uuid_mod.uuid4().hex[:8]}"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ try:
+ ddb.put_item(TableName=table, Item={
+ "pk": {"S": "k"}, "num": {"N": "7"}, "flag": {"BOOL": True}, "nothing": {"NULL": True},
+ "set": {"SS": ["a", "b"]}, "nums": {"NS": ["1"]},
+ "nested": {"M": {"innerKey": {"S": "v"}, "UPPER_key": {"N": "1"}}},
+ "list": {"L": [{"S": "x"}]},
+ })
+ result = _run_sdk_task(sfn_sync, f"{table}-get", "dynamodb:getItem",
+ {"TableName": table, "Key": {"pk": {"S": "k"}}})
+ finally:
+ ddb.delete_table(TableName=table)
+
+ assert result["Item"] == {
+ "pk": {"S": "k"}, "num": {"N": "7"}, "flag": {"Bool": True}, "nothing": {"Nul": True},
+ "set": {"Ss": ["a", "b"]}, "nums": {"Ns": ["1"]},
+ "nested": {"M": {"innerKey": {"S": "v"}, "UPPER_key": {"N": "1"}}},
+ "list": {"L": [{"S": "x"}]},
+ }
+
+
+def test_sfn_aws_sdk_json_results_rename_nested_members(sfn_sync, sm):
+ """An ARN member nested in a list becomes Arn, map keys such as version ids
+ stay as sent, and tag lists keep their Key/Value members."""
+ import re
+
+ name = f"sdk-secret-{_uuid_mod.uuid4().hex[:8]}"
+ version = sm.create_secret(Name=name, SecretString="x",
+ Tags=[{"Key": "owner", "Value": "probe"}])["VersionId"]
+ try:
+ result = _run_sdk_task(sfn_sync, f"{name}-list", "secretsmanager:listSecrets",
+ {"Filters": [{"Key": "name", "Values": [name]}]})
+ finally:
+ sm.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)
+
+ [secret] = result["SecretList"]
+ assert secret["Arn"].startswith(f"arn:aws:secretsmanager:us-east-1:000000000000:secret:{name}")
+ assert "ARN" not in secret
+ assert re.match(_SDK_TIMESTAMP, secret["CreatedDate"]), secret["CreatedDate"]
+ assert secret["Tags"] == [{"Key": "owner", "Value": "probe"}]
+ assert secret["SecretVersionsToStages"] == {version: ["AWSCURRENT"]}
+
+
def test_sfn_aws_sdk_rds_create_and_describe_instance(sfn, sfn_sync):
"""aws-sdk:rds CreateDBInstance + DescribeDBInstances via query-protocol dispatch."""
import uuid as _uuid