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(sfn): match AWS binary secret transport (#1813)
Jay Janssen8a3851a789d4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 121bdefb..43cf186a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **Step Functions — Secrets Manager binary values** — `aws-sdk:secretsmanager:getSecretValue`, `createSecret`, and `putSecretValue` now pass literal UTF-8 text in `SecretBinary`, matching the AWS SDK integration rather than exposing the HTTP API's base64 representation. Direct Secrets Manager API/SDK calls keep their existing binary encoding.- **Auto Scaling — scaling policies and scheduled actions keep their members** — `PutScalingPolicy` and `DescribePolicies` dropped `TargetTrackingConfiguration`, `StepAdjustments`, `PredictiveScalingConfiguration`, `EstimatedInstanceWarmup`, `MetricAggregationType` and `MinAdjustmentMagnitude`. They are stored and answered typed as on AWS, with only the members the policy type has, and `MaxCapacityBreachBehavior` defaults to `HonorMaxCapacity`. A member that is not a number gives `ValidationError` instead of a 500. `Alarms` stays empty where AWS lists the target tracking alarms. Scheduled actions keep `StartTime`, `EndTime` and `TimeZone`, and `DescribeScheduledActions` answers them with `Recurrence` and the sizes. Contributed by @iot-rocket.- **EC2 — subnets answer their DNS and IPv6 attributes** — `DescribeSubnets` answers `PrivateDnsNameOptionsOnLaunch`, `EnableDns64`, `Ipv6Native` and `AssignIpv6AddressOnCreation`, which it did not render, with AWS's defaults for a subnet created without them. `ModifySubnetAttribute` changes the private DNS name options. Contributed by @iot-rocket.- **EC2 — launch templates answer their tags and list versions newest first** — `CreateLaunchTemplate` and `DescribeLaunchTemplates` rendered tags under `tags`, so botocore dropped them; they answer `tagSet` now. `DescribeLaunchTemplateVersions` lists the newest version first, as AWS does. Contributed by @iot-rocket.@@ -29,6 +30,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFormation — a failed update rolls back its in-place changes** — the rollback kept every resource that existed before the update but did not undo what the update had changed on it, the limitation 1.5.8 shipped with. Each changed resource now goes back through its type's update handler with `UPDATE_IN_PROGRESS` / `UPDATE_COMPLETE` events, before the cleanup deletes what the update created. A custom resource whose own update failed is sent back too, and a revert that fails lands the stack in `UPDATE_ROLLBACK_FAILED`, which `ContinueUpdateRollback` retries or skips. `UPDATE_ROLLBACK_IN_PROGRESS` names the failed resource, the cleanup runs in `UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS` with `DELETE_IN_PROGRESS` events, and a delete that fails there no longer fails the rollback. An executed change set that rolls back restores the stack's parameters. AWS reverts resources in parallel, the emulator one after the other. Contributed by @iot-rocket.- **CloudFormation — an ECS cluster reads its settings back** — `ClusterSettings`, `DefaultCapacityProviderStrategy` and `Configuration` of `AWS::ECS::Cluster` were stored in the template's PascalCase (`Configuration` not at all), so `DescribeClusters` answered `[{}]` for the settings and the strategy. All three are stored in the API's camelCase now. `DescribeClusters` answers them also without `include`, where AWS needs `SETTINGS` or `CONFIGURATIONS`. Contributed by @iot-rocket.- **CloudFormation — VPCs, subnets, security groups, internet gateways and route tables carry the stack's tags** — the five types carried only the template's own tags. They now also get the stack-level tags and the three `aws:cloudformation:` tags, as on AWS, and a stack tag change is applied to them in place. Contributed by @iot-rocket.+## [1.5.16] — 2026-09-23### Addeddiff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex 10d9de41..126b9fea 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -27,6 +27,7 @@ SUCCEEDED / FAILED / TIMED_OUT / ABORTED.import astimport asyncio+import base64import contextvarsimport copyimport json@@ -3463,6 +3464,15 @@ def _dispatch_aws_sdk_json(service_info, service_name, action, input_data):wire_data = _convert_keys_to_camel(input_data or {})else:wire_data = input_data+ # Secrets Manager's SFN SDK integration takes literal UTF-8 text for+ # SecretBinary; its HTTP API takes base64. Translate only at this boundary,+ # without changing the state input or guessing whether the text is base64.+ if (service_name == "secretsmanager"+ and pascal_action in {"CreateSecret", "PutSecretValue"}+ and isinstance(wire_data, dict)+ and isinstance(wire_data.get("SecretBinary"), str)):+ wire_data = dict(wire_data)+ wire_data["SecretBinary"] = base64.b64encode(wire_data["SecretBinary"].encode("utf-8")).decode("ascii")body = json.dumps(wire_data)headers = {"x-amz-target": target,@@ -3490,6 +3500,10 @@ def _dispatch_aws_sdk_json(service_info, service_name, action, input_data):error_msg = result.get("message", result.get("Message", str(result)))raise _ExecutionError(_prefix_sdk_error(service_name, error_type), error_msg)+ if (service_name == "secretsmanager" and pascal_action == "GetSecretValue"+ 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):diff --git a/tests/test_stepfunctions_secret_binary.py b/tests/test_stepfunctions_secret_binary.pynew file mode 100644index 00000000..59b3004f--- /dev/null+++ b/tests/test_stepfunctions_secret_binary.py@@ -0,0 +1,156 @@+"""Secrets Manager binary transport at the Step Functions AWS SDK boundary.++The four read fixtures and two write representations reproduce a disposable+real-AWS Standard-workflow probe. AWS passes UTF-8 text here, not the base64+representation used by the Secrets Manager HTTP API. No encoding heuristic is+valid: a password can itself be valid base64, including valid UTF-8 when decoded.+"""++import base64+import json+import time+import uuid+from contextlib import contextmanager++import pytest+++@contextmanager+def _machine(sfn, start, states):+ arn = sfn.create_state_machine(+ name=f"sfn-binary-{uuid.uuid4().hex}",+ roleArn="arn:aws:iam::000000000000:role/R",+ type="STANDARD",+ definition=json.dumps({"StartAt": start, "States": states}),+ loggingConfiguration={"level": "OFF", "includeExecutionData": False},+ )["stateMachineArn"]+ try:+ yield arn+ finally:+ sfn.delete_state_machine(stateMachineArn=arn)+++def _run(sfn, arn, data):+ execution = sfn.start_execution(stateMachineArn=arn, input=json.dumps(data))["executionArn"]+ try:+ deadline = time.monotonic() + 30+ while time.monotonic() < deadline:+ result = sfn.describe_execution(executionArn=execution)+ if result["status"] != "RUNNING":+ assert result["status"] == "SUCCEEDED", result+ return json.loads(result["output"])+ time.sleep(0.05)+ pytest.fail("synthetic execution timed out")+ finally:+ if sfn.describe_execution(executionArn=execution)["status"] == "RUNNING":+ sfn.stop_execution(executionArn=execution)+++_READ_STATES = {+ "Read": {+ "Type": "Task",+ "Resource": "arn:aws:states:::aws-sdk:secretsmanager:getSecretValue",+ "Parameters": {"SecretId.$": "$.secretId"},+ "End": True,+ },+}+_WRITE_STATES = {+ "Create": {+ "Type": "Task",+ "Resource": "arn:aws:states:::aws-sdk:secretsmanager:createSecret",+ "Parameters": {"Name.$": "$.secretId", "SecretBinary.$": "$.binary"},+ "ResultPath": None,+ "Next": "Put",+ },+ "Put": {+ "Type": "Task",+ "Resource": "arn:aws:states:::aws-sdk:secretsmanager:putSecretValue",+ "Parameters": {+ "SecretId.$": "$.secretId",+ "SecretBinary.$": "$.updatedBinary",+ "VersionStages": ["AWSPENDING"],+ },+ "End": True,+ },+}++[email protected]("value", [+ pytest.param("abcdefghijklmnop", id="base64-invalid-utf8"),+ pytest.param("cmF3cGFzc3dvcmQ=", id="base64-valid-utf8"),+ pytest.param("not-base64!", id="non-base64"),+ pytest.param("quote'and\\slash", id="sql-metacharacters"),+])+def test_sfn_secret_binary_read_is_raw_text(sfn, sm, value):+ name = f"sfn-binary-{uuid.uuid4().hex}"+ created = sm.create_secret(Name=name, SecretBinary=value.encode("utf-8"))+ try:+ before = sm.get_secret_value(SecretId=name)+ assert before["SecretBinary"] == value.encode("utf-8")+ with _machine(sfn, "Read", _READ_STATES) as arn:+ result = _run(sfn, arn, {"secretId": name})+ assert result["SecretBinary"] == value+ assert result["SecretBinary"] != base64.b64encode(before["SecretBinary"]).decode("ascii")+ assert result["VersionId"] == created["VersionId"]+ assert "SecretString" not in result+ after = sm.get_secret_value(SecretId=name)+ assert after["SecretBinary"] == before["SecretBinary"]+ assert after["VersionId"] == before["VersionId"]+ finally:+ sm.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)++[email protected]("representation", ["raw", "base64"])+def test_sfn_secret_binary_writes_store_supplied_text(sfn, sm, representation):+ name = f"sfn-binary-{uuid.uuid4().hex}"+ original, updated = "abcdefghijklmnop", "not-base64!-updated"+ if representation == "base64":+ supplied = base64.b64encode(original.encode()).decode("ascii")+ supplied_update = base64.b64encode(updated.encode()).decode("ascii")+ else:+ supplied, supplied_update = original, updated+ try:+ with _machine(sfn, "Create", _WRITE_STATES) as arn:+ result = _run(sfn, arn, {+ "secretId": name, "binary": supplied, "updatedBinary": supplied_update,+ })+ current = sm.get_secret_value(SecretId=name, VersionStage="AWSCURRENT")+ pending = sm.get_secret_value(SecretId=name, VersionStage="AWSPENDING")+ assert current["SecretBinary"] == supplied.encode("utf-8")+ assert pending["SecretBinary"] == supplied_update.encode("utf-8")+ assert (current["SecretBinary"] == original.encode()) == (representation == "raw")+ assert (pending["SecretBinary"] == updated.encode()) == (representation == "raw")+ assert current["VersionId"] != pending["VersionId"]+ assert pending["VersionId"] == result["VersionId"]+ assert current["VersionStages"] == ["AWSCURRENT"]+ assert pending["VersionStages"] == ["AWSPENDING"]+ finally:+ sm.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)+++def test_sfn_secret_string_is_not_transformed(sfn, sm):+ name = f"sfn-binary-{uuid.uuid4().hex}"+ value = '{"password":"cmF3cGFzc3dvcmQ="}'+ sm.create_secret(Name=name, SecretString=value)+ try:+ with _machine(sfn, "Read", _READ_STATES) as arn:+ result = _run(sfn, arn, {"secretId": name})+ assert result["SecretString"] == value+ assert "SecretBinary" not in result+ finally:+ sm.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)+++def test_direct_secret_binary_sdk_keeps_arbitrary_bytes(sm):+ """The HTTP API must still base64-encode binary, including non-UTF-8 bytes."""+ name = f"sfn-binary-{uuid.uuid4().hex}"+ value = bytes(range(256))+ sm.create_secret(Name=name, SecretBinary=value)+ try:+ assert sm.get_secret_value(SecretId=name)["SecretBinary"] == value+ updated = sm.put_secret_value(SecretId=name, SecretBinary=value[::-1])+ result = sm.get_secret_value(SecretId=name)+ assert result["SecretBinary"] == value[::-1]+ assert result["VersionId"] == updated["VersionId"]+ finally:+ sm.delete_secret(SecretId=name, ForceDeleteWithoutRecovery=True)