Skip to content

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

feat(stepfunctions): States.StringSplit and States.Hash (#1509)

Maximilian Bandle65b8a11debdf
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index e41ea94b..28e3aa4e 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -3777,9 +3777,14 @@ def _eval_intrinsic_arg(arg, data, ctx):
return None
-# Real AWS caps both base64 intrinsics at 10,000 characters of input
+# Real AWS caps the base64 intrinsics and States.Hash at 10,000 characters of input
_BASE64_INTRINSIC_MAX = 10_000
+# The five States.Hash publishes, mapped to what hashlib calls them.
+_HASH_INTRINSIC_ALGORITHMS = {
+ "MD5": "md5", "SHA-1": "sha1", "SHA-256": "sha256", "SHA-384": "sha384", "SHA-512": "sha512",
+}
+
def _base64_intrinsic_arg(name, value):
"""Validate single string argument of States.Base64Encode / States.Base64Decode."""
@@ -3833,6 +3838,28 @@ def _exec_intrinsic(node, data, ctx):
out.append(ch)
i += 1
return "".join(out)
+ elif name == "States.Hash":
+ import hashlib
+ text, algorithm = args[0], args[1]
+ digest = _HASH_INTRINSIC_ALGORITHMS.get(algorithm)
+ if digest is None or not isinstance(text, str) or len(text) > _BASE64_INTRINSIC_MAX:
+ raise ValueError(f"Invalid arguments in {name}")
+ return hashlib.new(digest, text.encode("utf-8")).hexdigest()
+ elif name == "States.StringSplit":
+ # Every character of the second argument is a delimiter in its own right, and a run of them
+ # yields no empty members, so splitting an ARN on ":" indexes the same either way.
+ text, delimiters = args[0], args[1]
+ parts, current = [], []
+ for ch in text:
+ if ch in delimiters:
+ if current:
+ parts.append("".join(current))
+ current = []
+ else:
+ current.append(ch)
+ if current:
+ parts.append("".join(current))
+ return parts
elif name == "States.ArrayGetItem":
return args[0][int(args[1])]
elif name == "States.Array":
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 7ee33c84..ecee6134 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -1,4 +1,5 @@
import base64
+import hashlib
import io
import json
import os
@@ -563,6 +564,90 @@ def test_sfn_intrinsic_json_merge(sfn, sfn_sync):
output = json.loads(resp["output"])
assert output["merged"] == {"a": 1, "b": 2, "c": 99}
+def test_sfn_intrinsic_hash(sfn, sfn_sync):
+ """States.Hash covers AWS's five algorithms and refuses anything else."""
+ definition = json.dumps({
+ "StartAt": "Hash",
+ "States": {
+ "Hash": {
+ "Type": "Pass",
+ "Parameters": {
+ "md5.$": "States.Hash($.text, 'MD5')",
+ "sha1.$": "States.Hash($.text, 'SHA-1')",
+ "sha256.$": "States.Hash($.text, 'SHA-256')",
+ "sha384.$": "States.Hash($.text, 'SHA-384')",
+ "sha512.$": "States.Hash($.text, 'SHA-512')",
+ },
+ "End": True,
+ }
+ },
+ })
+ sm = sfn.create_state_machine(
+ name="sfn-intrinsic-hash",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ resp = sfn_sync.start_sync_execution(
+ stateMachineArn=sm["stateMachineArn"], input=json.dumps({"text": "input data"}))
+ assert resp["status"] == "SUCCEEDED"
+ output = json.loads(resp["output"])
+ # Lowercase hex of the UTF-8 bytes, so the digests are the ones any other tool produces.
+ assert output["md5"] == hashlib.md5(b"input data").hexdigest()
+ assert output["sha1"] == hashlib.sha1(b"input data").hexdigest()
+ assert output["sha256"] == hashlib.sha256(b"input data").hexdigest()
+ assert output["sha384"] == hashlib.sha384(b"input data").hexdigest()
+ assert output["sha512"] == hashlib.sha512(b"input data").hexdigest()
+
+ # An algorithm AWS does not publish is refused rather than passed to hashlib.
+ bad = sfn.create_state_machine(
+ name="sfn-intrinsic-hash-bad",
+ definition=json.dumps({"StartAt": "H", "States": {"H": {
+ "Type": "Pass", "Parameters": {"h.$": "States.Hash($.text, 'SHA-224')"}, "End": True}}}),
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ resp = sfn_sync.start_sync_execution(
+ stateMachineArn=bad["stateMachineArn"], input=json.dumps({"text": "input data"}))
+ assert resp["status"] == "FAILED"
+ assert resp.get("error") == "States.Runtime"
+
+def test_sfn_intrinsic_string_split(sfn, sfn_sync):
+ """States.StringSplit takes a set of delimiter characters and keeps no empty member."""
+ definition = json.dumps({
+ "StartAt": "Split",
+ "States": {
+ "Split": {
+ "Type": "Pass",
+ "Parameters": {
+ "simple.$": "States.StringSplit($.csv, ',')",
+ "charset.$": "States.StringSplit($.mixed, '.+,=')",
+ "runs.$": "States.StringSplit($.runs, ',')",
+ "absent.$": "States.StringSplit($.plain, ',')",
+ # Recovering the region from the execution ARN, which is what needs this.
+ "region.$": "States.ArrayGetItem(States.StringSplit($$.Execution.Id, ':'), 3)",
+ },
+ "End": True,
+ }
+ },
+ })
+ sm = sfn.create_state_machine(
+ name="sfn-intrinsic-split",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ resp = sfn_sync.start_sync_execution(
+ stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps({"csv": "1,2,3", "mixed": "This.is+a,test=string",
+ "runs": ",a,,b,", "plain": "abc"}),
+ )
+ assert resp["status"] == "SUCCEEDED"
+ output = json.loads(resp["output"])
+ assert output["simple"] == ["1", "2", "3"]
+ assert output["charset"] == ["This", "is", "a", "test", "string"]
+ # Runs of delimiters, and delimiters at either end, contribute nothing.
+ assert output["runs"] == ["a", "b"]
+ assert output["absent"] == ["abc"]
+ assert output["region"] == "us-east-1"
+
def test_sfn_intrinsic_format(sfn, sfn_sync):
"""States.Format interpolates arguments into a template string."""
definition = json.dumps({