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): list executions most recent first, paged by cursor (#2166) (#2202)
Lucasbd9b9b2a9fb5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e24e5a23..fec54677 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **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.### Fixed+- **Step Functions — `ListExecutions` order and pagination** — executions came back oldest first, so `maxResults=1` returned the oldest, and `nextToken` was an offset; they now come back most recent first (running executions by `startDate`, the rest by `stopDate`), the token resumes after the last execution returned so one started between pages is not repeated, an unreadable token answers `InvalidToken` and `maxResults=0` uses the default, as on AWS.- **Cognito — confirmation codes are checked under `AUTH=true`** — `ConfirmSignUp` and `ConfirmForgotPassword` accepted any code, and `ConfirmForgotPassword` changed the password even when no reset was requested; with `AUTH=true` they take only the issued code (`123456` for sign-up and `654321` for a password reset, as before), answer a wrong one with `CodeMismatchException` and a code that was never issued with `ExpiredCodeException`, and `ConfirmSignUp` refuses a user who is not `UNCONFIRMED` with `NotAuthorizedException`, as AWS does. Contributed by @iot-rocket.- **Cognito — `ExplicitAuthFlows` is enforced for the password flows under `AUTH=true`** — with `AUTH=true` a client that lists its auth flows now refuses `USER_PASSWORD_AUTH`, `ADMIN_USER_PASSWORD_AUTH` and `ADMIN_NO_SRP_AUTH` unless the list enables them (the legacy `USER_PASSWORD_AUTH` and `ADMIN_NO_SRP_AUTH` names included), with the `InvalidParameterException` AWS returns. Contributed by @iot-rocket.- **Cognito — `CUSTOM_AUTH` on clients without `ALLOW_` flows** — a client created without `ExplicitAuthFlows`, or with only the legacy names, refused `CUSTOM_AUTH`; it is now enabled, as on AWS, and a client whose `ALLOW_` list leaves it out answers `CUSTOM_AUTH is not enabled for the client.` as AWS does. Contributed by @iot-rocket.diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex 77ee80ff..dfcd9f23 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -749,7 +749,35 @@ def _describe_execution(data):return json_response(result)+def _execution_sort_key(execution):+ """AWS lists the most recent execution first: a running one by its+ startDate, the rest by stopDate. The ARN breaks ties, so the order is+ total and a token can resume it."""+ return (execution["stopDate"] or execution["startDate"], execution["executionArn"])+++def _encode_execution_token(execution):+ """Tokens carry the sort position of the last execution returned, not an+ index, as AWS's do: with an offset, an execution started between pages+ would repeat one."""+ raw = json.dumps(list(_execution_sort_key(execution))).encode("utf-8")+ return base64.urlsafe_b64encode(raw).decode("ascii")+++def _decode_execution_token(token):+ try:+ moment, arn = json.loads(base64.urlsafe_b64decode(token.encode("ascii")))+ return (str(moment), str(arn))+ except Exception:+ return None++def _list_executions(data):+ cursor = None+ if data.get("nextToken"):+ cursor = _decode_execution_token(data["nextToken"])+ if cursor is None:+ return error_response_json("InvalidToken", "Invalid Token: 'Invalid token'", 400)sm_arn = data.get("stateMachineArn")status_filter = data.get("statusFilter")all_execs = []@@ -766,18 +794,14 @@ def _list_executions(data):"startDate": ex["startDate"],"stopDate": ex.get("stopDate"),})- max_results = int(data.get("maxResults", 1000))- next_token = data.get("nextToken")- start = 0- if next_token:- try:- start = int(next_token)- except ValueError:- start = 0- page = all_execs[start:start + max_results]+ all_execs.sort(key=_execution_sort_key, reverse=True)+ if cursor is not None:+ all_execs = [e for e in all_execs if _execution_sort_key(e) < cursor]+ max_results = int(data.get("maxResults") or 1000)+ page = all_execs[:max_results]resp = {"executions": page}- if start + max_results < len(all_execs):- resp["nextToken"] = str(start + max_results)+ if len(all_execs) > max_results:+ resp["nextToken"] = _encode_execution_token(page[-1])return json_response(resp)diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex fac4465c..8b939eed 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -4698,6 +4698,62 @@ def test_sfn_list_executions_filter(sfn):succeeded = sfn.list_executions(stateMachineArn=arn, statusFilter="SUCCEEDED")["executions"]assert all(e["status"] == "SUCCEEDED" for e in succeeded)++_WAIT_AN_HOUR = {"Wait": {"Type": "Wait", "Seconds": 3600, "End": True}}+++def test_sfn_list_executions_most_recent_first(sfn):+ """Running executions sort by startDate and the rest by stopDate, in one+ ordering, most recent first. The timeline and answers are what AWS gave."""+ with _machine(sfn, "Wait", _WAIT_AN_HOUR) as arn:+ prefix = arn.replace(":stateMachine:", ":execution:")++ def listed(**kwargs):+ executions = sfn.list_executions(stateMachineArn=arn, **kwargs)["executions"]+ return [e["name"] for e in executions]++ for name in ("x", "y", "w"):+ sfn.start_execution(stateMachineArn=arn, name=name)+ time.sleep(0.01)+ assert listed(statusFilter="RUNNING") == ["w", "y", "x"]++ sfn.stop_execution(executionArn=f"{prefix}:y")+ time.sleep(0.01)+ sfn.start_execution(stateMachineArn=arn, name="z")+ time.sleep(0.01)+ sfn.stop_execution(executionArn=f"{prefix}:x")++ assert listed(statusFilter="ABORTED") == ["x", "y"]+ assert listed() == ["x", "z", "y", "w"]+++def test_sfn_list_executions_token_resumes_after_last_execution(sfn):+ """The token resumes after the last execution returned, so one started+ between pages is not repeated."""+ with _machine(sfn, "Wait", _WAIT_AN_HOUR) as arn:+ for name in ("a", "b", "c"):+ sfn.start_execution(stateMachineArn=arn, name=name)+ time.sleep(0.01)++ first = sfn.list_executions(stateMachineArn=arn, maxResults=1)+ assert [e["name"] for e in first["executions"]] == ["c"]+ sfn.start_execution(stateMachineArn=arn, name="d")+ second = sfn.list_executions(+ stateMachineArn=arn, maxResults=1, nextToken=first["nextToken"])+ assert [e["name"] for e in second["executions"]] == ["b"]+ third = sfn.list_executions(+ stateMachineArn=arn, maxResults=1, nextToken=second["nextToken"])+ assert [e["name"] for e in third["executions"]] == ["a"]+ assert "nextToken" not in third++ everything = sfn.list_executions(stateMachineArn=arn, maxResults=0)+ assert [e["name"] for e in everything["executions"]] == ["d", "c", "b", "a"]+ assert "nextToken" not in everything++ with pytest.raises(ClientError) as exc:+ sfn.list_executions(stateMachineArn=arn, nextToken="not-a-token")+ assert exc.value.response["Error"]["Code"] == "InvalidToken"+def test_sfn_timestamp_fields_are_sdk_compatible(sfn, sfn_sync):"""SFN timestamp fields must deserialize as datetimes, not fail as strings."""import datetime