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 Step Functions Choice context paths (#1922)
Jay Janssen927ef58738a0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e0cc4d34..a6e19e7e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFormation — `AWS::Lambda::Version` updates `FunctionScalingConfig` in place** — a stack update re-ran the create, which published a new version for every change; a `FunctionScalingConfig` change now keeps the version, also when the update rolls back. Contributed by @iot-rocket.### Fixed++- **Step Functions — JSONPath Choice rules read execution context** — `Variable` and supported variable-to-variable comparison paths now resolve `$$.` against the context object, including inside `And`, `Or`, and `Not`. A Choice can check the original execution input after earlier states replace the current input.- **CloudFormation — `AWS::EC2::VPCGatewayAttachment` updates in place** — a changed `InternetGatewayId` or `VpnGatewayId` moves the attachment under the same `IGW|vpc-…` / `VGW|vpc-…` physical id, `VpnGatewayId` is attached at all, and a `VpcId` change leaves the gateway attached to the new VPC, or to the old one when the update rolls back.- **CloudFormation — `AWS::Lambda::Version` publishes through `PublishVersion`** — the version takes its `Description`, a version of a function unchanged since its latest version fails with the `AlreadyExists` error AWS reports, `FunctionScalingConfig` on a function without a capacity provider is refused, and a function keeps its `CapacityProviderConfig`. Contributed by @iot-rocket.- **AppConfig — hosted configuration version numbers are never reused** — a version created after a delete, and the replacement CloudFormation makes for a changed `HostedConfigurationVersion`, get the next unused number instead of overwriting the live one, and a `LatestVersionNumber` mismatch reports the AWS message.diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex b37a8051..4e77415e 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -2006,7 +2006,7 @@ def _execute_choice(state_def, raw_input, ctx=None):effective = _apply_input_path(state_def, raw_input)for choice in state_def.get("Choices", []):- if _evaluate_rule(choice, effective):+ if _evaluate_rule(choice, effective, ctx):return _apply_output_path(state_def, effective), choice["Next"]default = state_def.get("Default")@@ -2031,18 +2031,24 @@ def _evaluate_jsonata_choice_rule(rule, raw_input, ctx):return _truthy(condition)-def _evaluate_rule(rule, data):+def _resolve_choice_path(path, data, ctx):+ if path.startswith("$$."):+ return _resolve_ctx_path(path, ctx or {})+ return _resolve_path(path, data)+++def _evaluate_rule(rule, data, ctx=None):if "And" in rule:- return all(_evaluate_rule(r, data) for r in rule["And"])+ return all(_evaluate_rule(r, data, ctx) for r in rule["And"])if "Or" in rule:- return any(_evaluate_rule(r, data) for r in rule["Or"])+ return any(_evaluate_rule(r, data, ctx) for r in rule["Or"])if "Not" in rule:- return not _evaluate_rule(rule["Not"], data)+ return not _evaluate_rule(rule["Not"], data, ctx)variable = rule.get("Variable")if not variable:return False- value = _resolve_path(variable, data)+ value = _resolve_choice_path(variable, data, ctx)# --- type checks ---if "IsPresent" in rule:@@ -2062,7 +2068,7 @@ def _evaluate_rule(rule, data):if "StringEquals" in rule:return value == rule["StringEquals"]if "StringEqualsPath" in rule:- return value == _resolve_path(rule["StringEqualsPath"], data)+ return value == _resolve_choice_path(rule["StringEqualsPath"], data, ctx)if "StringLessThan" in rule:return isinstance(value, str) and value < rule["StringLessThan"]if "StringGreaterThan" in rule:@@ -2079,7 +2085,7 @@ def _evaluate_rule(rule, data):if "NumericEquals" in rule:return _is_num(value) and value == rule["NumericEquals"]if "NumericEqualsPath" in rule:- return _is_num(value) and value == _resolve_path(rule["NumericEqualsPath"], data)+ return _is_num(value) and value == _resolve_choice_path(rule["NumericEqualsPath"], data, ctx)if "NumericLessThan" in rule:return _is_num(value) and value < rule["NumericLessThan"]if "NumericGreaterThan" in rule:@@ -2089,23 +2095,23 @@ def _evaluate_rule(rule, data):if "NumericGreaterThanEquals" in rule:return _is_num(value) and value >= rule["NumericGreaterThanEquals"]if "NumericLessThanPath" in rule:- rhs = _resolve_path(rule["NumericLessThanPath"], data)+ rhs = _resolve_choice_path(rule["NumericLessThanPath"], data, ctx)return _is_num(value) and _is_num(rhs) and value < rhsif "NumericGreaterThanPath" in rule:- rhs = _resolve_path(rule["NumericGreaterThanPath"], data)+ rhs = _resolve_choice_path(rule["NumericGreaterThanPath"], data, ctx)return _is_num(value) and _is_num(rhs) and value > rhsif "NumericLessThanEqualsPath" in rule:- rhs = _resolve_path(rule["NumericLessThanEqualsPath"], data)+ rhs = _resolve_choice_path(rule["NumericLessThanEqualsPath"], data, ctx)return _is_num(value) and _is_num(rhs) and value <= rhsif "NumericGreaterThanEqualsPath" in rule:- rhs = _resolve_path(rule["NumericGreaterThanEqualsPath"], data)+ rhs = _resolve_choice_path(rule["NumericGreaterThanEqualsPath"], data, ctx)return _is_num(value) and _is_num(rhs) and value >= rhs# --- boolean ---if "BooleanEquals" in rule:return value is rule["BooleanEquals"] or value == rule["BooleanEquals"]if "BooleanEqualsPath" in rule:- return value == _resolve_path(rule["BooleanEqualsPath"], data)+ return value == _resolve_choice_path(rule["BooleanEqualsPath"], data, ctx)# --- timestamp ---for op, cmp_fn in [("TimestampEquals", lambda a, b: a == b),diff --git a/tests/test_stepfunctions_choice_context.py b/tests/test_stepfunctions_choice_context.pynew file mode 100644index 00000000..b89665bb--- /dev/null+++ b/tests/test_stepfunctions_choice_context.py@@ -0,0 +1,84 @@+import json+import time+import uuid++import pytest++from ministack.services import stepfunctions+++ 'rule',+ [+ {'Variable': '$$.Execution.Input.marker', 'IsPresent': True},+ {'Variable': '$$.Execution.Input.missing', 'IsPresent': False},+ {'Variable': '$$.Execution.Input.marker', 'StringEquals': 'keep'},+ {'And': [+ {'Variable': '$$.Execution.Input.marker', 'IsPresent': True},+ {'Or': [+ {'Variable': '$.marker', 'StringEquals': 'wrong'},+ {'Not': {'Variable': '$$.Execution.Input.marker', 'StringEquals': 'wrong'}},+ ]},+ ]},+ {'Variable': '$.marker', 'StringEqualsPath': '$$.Execution.Input.marker'},+ {'Variable': '$$.Execution.Input.marker', 'StringEqualsPath': '$.marker'},+ {'Variable': '$$.Execution.Input.marker', 'StringEqualsPath': '$$.Execution.Input.marker'},+ {'Variable': '$.number', 'NumericEqualsPath': '$$.Execution.Input.number'},+ {'Variable': '$.number', 'NumericLessThanPath': '$$.Execution.Input.higher'},+ {'Variable': '$.number', 'NumericGreaterThanPath': '$$.Execution.Input.lower'},+ {'Variable': '$.number', 'NumericLessThanEqualsPath': '$$.Execution.Input.number'},+ {'Variable': '$.number', 'NumericGreaterThanEqualsPath': '$$.Execution.Input.number'},+ {'Variable': '$.enabled', 'BooleanEqualsPath': '$$.Execution.Input.enabled'},+ ],+)+def test_choice_context_rules(rule):+ data = {'marker': 'keep', 'number': 5, 'enabled': True}+ ctx = {'Execution': {'Input': {**data, 'lower': 4, 'higher': 6}}}+ assert stepfunctions._evaluate_rule(rule, data, ctx)+ assert stepfunctions._execute_choice(+ {'InputPath': '$.projected', 'Choices': [{**rule, 'Next': 'Match'}], 'Default': 'Miss'},+ {'projected': data, 'marker': 'wrong', 'number': 0, 'enabled': False},+ ctx,+ ) == (data, 'Match')+++def test_choice_context_missing_and_data_paths():+ assert not stepfunctions._evaluate_rule({'Variable': '$$.Execution.Id', 'IsPresent': True}, {})+ assert stepfunctions._evaluate_rule({'Variable': '$.value', 'NumericEqualsPath': '$.other'},+ {'value': 5, 'other': 5})+ assert not stepfunctions._evaluate_rule({'Variable': '$$.Execution.Input.marker', 'StringEquals': 'wrong'},+ {}, {'Execution': {'Input': {'marker': 'keep'}}})+++def test_choice_context_survives_input_replacement(sfn):+ definition = {+ 'StartAt': 'Replace',+ 'States': {+ 'Replace': {'Type': 'Pass', 'Result': {'projected': {'marker': 'keep'}}, 'Next': 'Check'},+ 'Check': {+ 'Type': 'Choice', 'InputPath': '$.projected',+ 'Choices': [{'And': [+ {'Variable': '$$.Execution.Input.marker', 'IsPresent': True},+ {'Variable': '$.marker', 'StringEqualsPath': '$$.Execution.Input.marker'},+ {'Variable': '$$.State.Name', 'StringEquals': 'Check'},+ ], 'Next': 'Match'}],+ 'Default': 'Miss',+ },+ 'Match': {'Type': 'Succeed'},+ 'Miss': {'Type': 'Fail', 'Error': 'ContextNotResolved'},+ },+ }+ arn = sfn.create_state_machine(name=f'choice-context-{uuid.uuid4().hex}',+ definition=json.dumps(definition),+ roleArn='arn:aws:iam::000000000000:role/R')['stateMachineArn']+ try:+ execution = sfn.start_execution(stateMachineArn=arn, input=json.dumps({'marker': 'keep'}))['executionArn']+ for _ in range(100):+ result = sfn.describe_execution(executionArn=execution)+ if result['status'] != 'RUNNING':+ break+ time.sleep(0.1)+ assert result['status'] == 'SUCCEEDED', result+ assert json.loads(result['output']) == {'marker': 'keep'}+ finally:+ sfn.delete_state_machine(stateMachineArn=arn)