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
feat: SFN TestState API + mock config, critical runtime fixes, security hardening, 851 tests (v1.1.22) (#80)
Nahuel Nucera7c48d9078592
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8e965310..433f987c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,28 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.1.22] — 2026-04-03++### Added+- **Step Functions mock config** — `SFN_MOCK_CONFIG` (or `LOCALSTACK_SFN_MOCK_CONFIG`) env var pointing to a JSON file that mocks Task state responses; fully compatible with the AWS Step Functions Local mock config format: `MockedResponses` with invocation indexing (`"0"`, `"1-2"`, etc.), `#TestCaseName` ARN suffix on `StartExecution`, `Return` and `Throw` per attempt. Contributed by @maxence-leblanc (issue)+- **Step Functions `TestState` API** — execute a single state in isolation without creating a state machine; supports Pass, Task, Choice, Wait, Succeed, Fail state types; `inspectionLevel` (INFO/DEBUG) returns data transformation details; `mock` parameter for Task states with `result`/`errorOutput`; `stateName` to extract a state from a full definition; Retry/Catch evaluation with `RETRIABLE`/`CAUGHT_ERROR` status++### Fixed+- **CloudWatch Logs `GetLogEvents` pagination** — `nextForwardToken` and `nextBackwardToken` now return the caller's token when at end of stream, preventing SDK clients from looping infinitely; token-based offset pagination now works correctly+- **EventBridge → Lambda crash** — `asyncio.run()` inside the running event loop replaced with direct synchronous dispatch; PutEvents with Lambda targets no longer crashes+- **Step Functions StartSyncExecution crash** — `_call_lambda` replaced `asyncio.run()` with direct `_execute_function()` call; sync Lambda Task states no longer crash+- **`/_ministack/config` endpoint hardened** — now whitelists allowed config keys instead of accepting arbitrary `__import__` + `setattr` on any module+- **S3 path traversal in persistence** — `_persist_object` validates paths stay within `DATA_DIR` using `os.path.realpath()` prefix check; blocks `../` in S3 keys+- **Lambda worker reset** — `reset()` now acquires lock and calls `worker.kill()` (cleans up temp dirs) instead of bare `_proc.terminate()`+- **DynamoDB `_stream_records` cleared on reset** — stream records no longer accumulate unboundedly across resets+- **Lambda ESM position tracking cleared on reset** — `_kinesis_positions` and `_dynamodb_stream_positions` now cleared on `reset()`+- **License** — updated year 2026++### Tests+- 851 tests total, all passing++---+## [1.1.21] — 2026-04-02### Addeddiff --git a/LICENSE b/LICENSEindex 4abfb512..8ae01fd9 100644--- a/LICENSE+++ b/LICENSE@@ -1,6 +1,6 @@MIT License-Copyright (c) 2024 MiniStack Contributors+Copyright (c) 2026 MiniStack ContributorsPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealdiff --git a/README.md b/README.mdindex 5fee6b5f..f6d5deac 100644--- a/README.md+++ b/README.md@@ -220,7 +220,7 @@ subnet = ec2.create_subnet(| **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, GetAccount, PutAccountSuppressionAttributes, ListSuppressedDestinations | REST API (`/v2/email/`); identities auto-verified; emails stored in-memory, not sent || **ACM** | RequestCertificate, DescribeCertificate, ListCertificates, DeleteCertificate, GetCertificate, ImportCertificate, AddTagsToCertificate, RemoveTagsFromCertificate, ListTagsForCertificate, UpdateCertificateOptions, RenewCertificate, ResendValidationEmail | Certificates auto-issued; DNS validation records generated; supports SANs || **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked |-| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel |+| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TestState, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel; TestState API with mock and inspectionLevel support; SFN_MOCK_CONFIG for AWS SFN Local compatible mock testing || **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags | HTTP API (v2) protocol; Lambda proxy (AWS_PROXY) and HTTP proxy (HTTP_PROXY) integrations; data plane via `{apiId}.execute-api.localhost`; `{param}` and `{proxy+}` path matching; JWT/Lambda authorizer CRUD || **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence || **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |@@ -536,20 +536,20 @@ pip install boto3 pytest duckdb docker cbor2# Start MiniStackdocker compose up -d-# Run the full test suite (841 tests across all 34 services)+# Run the full test suite (851 tests across all 34 services)pytest tests/ -v```Expected output:```-collected 841 items+collected 851 itemstests/test_services.py::test_s3_create_bucket PASSED...tests/test_services.py::test_app_asgi_callable PASSED-841 passed in ~100s+851 passed in ~100s```---diff --git a/examples/go-testcontainers/go.mod b/examples/go-testcontainers/go.modindex c2f35ab9..da2289b3 100644--- a/examples/go-testcontainers/go.mod+++ b/examples/go-testcontainers/go.mod@@ -8,14 +8,13 @@ require (github.com/aws/aws-sdk-go-v2/service/dynamodb v1.31.1github.com/aws/aws-sdk-go-v2/service/s3 v1.53.1github.com/aws/aws-sdk-go-v2/service/sqs v1.31.1- github.com/testcontainers/testcontainers-go v0.30.0+ github.com/testcontainers/testcontainers-go v0.34.0)require (dario.cat/mergo v1.0.0 // indirectgithub.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirectgithub.com/Microsoft/go-winio v0.6.2 // indirect- github.com/Microsoft/hcsshim v0.11.7 // indirectgithub.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.2 // indirectgithub.com/aws/aws-sdk-go-v2/internal/configsources v1.3.5 // indirectgithub.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.5 // indirect@@ -30,9 +29,10 @@ require (github.com/containerd/containerd v1.7.29 // indirectgithub.com/containerd/log v0.1.0 // indirectgithub.com/containerd/platforms v0.2.1 // indirect- github.com/cpuguy83/dockercfg v0.3.1 // indirect+ github.com/cpuguy83/dockercfg v0.3.2 // indirect+ github.com/davecgh/go-spew v1.1.1 // indirectgithub.com/distribution/reference v0.6.0 // indirect- github.com/docker/docker v25.0.5+incompatible // indirect+ github.com/docker/docker v27.1.1+incompatible // indirectgithub.com/docker/go-connections v0.5.0 // indirectgithub.com/docker/go-units v0.5.0 // indirectgithub.com/felixge/httpsnoop v1.0.4 // indirect@@ -42,9 +42,11 @@ require (github.com/gogo/protobuf v1.3.2 // indirectgithub.com/google/uuid v1.6.0 // indirectgithub.com/jmespath/go-jmespath v0.4.0 // indirect- github.com/klauspost/compress v1.16.7 // indirect+ github.com/klauspost/compress v1.17.4 // indirect+ github.com/kr/text v0.2.0 // indirectgithub.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirectgithub.com/magiconair/properties v1.8.7 // indirect+ github.com/moby/docker-image-spec v1.3.1 // indirectgithub.com/moby/patternmatcher v0.6.0 // indirectgithub.com/moby/sys/sequential v0.5.0 // indirectgithub.com/moby/sys/user v0.3.0 // indirect@@ -54,10 +56,12 @@ require (github.com/opencontainers/go-digest v1.0.0 // indirectgithub.com/opencontainers/image-spec v1.1.0 // indirectgithub.com/pkg/errors v0.9.1 // indirect+ github.com/pmezard/go-difflib v1.0.0 // indirectgithub.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirectgithub.com/shirou/gopsutil/v3 v3.23.12 // indirectgithub.com/shoenig/go-m1cpu v0.1.6 // indirectgithub.com/sirupsen/logrus v1.9.3 // indirect+ github.com/stretchr/testify v1.9.0 // indirectgithub.com/tklauser/go-sysconf v0.3.12 // indirectgithub.com/tklauser/numcpus v0.6.1 // indirectgithub.com/yusufpapurcu/wmi v1.2.3 // indirect@@ -65,6 +69,7 @@ require (go.opentelemetry.io/otel v1.24.0 // indirectgo.opentelemetry.io/otel/metric v1.24.0 // indirectgo.opentelemetry.io/otel/trace v1.24.0 // indirect- golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea // indirect+ golang.org/x/crypto v0.40.0 // indirectgolang.org/x/sys v0.34.0 // indirect+ gopkg.in/yaml.v3 v3.0.1 // indirect)diff --git a/examples/go-testcontainers/go.sum b/examples/go-testcontainers/go.sumindex 77e529b5..44e56f82 100644--- a/examples/go-testcontainers/go.sum+++ b/examples/go-testcontainers/go.sum@@ -6,8 +6,6 @@ github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElgithub.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=-github.com/Microsoft/hcsshim v0.11.7 h1:vl/nj3Bar/CvJSYo7gIQPyRWc9f3c6IeSNavBTSZNZQ=-github.com/Microsoft/hcsshim v0.11.7/go.mod h1:MV8xMfmECjl5HdO7U/3/hFVnkmSBjAjmA09d4bExKcU=github.com/aws/aws-sdk-go-v2 v1.26.1 h1:5554eUqIYVWpU0YmeeYZ0wU64H2VLBs8TlhRB2L+EkA=github.com/aws/aws-sdk-go-v2 v1.26.1/go.mod h1:ffIFB97e2yNsv4aTSGkqtHnppsIJzw7G7BReUZ3jCXM=github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.2 h1:x6xsQXGSmW6frevwDA+vi/wqhp1ct18mVXYN08/93to=@@ -46,8 +44,9 @@ github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I=github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo=github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A=github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw=-github.com/cpuguy83/dockercfg v0.3.1 h1:/FpZ+JaygUR/lZP2NlFI2DVfrOEMAIKP5wWEJdoYe9E=-github.com/cpuguy83/dockercfg v0.3.1/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=+github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=+github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY=github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=@@ -55,8 +54,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97cgithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=-github.com/docker/docker v25.0.5+incompatible h1:UmQydMduGkrD5nQde1mecF/YnSbTOaPeFIeP5C4W+DE=-github.com/docker/docker v25.0.5+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=+github.com/docker/docker v27.1.1+incompatible h1:hO/M4MtV36kzKldqnA37IWhebRA+LnqqcqDja6kVaKY=+github.com/docker/docker v27.1.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=@@ -72,8 +71,6 @@ github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=-github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=-github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=@@ -88,12 +85,18 @@ github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwgithub.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=-github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I=-github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=+github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=+github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=+github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=+github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=+github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=+github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=github.com/moby/patternmatcher v0.6.0 h1:GmP9lR19aU5GqSSFko+5pRqHi+Ohk1O69aFiKkVGiPk=github.com/moby/patternmatcher v0.6.0/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=github.com/moby/sys/sequential v0.5.0 h1:OPvI35Lzn9K04PBbCLW0g4LcFAJgHsvXsRyewg5lXtc=@@ -116,6 +119,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbgithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=+github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg=+github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o=github.com/shirou/gopsutil/v3 v3.23.12 h1:z90NtUkp3bMtmICZKpC4+WaknU1eXtp5vtbQ11DgpE4=github.com/shirou/gopsutil/v3 v3.23.12/go.mod h1:1FrWgea594Jp7qmjHUUPlJDTPgcsb9mGnXDxavtikzM=github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=@@ -127,14 +132,16 @@ github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsgithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=+github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=-github.com/testcontainers/testcontainers-go v0.30.0 h1:jmn/XS22q4YRrcMwWg0pAwlClzs/abopbsBzrepyc4E=-github.com/testcontainers/testcontainers-go v0.30.0/go.mod h1:K+kHNGiM5zjklKjgTtcrEetF3uhWbMUyqAQoyoh8Pf0=+github.com/testcontainers/testcontainers-go v0.34.0 h1:5fbgF0vIN5u+nD3IWabQwRybuB4GY8G2HHgCkbMzMHo=+github.com/testcontainers/testcontainers-go v0.34.0/go.mod h1:6P/kMkQe8yqPHfPWNulFGdFHTD8HB2vLq/231xY2iPQ=github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=@@ -162,8 +169,8 @@ go.opentelemetry.io/proto/otlp v1.0.0/go.mod h1:Sy6pihPLfYHkr3NkUbEhGHFhINUSI/v8golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=-golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea h1:vLCWI/yYrdEHyN2JzIzPO3aaQJHQdp89IZBA/+azVC4=-golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=+golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=+golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=@@ -187,6 +194,8 @@ golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=+golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=+golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=@@ -206,16 +215,18 @@ google.golang.org/genproto/googleapis/api v0.0.0-20231120223509-83a465c0220f h1:google.golang.org/genproto/googleapis/api v0.0.0-20231120223509-83a465c0220f/go.mod h1:Uy9bTZJqmfrw2rIBxgGLnamc78euZULUBrLZ9XTITKI=google.golang.org/genproto/googleapis/rpc v0.0.0-20240401170217-c3f982113cda h1:LI5DOvAxUPMv/50agcLLoo+AdWc1irS9Rzz4vPuD1V4=google.golang.org/genproto/googleapis/rpc v0.0.0-20240401170217-c3f982113cda/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY=-google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk=-google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98=+google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA=+google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0=google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io=google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=-gotest.tools/v3 v3.5.0 h1:Ljk6PdHdOhAb5aDMWXjDLMMhph+BpztA4v1QdqEW2eY=-gotest.tools/v3 v3.5.0/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU=+gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU=+gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU=diff --git a/ministack/app.py b/ministack/app.pyindex dd4f85ee..1cb573c0 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -235,13 +235,20 @@ async def app(scope, receive, send):returnif path == "/_ministack/config" and method == "POST":+ _ALLOWED_CONFIG_KEYS = {+ "athena.ATHENA_ENGINE", "athena.ATHENA_DATA_DIR",+ "stepfunctions._sfn_mock_config",+ "lambda_svc.LAMBDA_EXECUTOR",+ }try:config = json.loads(body) if body else {}except json.JSONDecodeError:config = {}applied = {}for key, value in config.items():- # Set module-level variables on service modules: "athena.ATHENA_ENGINE" -> "sqlite"+ if key not in _ALLOWED_CONFIG_KEYS:+ logger.warning("/_ministack/config: rejected key %s (not in whitelist)", key)+ continueif "." in key:mod_name, var_name = key.rsplit(".", 1)try:diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.pyindex 40c99fe6..09a95886 100644--- a/ministack/core/lambda_runtime.py+++ b/ministack/core/lambda_runtime.py@@ -427,10 +427,8 @@ def invalidate_worker(func_name: str):def reset():- """Terminate all warm workers and clear the pool."""- for worker in list(_workers.values()):- try:- worker._proc.terminate()- except Exception:- pass- _workers.clear()+ """Terminate all warm workers, clean up temp dirs, and clear the pool."""+ with _lock:+ for worker in list(_workers.values()):+ worker.kill()+ _workers.clear()diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.pyindex d41b8788..4d2f425e 100644--- a/ministack/services/cloudwatch_logs.py+++ b/ministack/services/cloudwatch_logs.py@@ -362,6 +362,7 @@ def _get_log_events(data):start_from_head = data.get("startFromHead", False)start_time = data.get("startTime")end_time = data.get("endTime")+ next_token = data.get("nextToken")if group not in _log_groups:return error_response_json(@@ -382,15 +383,34 @@ def _get_log_events(data):if end_time is not None:filtered = [e for e in filtered if e["timestamp"] <= end_time]- if start_from_head:- page = filtered[:limit]+ # Parse offset from token: f/<offset> for forward, b/<offset> for backward+ offset = 0+ if next_token:+ try:+ offset = int(next_token.split("/", 1)[1])+ except (IndexError, ValueError):+ offset = 0++ if start_from_head or (next_token and next_token.startswith("f/")):+ page = filtered[offset:offset + limit]+ new_forward = f"f/{offset + len(page)}"+ new_backward = f"b/{offset}"else:- page = filtered[-limit:]+ end = len(filtered) - offset if next_token and next_token.startswith("b/") else len(filtered)+ start = max(0, end - limit)+ page = filtered[start:end]+ new_forward = f"f/{end}"+ new_backward = f"b/{len(filtered) - start}"++ # AWS behaviour: when at end of stream, return the caller's token+ # so SDK clients stop paginating+ forward_token = next_token if (next_token and len(page) < limit) else new_forward+ backward_token = next_token if (next_token and offset == 0 and next_token.startswith("b/")) else new_backwardreturn json_response({"events": page,- "nextForwardToken": f"f/{len(all_events)}",- "nextBackwardToken": "b/0",+ "nextForwardToken": forward_token,+ "nextBackwardToken": backward_token,})diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex 64aaa958..5d8b38ab 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -1807,3 +1807,4 @@ def reset():_tags.clear()_ttl_settings.clear()_pitr_settings.clear()+ _stream_records.clear()diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.pyindex 00b52a18..f02c58d6 100644--- a/ministack/services/eventbridge.py+++ b/ministack/services/eventbridge.py@@ -13,12 +13,12 @@ Supports: CreateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus,ListApiDestinations, UpdateApiDestination."""-import asyncio-import osimport hashlibimport jsonimport logging+import osimport re+import threadingimport timefrom datetime import datetime, timezone@@ -606,9 +606,14 @@ def _dispatch_to_lambda(arn, payload):except (json.JSONDecodeError, TypeError):event = {"body": payload}- headers = {"x-amz-invocation-type": "Event"}- result = asyncio.run(lambda_svc._invoke(func_name, event, headers))- logger.info(f"EventBridge → Lambda {func_name}: status={result[0] if result else 'unknown'}")+ func = lambda_svc._functions.get(func_name)+ if not func:+ logger.warning(f"EventBridge → Lambda: function {func_name} not found")+ return+ threading.Thread(+ target=lambda_svc._execute_function, args=(func, event), daemon=True+ ).start()+ logger.info(f"EventBridge → Lambda {func_name}: dispatched")def _dispatch_to_sqs(arn, payload):diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 7d56eb69..c11c9dd5 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -2538,4 +2538,6 @@ def reset():_layers.clear()_esms.clear()_function_urls.clear()+ _kinesis_positions.clear()+ _dynamodb_stream_positions.clear()lambda_runtime.reset()diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 83e1217c..17a5980b 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -2643,7 +2643,10 @@ def _list_parts(bucket_name: str, key: str, query_params: dict):def _persist_object(bucket: str, key: str, obj):try:- fpath = os.path.join(DATA_DIR, bucket, key)+ fpath = os.path.realpath(os.path.join(DATA_DIR, bucket, key))+ if not fpath.startswith(os.path.realpath(DATA_DIR)):+ logger.warning("S3 persist: path traversal blocked for %s/%s", bucket, key)+ returnos.makedirs(os.path.dirname(fpath), exist_ok=True)data = obj["body"] if isinstance(obj, dict) else objwith open(fpath, "wb") as f:diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex 7c46600d..43ee43ef 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -42,6 +42,54 @@ logger = logging.getLogger("states")ACCOUNT_ID = "000000000000"REGION = os.environ.get("MINISTACK_REGION", "us-east-1")+# SFN mock config — compatible with LocalStack's SFN_MOCK_CONFIG / LOCALSTACK_SFN_MOCK_CONFIG+_sfn_mock_config: dict = {}+_sfn_mock_config_path = (+ os.environ.get("SFN_MOCK_CONFIG")+ or os.environ.get("LOCALSTACK_SFN_MOCK_CONFIG")+ or ""+)+if _sfn_mock_config_path:+ try:+ with open(_sfn_mock_config_path) as f:+ _sfn_mock_config = json.load(f)+ logger.info("SFN mock config loaded from %s", _sfn_mock_config_path)+ except Exception as e:+ logger.warning("Failed to load SFN mock config from %s: %s", _sfn_mock_config_path, e)+++def _get_mock_response(sm_name: str, test_case: str, state_name: str, attempt: int) -> dict | None:+ """Look up a mock response for a state using the AWS SFN Local mock config format.++ Format: StateMachines.<SM>.TestCases.<TC>.<State> -> response name+ MockedResponses.<name>.<attempt> -> {Return: ...} or {Throw: ...}+ Attempt keys can be "0", "1", "1-3", etc.+ """+ sm_cfg = _sfn_mock_config.get("StateMachines", {}).get(sm_name, {})+ if not test_case or not sm_cfg:+ return None+ tc = sm_cfg.get("TestCases", {}).get(test_case, {})+ response_name = tc.get(state_name)+ if not response_name:+ return None+ mocked = _sfn_mock_config.get("MockedResponses", {}).get(response_name, {})+ if not mocked:+ return None+ # Match attempt: exact ("0") or range ("1-3")+ str_attempt = str(attempt)+ if str_attempt in mocked:+ return mocked[str_attempt]+ for key, val in mocked.items():+ if "-" in key:+ parts = key.split("-", 1)+ try:+ lo, hi = int(parts[0]), int(parts[1])+ if lo <= attempt <= hi:+ return val+ except ValueError:+ continue+ return None+_state_machines: dict = {}_executions: dict = {}_task_tokens: dict = {}@@ -87,6 +135,7 @@ async def handle_request(method, path, headers, body, query_params):"DescribeActivity": _describe_activity,"ListActivities": _list_activities,"GetActivityTask": _get_activity_task,+ "TestState": _test_state,}handler = handlers.get(action)@@ -185,7 +234,13 @@ def _list_state_machines(data):# ---------------------------------------------------------------------------def _start_execution(data):- sm_arn = data.get("stateMachineArn")+ sm_arn_raw = data.get("stateMachineArn", "")+ # Support #TestCaseName suffix for mock config+ test_case = ""+ if "#" in sm_arn_raw:+ sm_arn, test_case = sm_arn_raw.rsplit("#", 1)+ else:+ sm_arn = sm_arn_rawif sm_arn not in _state_machines:return error_response_json("StateMachineDoesNotExist",@@ -210,6 +265,8 @@ def _start_execution(data):"inputDetails": {"included": True},"output": None,"outputDetails": {"included": True},+ "testCase": test_case,+ "mockAttempts": {},"events": [{"id": 1, "type": "ExecutionStarted", "timestamp": start_date,"executionStartedEventDetails": {@@ -304,7 +361,12 @@ def _get_execution_history(data):def _start_sync_execution(data):- sm_arn = data.get("stateMachineArn")+ sm_arn_raw = data.get("stateMachineArn", "")+ test_case = ""+ if "#" in sm_arn_raw:+ sm_arn, test_case = sm_arn_raw.rsplit("#", 1)+ else:+ sm_arn = sm_arn_rawif sm_arn not in _state_machines:return error_response_json("StateMachineDoesNotExist",@@ -329,6 +391,8 @@ def _start_sync_execution(data):"inputDetails": {"included": True},"output": None,"outputDetails": {"included": True},+ "testCase": test_case,+ "mockAttempts": {},"events": [{"id": 1, "type": "ExecutionStarted", "timestamp": start_date,"executionStartedEventDetails": {@@ -535,6 +599,220 @@ def _add_event(execution, event_type, details=None):return event+# ---------------------------------------------------------------------------+# TestState API+# ---------------------------------------------------------------------------++def _test_state(data):+ """Execute a single state in isolation — AWS TestState API."""+ definition_str = data.get("definition")+ if not definition_str:+ return error_response_json("InvalidDefinition", "definition is required", 400)++ try:+ definition = json.loads(definition_str) if isinstance(definition_str, str) else definition_str+ except json.JSONDecodeError:+ return error_response_json("InvalidDefinition", "Invalid JSON in definition", 400)++ input_str = data.get("input", "{}")+ try:+ input_data = json.loads(input_str) if isinstance(input_str, str) else input_str+ except json.JSONDecodeError:+ return error_response_json("InvalidExecutionInput", "Invalid JSON in input", 400)++ inspection_level = data.get("inspectionLevel", "INFO")+ state_name = data.get("stateName")+ mock_raw = data.get("mock")+ if isinstance(mock_raw, str):+ try:+ mock = json.loads(mock_raw)+ except json.JSONDecodeError:+ mock = None+ else:+ mock = mock_raw++ # If definition has States (full SM definition), extract the target state+ if "States" in definition:+ if not state_name:+ state_name = definition.get("StartAt")+ states = definition.get("States", {})+ if state_name not in states:+ return error_response_json("InvalidDefinition",+ f"State '{state_name}' not found in definition", 400)+ state_def = states[state_name]+ else:+ # Single state definition+ state_def = definition+ if not state_name:+ state_name = "TestState"++ state_type = state_def.get("Type")+ if not state_type:+ return error_response_json("InvalidDefinition", "State must have a Type", 400)++ # Build context+ user_ctx = data.get("context")+ if user_ctx:+ try:+ ctx = json.loads(user_ctx) if isinstance(user_ctx, str) else user_ctx+ except json.JSONDecodeError:+ ctx = {}+ else:+ ctx = {}+ ctx.setdefault("Execution", {"Id": f"arn:aws:states:{REGION}:{ACCOUNT_ID}:execution:test:{new_uuid()}", "Name": "test", "StartTime": now_iso()})+ ctx.setdefault("StateMachine", {"Id": "test", "Name": "test"})+ ctx["State"] = {"Name": state_name, "EnteredTime": now_iso()}++ inspection_data = {}+ if inspection_level in ("DEBUG", "TRACE"):+ inspection_data["input"] = json.dumps(input_data)++ result = {}+ try:+ if state_type == "Pass":+ output, next_state = _execute_pass(state_def, input_data)+ result = {"status": "SUCCEEDED", "output": json.dumps(output)}+ if next_state:+ result["nextState"] = next_state++ elif state_type == "Choice":+ output, next_state = _execute_choice(state_def, input_data)+ result = {"status": "SUCCEEDED", "output": json.dumps(output)}+ if next_state:+ result["nextState"] = next_state++ elif state_type == "Wait":+ output, next_state = _execute_wait(state_def, input_data)+ result = {"status": "SUCCEEDED", "output": json.dumps(output)}+ if next_state:+ result["nextState"] = next_state++ elif state_type == "Succeed":+ output = _apply_input_path(state_def, input_data)+ output = _apply_output_path(state_def, output)+ result = {"status": "SUCCEEDED", "output": json.dumps(output)}++ elif state_type == "Fail":+ result = {+ "status": "FAILED",+ "error": state_def.get("Error", "States.Fail"),+ "cause": state_def.get("Cause", ""),+ }++ elif state_type == "Task":+ effective = _apply_input_path(state_def, input_data)+ effective = _apply_parameters(state_def, effective, ctx)++ if inspection_level in ("DEBUG", "TRACE"):+ inspection_data["afterInputPath"] = json.dumps(_apply_input_path(state_def, input_data))+ inspection_data["afterParameters"] = json.dumps(effective)++ # Mock support+ if mock:+ if "errorOutput" in mock:+ err = mock["errorOutput"]+ error_code = err.get("error", "MockError")+ cause = err.get("cause", "Mocked failure")+ # Check Catch+ catchers = state_def.get("Catch", [])+ catcher = _find_matching_catcher(catchers, error_code)+ if catcher:+ error_output = {"Error": error_code, "Cause": cause}+ output = _apply_result_path_raw(+ catcher.get("ResultPath", "$"), input_data, error_output)+ result = {+ "status": "CAUGHT_ERROR",+ "output": json.dumps(output),+ "error": error_code,+ "cause": cause,+ "nextState": catcher["Next"],+ }+ else:+ # Check Retry+ retriers = state_def.get("Retry", [])+ retrier, _ = _find_matching_retrier(retriers, error_code, {})+ if retrier is not None:+ retry_config = data.get("stateConfiguration", {})+ retry_count = retry_config.get("retrierRetryCount", 0)+ max_attempts = retrier.get("MaxAttempts", 3)+ if retry_count < max_attempts:+ interval = retrier.get("IntervalSeconds", 1)+ backoff = retrier.get("BackoffRate", 2.0)+ result = {+ "status": "RETRIABLE",+ "error": error_code,+ "cause": cause,+ }+ if inspection_level in ("DEBUG", "TRACE"):+ inspection_data["errorDetails"] = {+ "retryBackoffIntervalSeconds": interval * (backoff ** retry_count),+ "retryIndex": 0,+ }+ else:+ result = {"status": "FAILED", "error": error_code, "cause": cause}+ else:+ result = {"status": "FAILED", "error": error_code, "cause": cause}+ elif "result" in mock:+ try:+ mock_result = json.loads(mock["result"]) if isinstance(mock["result"], str) else mock["result"]+ except json.JSONDecodeError:+ mock_result = mock["result"]+ task_result = _apply_result_selector(state_def, mock_result)+ output = _apply_result_path(state_def, input_data, task_result)+ output = _apply_output_path(state_def, output)+ result = {"status": "SUCCEEDED", "output": json.dumps(output)}+ next_state = _next_or_end(state_def)+ if next_state:+ result["nextState"] = next_state+ else:+ # Real execution+ resource = state_def.get("Resource", "")+ try:+ task_result = _invoke_resource(resource, effective)+ task_result = _apply_result_selector(state_def, task_result)++ if inspection_level in ("DEBUG", "TRACE"):+ inspection_data["result"] = json.dumps(task_result)+ inspection_data["afterResultSelector"] = json.dumps(task_result)++ output = _apply_result_path(state_def, input_data, task_result)++ if inspection_level in ("DEBUG", "TRACE"):+ inspection_data["afterResultPath"] = json.dumps(output)++ output = _apply_output_path(state_def, output)+ result = {"status": "SUCCEEDED", "output": json.dumps(output)}+ next_state = _next_or_end(state_def)+ if next_state:+ result["nextState"] = next_state+ except _ExecutionError as err:+ catchers = state_def.get("Catch", [])+ catcher = _find_matching_catcher(catchers, err.error)+ if catcher:+ error_output = {"Error": err.error, "Cause": err.cause}+ output = _apply_result_path_raw(+ catcher.get("ResultPath", "$"), input_data, error_output)+ result = {+ "status": "CAUGHT_ERROR",+ "output": json.dumps(output),+ "error": err.error,+ "cause": err.cause,+ "nextState": catcher["Next"],+ }+ else:+ result = {"status": "FAILED", "error": err.error, "cause": err.cause}+ else:+ return error_response_json("InvalidDefinition", f"Unsupported state type: {state_type}", 400)++ except _ExecutionError as err:+ result = {"status": "FAILED", "error": err.error, "cause": err.cause}++ if inspection_level in ("DEBUG", "TRACE") and inspection_data:+ result["inspectionData"] = inspection_data++ return json_response(result)++# ===================================================================# ASL Execution Engine# ===================================================================@@ -703,6 +981,26 @@ def _execute_task(state_def, raw_input, execution, ctx):resource = state_def.get("Resource", "")is_callback = ".waitForTaskToken" in resource+ # SFN mock config — return canned response if configured (AWS SFN Local format)+ if _sfn_mock_config and execution:+ test_case = execution.get("testCase", "")+ sm_name = ctx.get("StateMachine", {}).get("Name", "")+ state_name = ctx.get("State", {}).get("Name", "")+ attempts = execution.get("mockAttempts", {})+ attempt = attempts.get(state_name, 0)+ mock = _get_mock_response(sm_name, test_case, state_name, attempt)+ if mock is not None:+ attempts[state_name] = attempt + 1+ if "Throw" in mock:+ raise _ExecutionError(+ mock["Throw"].get("Error", "MockError"),+ mock["Throw"].get("Cause", "Mocked failure"))+ mock_result = mock.get("Return", {})+ result = _apply_result_selector(state_def, mock_result)+ output = _apply_result_path(state_def, raw_input, result)+ output = _apply_output_path(state_def, output)+ return output, _next_or_end(state_def)+if is_callback:ctx["Task"] = {"Token": new_uuid()}@@ -871,32 +1169,38 @@ def _invoke_with_callback(resource, input_data, token, state_def):def _call_lambda(func_name, event):- """Invoke a Lambda via the co-located lambda_svc module."""+ """Invoke a Lambda via the co-located lambda_svc module (synchronous)."""try:from ministack.services import lambda_svcexcept ImportError:logger.warning("lambda_svc unavailable; returning passthrough for %s", func_name)return event- status, headers, body = asyncio.run(lambda_svc._invoke(func_name, event, {}))+ func = lambda_svc._functions.get(func_name)+ if not func:+ raise _ExecutionError(+ "Lambda.ResourceNotFoundException",+ f"Function not found: {func_name}")- if headers.get("X-Amz-Function-Error"):- try:- err = json.loads(body)- raise _ExecutionError(- err.get("errorType", "Lambda.Unknown"),- err.get("errorMessage", body.decode("utf-8", errors="replace")- if isinstance(body, bytes) else str(body)))- except (json.JSONDecodeError, UnicodeDecodeError):+ result = lambda_svc._execute_function(func, event)++ if result.get("error"):+ body = result.get("body", {})+ if isinstance(body, dict):raise _ExecutionError(- "Lambda.Unknown",- body.decode("utf-8", errors="replace")- if isinstance(body, bytes) else str(body))+ body.get("errorType", "Lambda.Unknown"),+ body.get("errorMessage", str(body)))+ raise _ExecutionError("Lambda.Unknown", str(body))+ body = result.get("body")+ if body is None:+ return {}+ if isinstance(body, (dict, list)):+ return bodytry:- return json.loads(body) if body else {}- except (json.JSONDecodeError, UnicodeDecodeError):- return body.decode("utf-8", errors="replace") if isinstance(body, bytes) else body+ return json.loads(body) if isinstance(body, (str, bytes)) else body+ except (json.JSONDecodeError, TypeError):+ return body# ---------------------------------------------------------------------------diff --git a/pyproject.toml b/pyproject.tomlindex 4feec9f5..0ed6076b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.1.21"+version = "1.1.22"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/test_services.py b/tests/test_services.pyindex 4fcd67e2..3b58d03d 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -12865,6 +12865,238 @@ def test_sfn_activity_worker_failure(sfn):assert sfn.describe_execution(executionArn=exec_arn)["status"] == "FAILED"+def test_sfn_mock_config_return(sfn):+ """SFN_MOCK_CONFIG Return — AWS SFN Local format with #TestCase ARN suffix."""+ from conftest import _ministack_config++ mock_cfg = {+ "StateMachines": {+ "qa-sfn-mock": {+ "TestCases": {+ "HappyPath": {+ "CallService": "MockedSuccess",+ }+ }+ }+ },+ "MockedResponses": {+ "MockedSuccess": {+ "0": {"Return": {"status": "mocked", "value": 42}},+ }+ },+ }+ _ministack_config({"stepfunctions._sfn_mock_config": mock_cfg})++ definition = json.dumps({+ "StartAt": "CallService",+ "States": {+ "CallService": {+ "Type": "Task",+ "Resource": "arn:aws:lambda:us-east-1:000000000000:function:nonexistent",+ "End": True,+ }+ },+ })+ sm_arn = sfn.create_state_machine(+ name="qa-sfn-mock",+ definition=definition,+ roleArn="arn:aws:iam::000000000000:role/r",+ )["stateMachineArn"]++ # Execute with #HappyPath test case+ exec_arn = sfn.start_execution(+ stateMachineArn=sm_arn + "#HappyPath", input="{}",+ )["executionArn"]+ for _ in range(20):+ time.sleep(0.3)+ desc = sfn.describe_execution(executionArn=exec_arn)+ if desc["status"] != "RUNNING":+ break++ assert desc["status"] == "SUCCEEDED"+ output = json.loads(desc["output"])+ assert output["status"] == "mocked"+ assert output["value"] == 42+ _ministack_config({"stepfunctions._sfn_mock_config": {}})+++def test_sfn_mock_config_throw(sfn):+ """SFN_MOCK_CONFIG Throw — AWS SFN Local format with invocation indexing."""+ from conftest import _ministack_config++ mock_cfg = {+ "StateMachines": {+ "qa-sfn-mock-throw": {+ "TestCases": {+ "FailPath": {+ "CallService": "MockedFailure",+ }+ }+ }+ },+ "MockedResponses": {+ "MockedFailure": {+ "0": {"Throw": {"Error": "ServiceDown", "Cause": "mocked failure"}},+ }+ },+ }+ _ministack_config({"stepfunctions._sfn_mock_config": mock_cfg})++ definition = json.dumps({+ "StartAt": "CallService",+ "States": {+ "CallService": {+ "Type": "Task",+ "Resource": "arn:aws:lambda:us-east-1:000000000000:function:nonexistent",+ "End": True,+ }+ },+ })+ sm_arn = sfn.create_state_machine(+ name="qa-sfn-mock-throw",+ definition=definition,+ roleArn="arn:aws:iam::000000000000:role/r",+ )["stateMachineArn"]++ exec_arn = sfn.start_execution(+ stateMachineArn=sm_arn + "#FailPath", input="{}",+ )["executionArn"]+ for _ in range(20):+ time.sleep(0.3)+ desc = sfn.describe_execution(executionArn=exec_arn)+ if desc["status"] != "RUNNING":+ break++ assert desc["status"] == "FAILED"+ _ministack_config({"stepfunctions._sfn_mock_config": {}})+++def test_sfn_test_state_pass(sfn_sync):+ """TestState API — Pass state returns transformed output."""+ resp = sfn_sync.test_state(+ definition=json.dumps({+ "Type": "Pass",+ "Result": {"greeting": "hello"},+ "ResultPath": "$.result",+ "Next": "NextStep",+ }),+ input=json.dumps({"existing": "data"}),+ roleArn="arn:aws:iam::000000000000:role/r",+ )+ assert resp["status"] == "SUCCEEDED"+ output = json.loads(resp["output"])+ assert output["result"]["greeting"] == "hello"+ assert output["existing"] == "data"+ assert resp["nextState"] == "NextStep"+++def test_sfn_test_state_choice(sfn_sync):+ """TestState API — Choice state routes to correct next state."""+ resp = sfn_sync.test_state(+ definition=json.dumps({+ "Type": "Choice",+ "Choices": [+ {"Variable": "$.val", "NumericEquals": 1, "Next": "One"},+ {"Variable": "$.val", "NumericEquals": 2, "Next": "Two"},+ ],+ "Default": "Other",+ }),+ input=json.dumps({"val": 2}),+ roleArn="arn:aws:iam::000000000000:role/r",+ )+ assert resp["status"] == "SUCCEEDED"+ assert resp["nextState"] == "Two"+++def test_sfn_test_state_fail(sfn_sync):+ """TestState API — Fail state returns FAILED status."""+ resp = sfn_sync.test_state(+ definition=json.dumps({+ "Type": "Fail",+ "Error": "CustomError",+ "Cause": "Something went wrong",+ }),+ input="{}",+ roleArn="arn:aws:iam::000000000000:role/r",+ )+ assert resp["status"] == "FAILED"+ assert resp["error"] == "CustomError"+ assert resp["cause"] == "Something went wrong"+++def test_sfn_test_state_task_with_mock_return(sfn_sync):+ """TestState API — Task state with mock.result returns mocked output."""+ resp = sfn_sync.test_state(+ definition=json.dumps({+ "Type": "Task",+ "Resource": "arn:aws:lambda:us-east-1:000000000000:function:MyFunc",+ "End": True,+ }),+ input=json.dumps({"key": "value"}),+ roleArn="arn:aws:iam::000000000000:role/r",+ inspectionLevel="DEBUG",+ mock={"result": json.dumps({"Payload": {"statusCode": 200, "body": "mocked"}})},+ )+ assert resp["status"] == "SUCCEEDED"+ output = json.loads(resp["output"])+ assert output["Payload"]["body"] == "mocked"+++def test_sfn_test_state_task_with_mock_error(sfn_sync):+ """TestState API — Task state with mock.errorOutput and Catch."""+ resp = sfn_sync.test_state(+ definition=json.dumps({+ "Type": "Task",+ "Resource": "arn:aws:lambda:us-east-1:000000000000:function:MyFunc",+ "Catch": [{"ErrorEquals": ["Lambda.ServiceException"], "Next": "HandleError"}],+ "Next": "Done",+ }),+ input=json.dumps({"key": "value"}),+ roleArn="arn:aws:iam::000000000000:role/r",+ mock={"errorOutput": {"error": "Lambda.ServiceException", "cause": "Service unavailable"}},+ )+ assert resp["status"] == "CAUGHT_ERROR"+ assert resp["nextState"] == "HandleError"+ assert resp["error"] == "Lambda.ServiceException"+++def test_sfn_test_state_debug_inspection(sfn_sync):+ """TestState API — DEBUG inspectionLevel returns data transformation details."""+ resp = sfn_sync.test_state(+ definition=json.dumps({+ "Type": "Pass",+ "InputPath": "$.payload",+ "Result": {"data": 1},+ "ResultPath": "$.result",+ "Next": "Done",+ }),+ input=json.dumps({"payload": {"foo": "bar"}}),+ roleArn="arn:aws:iam::000000000000:role/r",+ inspectionLevel="DEBUG",+ )+ assert resp["status"] == "SUCCEEDED"+ assert "inspectionData" in resp+ assert "input" in resp["inspectionData"]+++def test_sfn_test_state_from_full_definition(sfn_sync):+ """TestState API — extract specific state from full state machine definition."""+ resp = sfn_sync.test_state(+ definition=json.dumps({+ "StartAt": "First",+ "States": {+ "First": {"Type": "Pass", "Result": "first", "Next": "Second"},+ "Second": {"Type": "Pass", "Result": "second", "End": True},+ }+ }),+ input="{}",+ roleArn="arn:aws:iam::000000000000:role/r",+ stateName="Second",+ )+ assert resp["status"] == "SUCCEEDED"+ assert json.loads(resp["output"]) == "second"++# ---------------------------------------------------------------------------# EC2# ---------------------------------------------------------------------------@@ -14359,6 +14591,31 @@ def test_logs_list_tags_for_resource_arn_without_star(logs):logs.delete_log_group(logGroupName=name)+def test_logs_get_log_events_pagination_stops(logs):+ """GetLogEvents must return the caller's token when at end of stream to stop SDK pagination."""+ group = "/test/pagination-stop"+ stream = "s1"+ logs.create_log_group(logGroupName=group)+ logs.create_log_stream(logGroupName=group, logStreamName=stream)+ logs.put_log_events(+ logGroupName=group, logStreamName=stream,+ logEvents=[+ {"timestamp": 1000, "message": "msg1"},+ {"timestamp": 2000, "message": "msg2"},+ ],+ )++ # First call — get all events+ resp = logs.get_log_events(logGroupName=group, logStreamName=stream, startFromHead=True)+ assert len(resp["events"]) == 2+ fwd_token = resp["nextForwardToken"]++ # Second call with forward token — no more events, token must match what we sent+ resp2 = logs.get_log_events(logGroupName=group, logStreamName=stream, nextToken=fwd_token)+ assert len(resp2["events"]) == 0+ assert resp2["nextForwardToken"] == fwd_token # same token = stop paginating++# ---------------------------------------------------------------------------# Regression: SQS SendMessageBatch must reject batches larger than 10 entries.# AWS returns TooManyEntriesInBatchRequest; MiniStack was silently accepting them.