Skip to content

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

feat(stepfunctions): implement the States.Base64Encode/Decode intrinsics (#1360)

Maximilian Bandle2f8f5a52ab14
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 297a2731..8f2b83e0 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -3724,6 +3724,17 @@ def _eval_intrinsic_arg(arg, data, ctx):
return None
+# Real AWS caps both base64 intrinsics at 10,000 characters of input
+_BASE64_INTRINSIC_MAX = 10_000
+
+
+def _base64_intrinsic_arg(name, value):
+ """Validate single string argument of States.Base64Encode / States.Base64Decode."""
+ if not isinstance(value, str) or len(value) > _BASE64_INTRINSIC_MAX:
+ raise ValueError(f"Invalid arguments in {name}")
+ return value
+
+
def _exec_intrinsic(node, data, ctx):
"""Execute a parsed intrinsic call node ('call', name, args)."""
_, name, raw_args = node
@@ -3738,6 +3749,15 @@ def _exec_intrinsic(node, data, ctx):
merged.update(args[0])
merged.update(args[1])
return merged
+ elif name == "States.Base64Encode":
+ import base64
+ text = _base64_intrinsic_arg(name, args[0])
+ return base64.b64encode(text.encode("utf-8")).decode("ascii")
+ elif name == "States.Base64Decode":
+ import base64
+ raw = _base64_intrinsic_arg(name, args[0])
+ # AWS decodes leniently, so pad rather than reject input that arrives without it.
+ return base64.b64decode(raw + "=" * (-len(raw) % 4)).decode("utf-8", errors="replace")
elif name == "States.Format":
# AWS States.Format: \' → ', \{ → {, \} → }, \\ → \ in
# template segments only. Interpolated values are verbatim.
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index ae0380f3..cd0080f6 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -624,6 +624,76 @@ def test_sfn_intrinsic_format_escapes(sfn, sfn_sync):
assert output["backslash"] == "C:\\tmp"
assert output["preserved"] == "path: C:\\tmp\\file"
+def test_sfn_intrinsic_base64(sfn, sfn_sync):
+ """States.Base64Encode / Decode round-trip, nest, and decode leniently."""
+ definition = json.dumps({
+ "StartAt": "B64",
+ "States": {
+ "B64": {
+ "Type": "Pass",
+ "Parameters": {
+ "encoded.$": "States.Base64Encode($.text)",
+ "decoded.$": "States.Base64Decode($.b64)",
+ "unpadded.$": "States.Base64Decode('aGVsbG8')",
+ "utf8.$": "States.Base64Encode($.accented)",
+ "empty.$": "States.Base64Encode('')",
+ # The common shape: build a string, then encode it for an API that takes
+ # base64 only. Encode has to accept another intrinsic's result, not just a path.
+ "nested.$": "States.Base64Encode(States.Format('run {} now', $.text))",
+ "roundtrip.$": "States.Base64Decode(States.Base64Encode($.text))",
+ },
+ "End": True,
+ }
+ },
+ })
+ sm = sfn.create_state_machine(
+ name=f"sfn-intrinsic-b64-{_uuid_mod.uuid4().hex[:8]}",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ resp = sfn_sync.start_sync_execution(
+ stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps({"text": "hello", "b64": "RGF0YSB0byBlbmNvZGU=", "accented": "héllo→"}),
+ )
+ assert resp["status"] == "SUCCEEDED", resp.get("cause")
+ output = json.loads(resp["output"])
+ assert output["encoded"] == "aGVsbG8="
+ assert output["decoded"] == "Data to encode"
+ assert output["unpadded"] == "hello"
+ # UTF-8, not latin-1: "héllo→" is nine bytes, so twelve base64 characters.
+ assert output["utf8"] == "aMOpbGxv4oaS"
+ assert output["empty"] == ""
+ assert output["nested"] == "cnVuIGhlbGxvIG5vdw=="
+ assert output["roundtrip"] == "hello"
+
+
+def test_sfn_intrinsic_base64_rejects_what_aws_rejects(sfn, sfn_sync):
+ """Both base64 intrinsics cap input at 10,000 characters and require a string."""
+ def run(params, payload):
+ sm = sfn.create_state_machine(
+ name=f"sfn-b64-bad-{_uuid_mod.uuid4().hex[:8]}",
+ definition=json.dumps({"StartAt": "B", "States": {
+ "B": {"Type": "Pass", "Parameters": params, "End": True}}}),
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ return sfn_sync.start_sync_execution(stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps(payload))
+
+ ok = run({"out.$": "States.Base64Encode($.s)"}, {"s": "a" * 10_000})
+ assert ok["status"] == "SUCCEEDED", ok.get("cause")
+ assert len(json.loads(ok["output"])["out"]) == 13336
+
+ for params, payload, fn in (
+ ({"out.$": "States.Base64Encode($.s)"}, {"s": "a" * 10_001}, "States.Base64Encode"),
+ ({"out.$": "States.Base64Encode($.n)"}, {"n": 123}, "States.Base64Encode"),
+ ({"out.$": "States.Base64Decode($.s)"}, {"s": "YQ==" * 5_000}, "States.Base64Decode"),
+ ):
+ resp = run(params, payload)
+ assert resp["status"] == "FAILED", resp.get("output")
+ assert resp.get("error") == "States.Runtime", resp
+ assert f"Invalid arguments in {fn}" in (resp.get("cause") or ""), resp.get("cause")
+
+
def test_sfn_intrinsic_nested(sfn, sfn_sync):
"""Nested intrinsic: States.StringToJson(States.Format(...))"""
definition = json.dumps({