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(eventbridge): 8 AWS-spec divergences + cron L/W/# parity (#545)
Nahuel Nucera4641a9fc4a67
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2629b45b..5a254afd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,10 +7,29 @@ Versioning follows [Semantic Versioning](https://semver.org/).----## [Unreleased]+## [1.3.25] — 2026-05-03### Added-- **AppSync Events API emulator** — Event APIs are now available under the AppSync service: `CreateApi`/`GetApi`/`ListApis`/`UpdateApi`/`DeleteApi`, channel namespace CRUD, API-key management through the AWS SDK's `/v1/apis/{apiId}/apikeys` path, HTTP `POST /event` publishing on `*.appsync-api.*`, and realtime `*.appsync-realtime-api.*` WebSocket subscribe/publish flows. Channel validation follows the AppSync Events grammar, publish fan-out returns AWS-shaped identifiers, and API-key / Lambda-authorizer checks are enforced consistently across HTTP and WebSocket publish paths.+- **AppSync Events API** — Event API management under `/v2/apis`, channel namespaces, API keys via `/v1/apis/{apiId}/apikeys`, HTTP publish on `{apiId}.appsync-api.*`, and realtime WebSocket on `{apiId}.appsync-realtime-api.*` (`aws-appsync-event-ws` subprotocol). Strict auth via `APPSYNC_EVENTS_ENFORCE_AUTH=1`. Contributed by @marcin-nowak-scl.+- **CloudFront KeyValueStore — management plane** — Create/Describe/List/Update/Delete with ETag concurrency; `KeyValueStoreAssociations` round-tripped through CloudFront Functions. Contributed by @DaviReisVieira.+- **CloudFront KeyValueStore — data plane** — separate `cloudfront-keyvaluestore` service covering Describe, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys with ETag concurrency. Contributed by @DaviReisVieira.+- **EventBridge `cron()` schedule auto-fire** — full AWS-spec parity. Zero-dep parser for the 6-field syntax: `*`, `?`, ranges, steps, lists, named month/weekday tokens, and the `L` (last day / `<n>L` last weekday-of-month), `LW` (last weekday), `<n>W` (nearest weekday), and `<n>#<k>` (kth weekday-of-month) operators. DoM/DoW mutual-exclusion enforced at `PutRule`. Contributed by @hiddengearz.++### Fixed+- **AppSync Events `ChannelNamespace` response now includes `channelNamespaceArn`** — spec member was omitted; Terraform / Java SDK v2 saw `null` where AWS returns the ARN.+- **CloudFront KVS data-plane `DescribeKeyValueStore` `Created` / `LastModified`** — were hardcoded to `0`; now parsed from the management-plane timestamp into int epoch seconds.+- **S3 vhost routing excludes `cloudfront-kvs.*`** — moved the bypass from a `/key-value-stores/` path check up to the `_NON_S3_VHOST_NAMES` host-name layer.+- **EventBridge `DescribeRule` / `ListRules` now emit `CreatedBy` and `ManagedBy`** — spec members were silently dropped from `_rule_out`.+- **EventBridge `PutEvents` rejects more than 10 entries** — AWS spec caps `Entries` at 10; ministack accepted any size.+- **EventBridge event `Time` is int epoch seconds, not float** — Java/Go SDK v2 timestamp parsers reject high-precision floats; archive replays now also dispatch the int form.+- **EventBridge content-filter `[{"exists": false}]` matches absent keys** — short-circuited to no-match before the `exists` branch was evaluated, so patterns that should fire on missing fields silently dropped.+- **EventBridge `ListRules` paginates** — added `Limit` (1-100) and opaque `NextToken`; previously returned the full list and SDK paginators looped on the first page.+- **EventBridge `ListRuleNamesByTarget` `NextToken` is opaque** — was a raw integer offset string.+- **EventBridge `DescribeEventBus` / `ListEventBuses` omit `Policy` when no policy set** — was emitting `""`, divergent from AWS shape.+- **EventBridge `DescribeEventSource` State** — was hardcoded `ENABLED`; AWS enum is `PENDING` / `ACTIVE` / `DELETED`. Now returns `ACTIVE`.++---+## [1.3.24] — 2026-05-02### Fixed@@ -26,7 +45,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added- **Amazon OpenSearch Service** — management plane on `/2021-01-01/*`: CreateDomain, DescribeDomain(s), DeleteDomain, ListDomainNames (with `EngineType` filter), UpdateDomainConfig, DescribeDomainConfig (`Options`/`Status` wrapping), DescribeDomainChangeProgress, ListVersions, GetCompatibleVersions, AddTags/ListTags/RemoveTags. Account-scoped state. Default data plane is a stub endpoint; set `OPENSEARCH_DATAPLANE=1` to spawn one real `opensearchproject/opensearch` container per `CreateDomain` (same pattern as ElastiCache/RDS). Add `OPENSEARCH_DASHBOARDS=1` for an optional per-domain `opensearch-dashboards` sidecar — `DescribeDomain.DashboardEndpoint` is populated. `DeleteDomain` tears down spawned containers. Terraform `aws_opensearch_domain` compatible. Requested by @marcin-nowak-scl.-- **EventBridge scheduled rule auto-fire — `rate()` and `cron()`** — both schedule expression types now fire automatically. A daemon thread (`eb-scheduler`) ticks every 10 s; the per-rule countdown anchors to `CreationTime` so the first fire lands one full interval after `PutRule`. `rate(N minute|hour|day)` rules use interval arithmetic; `cron(Min Hr DoM Mon DoW Year)` rules use a zero-dependency hand-rolled parser that handles `*`, `?`, ranges (`MON-FRI`), steps (`*/5`), lists, and named month/weekday tokens. The `?` mutual-exclusion between DoM and DoW is enforced per AWS spec. No new runtime dependencies. Scheduled event payload matches AWS exactly (`source: aws.events`, `detail-type: Scheduled Event`, `detail: {}`, ISO 8601 `time`). Multi-tenant — iterates the rules store directly. Contributed by @hiddengearz.+- **EventBridge scheduled rule auto-fire** — `rate(N minute|hour|day)` rules now fire automatically. A daemon thread (`eb-scheduler`) ticks every 10 s; the per-rule countdown anchors to `CreationTime` so the first fire lands one full interval after `PutRule`. Scheduled event payload matches AWS exactly (`source: aws.events`, `detail-type: Scheduled Event`, `detail: {}`, ISO 8601 `time`). Multi-tenant — iterates the rules store directly. `cron()` expressions are stored but not yet auto-fired (one-time `INFO` log surfaces the gap). Contributed by @hiddengearz.- **AWS Organizations** — DescribeOrganization, ListRoots, ListAccounts, DescribeAccount, ListOrganizationalUnitsForParent / ListAccountsForParent, CreateOrganizationalUnit / DescribeOrganizationalUnit / DeleteOrganizationalUnit. Single-master-account org auto-initialised on first call; nested OUs carry the new `Path` field (2026-03 AWS additive change).- **AWS Account service** — GetAccountInformation, GetContactInformation, ListRegions, GetRegionOptStatus. Returns the new `AccountState: ACTIVE` field (2026-04 AWS additive change). Older boto3 SDKs strip the field; newer ones see it.- **AWS Batch** — control-plane stub: ComputeEnvironments, JobQueues, JobDefinitions (auto-revisioning), SubmitJob (auto-`SUCCEEDED`), DescribeJobs, ListJobs. Account-scoped.diff --git a/README.md b/README.mdindex 8eb782ef..e6fc4e34 100644--- a/README.md+++ b/README.md@@ -374,7 +374,8 @@ subnet = ec2.create_subnet(| **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` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag || **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 || **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 27 actions; RSA (2048/4096), ECC (SECG_P256K1, NIST P-256/384/521), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; envelope encryption; alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |-| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; field validation and name uniqueness enforcement; **CloudFront Functions** are API stubs only (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function` and distribution associations) — no `TestFunction`, no KVS associations, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again |+| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again |+| **CloudFront KeyValueStore (data plane)** | DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys | Separate `cloudfront-keyvaluestore` SDK service (REST/JSON, signing name `cloudfront-keyvaluestore`); ETag-based optimistic concurrency on every mutating op; `UpdateKeys` is atomic (validates whole batch, rejects on first invalid entry); `ListKeys` paginates with opaque `NextToken` capped at 50 results per AWS spec; bridges to the management plane via the shared KVS ARN |### CloudFormationdiff --git a/ministack/app.py b/ministack/app.pyindex 0b0941fa..b448e012 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -97,6 +97,7 @@ _NON_S3_VHOST_NAMES = frozenset({"secretsmanager", "logs", "ssm", "events", "kinesis", "monitoring", "ses","states", "ecs", "rds", "rds-data", "elasticache", "glue", "athena","apigateway", "cloudformation", "autoscaling", "codebuild", "transfer",+ "cloudfront-kvs","appsync-api", "appsync-realtime-api",})@@ -280,6 +281,7 @@ _state_map = {"appconfig": "appconfig", "transfer": "transfer","scheduler": "scheduler", "autoscaling": "autoscaling","eks": "eks", "backup": "backup", "pipes": "pipes",+ "cloudfront_keyvaluestore": "cloudfront_keyvaluestore",}SERVICE_NAME_ALIASES = {@@ -1029,6 +1031,10 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dbucket = _extract_s3_vhost_bucket(host)if not bucket or _S3_VHOST_EXCLUDE_RE.search(host) or bucket in _NON_S3_VHOST_NAMES:return None+ # CloudFront KVS data-plane clients (boto3 cloudfront-keyvaluestore with+ # inject_host_prefix=False) hit ministack with host=localhost and path+ # prefixed by /key-value-stores/. Host-name exclusion above doesn't fire,+ # so guard explicitly here too.if path.startswith("/key-value-stores/"):return None@@ -1298,10 +1304,21 @@ async def _handle_lifespan(scope, receive, send):await transfer.sftp_start()except Exception as e:logger.warning("Transfer SFTP startup failed: %s", e)+ # Start the EventBridge scheduler daemon explicitly. Module-import+ # autostart is gated by MINISTACK_TEST_NO_AUTOSTART so unit tests+ # don't race; lifespan.startup is the canonical place to spin it up.+ try:+ from ministack.services import eventbridge as _eb_mod+ _eb_mod.start_scheduler()+ except Exception as e:+ logger.warning("EventBridge scheduler startup failed: %s", e)await send({"type": "lifespan.startup.complete"})- logger.info("Ready.")+ logger.info("Ready — %d services available on port %s.", len(SERVICE_HANDLERS), port)+ # Per-service "init completed" lines are logged at DEBUG only — at+ # INFO they bury the operational signal (CreateBucket, etc.) under+ # a wall of one line per service.for svc in SERVICE_HANDLERS:- logger.info("%s init completed.", svc.capitalize())+ logger.debug("%s init completed.", svc.capitalize())asyncio.create_task(_run_ready_scripts())elif message["type"] == "lifespan.shutdown":logger.info("MiniStack shutting down...")diff --git a/ministack/services/appsync.py b/ministack/services/appsync.pyindex 29c63f63..08a1ab8a 100644--- a/ministack/services/appsync.py+++ b/ministack/services/appsync.py@@ -558,7 +558,7 @@ async def handle_request(method, path, headers, body, query_params):if method == "POST":return appsync_events._create_api_key(api_id, body or b"{}")elif method == "GET":- return appsync_events._list_api_keys(api_id)+ return appsync_events._list_api_keys(api_id, query_params)elif method == "DELETE":return appsync_events._delete_api_key(api_id, sub2)if sub2 is None:diff --git a/ministack/services/appsync_events.py b/ministack/services/appsync_events.pyindex 9321ddc8..438bc01e 100644--- a/ministack/services/appsync_events.py+++ b/ministack/services/appsync_events.py@@ -1,32 +1,19 @@"""-AppSync Events Service Emulator — AWS-compatible.-Supports: CreateApi, GetApi, ListApis, UpdateApi, DeleteApi,- CreateChannelNamespace, GetChannelNamespace, ListChannelNamespaces,- UpdateChannelNamespace, DeleteChannelNamespace,- CreateApiKey, ListApiKeys, DeleteApiKey,- Publish (HTTP POST /event on {apiId}.appsync-api.{region}.{host}),- WebSocket subscribe (wss://{apiId}.appsync-realtime-api.{region}.{host}/event/realtime,- aws-appsync-event-ws subprotocol: connection_init, subscribe,- unsubscribe, publish, server-pushed data + ka keep-alives).-Event API management is REST/JSON under /v2/apis (shares the ``appsync``-credential scope); API key operations use the AWS SDK's /v1/apis/{apiId}/apikeys-path and are delegated from ``services/appsync.py``. Channel paths validated-against the 1..5-segment spec regex; subscribe patterns accept a trailing-``*`` single-level wildcard. Connection-scoped-authorization is sent via a second ``header-<base64url(json)>`` subprotocol-entry and cached for later subscribe/publish frames. Set-``APPSYNC_EVENTS_ENFORCE_AUTH=1`` for strict mode: without an ``AWS_LAMBDA``-``authProvider``, only registered **x-api-key** values are accepted; when-``authType: AWS_LAMBDA`` and ``lambdaAuthorizerConfig.authorizerUri`` are present-in the API ``eventConfig``, the named Lambda is invoked (connect + subscribe +-publish) with the same ``AuthorizationToken`` / ``Channel`` / ``Operation``-shape as on AWS. By default ``CreateApi`` / ``GetApi`` return ``dns`` hostnames of-the form ``{apiId}.appsync-api.{region}.{MINISTACK_HOST}:{port}`` and-``{apiId}.appsync-realtime-api.{region}.{MINISTACK_HOST}:{port}`` (AWS-style-service labels with a local base host and explicit ``GATEWAY_PORT``).-Optional: ``APPSYNC_EVENTS_HTTP_HOST_TEMPLATE`` and-``APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE`` (``{api_id}``, ``{region}``, ``{port}``)-override those defaults when **both** are set.+AWS AppSync Events emulator.++Event API management lives under /v2/apis and shares the ``appsync``+credential scope, so ``services/appsync.py`` delegates here. API key+operations land on /v1/apis/{apiId}/apikeys (same delegation path).+Data plane: HTTP publish at POST /event on {apiId}.appsync-api.* and a+realtime WebSocket on {apiId}.appsync-realtime-api.* using the+``aws-appsync-event-ws`` subprotocol.++Channel paths follow the 1..5-segment grammar; subscribe patterns accept a+trailing ``*`` single-level wildcard. Connection-scoped authorization is+declared via a second ``header-<base64url(json)>`` Sec-WebSocket-Protocol+entry. Set ``APPSYNC_EVENTS_ENFORCE_AUTH=1`` for strict mode (registered+x-api-key required, or AWS_LAMBDA authorizer Lambda invoked when configured+in the API ``eventConfig``)."""import asyncio@@ -175,13 +162,15 @@ def _default_event_config(requested: dict | None) -> dict:"""requested = requested or {}default_auth = [{"authType": "API_KEY"}]- return {+ out = {"authProviders": requested.get("authProviders") or default_auth,"connectionAuthModes": requested.get("connectionAuthModes") or default_auth,"defaultPublishAuthModes": requested.get("defaultPublishAuthModes") or default_auth,"defaultSubscribeAuthModes": requested.get("defaultSubscribeAuthModes") or default_auth,- "logConfig": requested.get("logConfig"),}+ if requested.get("logConfig") is not None:+ out["logConfig"] = requested["logConfig"]+ return outdef _api_response(api_id: str) -> dict:@@ -202,6 +191,10 @@ def _api_response(api_id: str) -> dict:}+def _channel_namespace_arn(api_id: str, name: str) -> str:+ return f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}/channelNamespace/{name}"++def _channel_response(api_id: str, name: str) -> dict:ns = _channel_namespaces.get(api_id, {}).get(name, {})if not ns:@@ -214,6 +207,7 @@ def _channel_response(api_id: str, name: str) -> dict:"codeHandlers": ns.get("codeHandlers"),"handlerConfigs": ns.get("handlerConfigs"),"tags": ns.get("tags", {}),+ "channelNamespaceArn": _channel_namespace_arn(api_id, name),"created": ns["created"],"lastModified": ns["lastModified"],}@@ -262,7 +256,12 @@ _CHANNEL_SEGMENT_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])def _split_channel(channel: str) -> list[str] | None:- if not channel or not channel.startswith("/"):+ """Split an AWS AppSync Events channel path into segments.++ Per AWS spec the leading and trailing ``/`` are optional, so ``foo/bar``+ and ``/foo/bar/`` both yield ``["foo", "bar"]``. 1..5 segments required.+ """+ if not channel:return Noneparts = [p for p in channel.split("/") if p != ""]if not 1 <= len(parts) <= 5:@@ -397,6 +396,13 @@ def _bearer_from_auth_dict(auth: dict | None) -> str:def _parse_lambda_authorizer_body(body: object) -> tuple[bool, dict | None]:+ """Parse the AppSync Events Lambda authorizer response.++ Per AWS spec the response carries ``isAuthorized`` (required boolean) and+ optionally ``handlerContext`` (key/value strings, exposed to handlers as+ ``$ctx.identity.handlerContext``). ``ttlOverride`` is parsed/ignored —+ ministack doesn't cache authorizer decisions.+ """if isinstance(body, str):try:body = json.loads(body)@@ -404,28 +410,41 @@ def _parse_lambda_authorizer_body(body: object) -> tuple[bool, dict | None]:return False, Noneif not isinstance(body, dict):return False, None- ok = bool(- body.get("isAuthorized")- or body.get("IsAuthorized")- )- ctx = body.get("resolverContext")- if ctx is None:- ctx = body.get("ResolverContext")- if not ok:+ if not bool(body.get("isAuthorized")):return False, None- if isinstance(ctx, dict):- return True, ctx- return True, None+ ctx = body.get("handlerContext")+ return True, ctx if isinstance(ctx, dict) else None-def _events_authorizer_invoke(arn: str, operation: str, channel: str | None, authorization_token: str) -> tuple[bool, dict | None]:- """Invoke the configured authorizer Lambda with AppSync-style request/response payloads."""+def _events_authorizer_invoke(+ arn: str,+ api_id: str,+ operation: str,+ channel: str | None,+ namespace: str | None,+ authorization_token: str,+ request_headers: dict,+) -> tuple[bool, dict | None]:+ """Invoke the configured authorizer Lambda with the AWS-spec event payload.++ Real AWS sends ``{authorizationToken, requestContext{apiId,accountId,+ requestId,operation,channelNamespaceName,channel}, requestHeaders}`` with+ operations ``EVENT_CONNECT`` / ``EVENT_SUBSCRIBE`` / ``EVENT_PUBLISH``;+ for ``EVENT_CONNECT`` the channelNamespaceName and channel are null.+ """if not authorization_token.strip() or not arn:return False, Nonepayload: dict = {- "AuthorizationToken": authorization_token,- "Channel": channel,- "Operation": operation,+ "authorizationToken": authorization_token,+ "requestContext": {+ "apiId": api_id,+ "accountId": get_account_id(),+ "requestId": new_uuid(),+ "operation": operation,+ "channelNamespaceName": namespace,+ "channel": channel,+ },+ "requestHeaders": request_headers or {},}try:from ministack.services import lambda_svc@@ -447,24 +466,38 @@ def _events_authorizer_invoke(arn: str, operation: str, channel: str | None, autreturn _parse_lambda_authorizer_body(res.get("body"))+# AWS operation enum — sent verbatim in the Lambda authorizer ``operation`` field.+EVENT_CONNECT = "EVENT_CONNECT"+EVENT_SUBSCRIBE = "EVENT_SUBSCRIBE"+EVENT_PUBLISH = "EVENT_PUBLISH"++# AWS limit: at most 5 events per publish (HTTP body or WebSocket frame).+_MAX_EVENTS_PER_BATCH = 5++async def _authorize_event_op(api_id: str,channel: str | None,operation: str,auth: dict | None,+ request_headers: dict | None = None,) -> tuple[bool, str | None]:- """Authorize an AppSync Events subscribe/publish operation."""+ """Authorize an AppSync Events subscribe/publish/connect operation."""lambda_arn = _find_lambda_authorizer_arn(api_id)if lambda_arn:token = _bearer_from_auth_dict(auth)if not token:return False, f"{operation} rejected: no Authorization token"- ok, _resolver_context = await asyncio.to_thread(+ namespace = _channel_namespace_for(channel) if channel else None+ ok, _ctx = await asyncio.to_thread(_events_authorizer_invoke,lambda_arn,+ api_id,operation,channel,+ namespace,token,+ request_headers or {},)if not ok:return False, f"{operation} rejected: AppSync authorizer denied"@@ -588,10 +621,49 @@ def _get_api(api_id):return json_response({"api": _api_response(api_id)})+def _qp_str(query_params: dict, key: str) -> str | None:+ v = query_params.get(key)+ if isinstance(v, list):+ return v[0] if v else None+ return v+++def _qp_int(query_params: dict, key: str, default: int) -> int:+ v = _qp_str(query_params, key)+ if v is None or v == "":+ return default+ try:+ return int(v)+ except (TypeError, ValueError):+ return default+++def _paginate(items: list, query_params: dict) -> tuple[list, str | None]:+ """Apply AppSync ``maxResults`` + ``nextToken`` pagination over a sorted list.++ Token is the index of the first item to return — opaque to clients but+ survives a restart since item order is stable (lexical on identifier).+ """+ max_results = max(1, min(_qp_int(query_params, "maxResults", 100), 1000))+ next_token = _qp_str(query_params, "nextToken")+ start = 0+ if next_token:+ try:+ start = max(0, int(next_token))+ except ValueError:+ start = 0+ page = items[start : start + max_results]+ new_token = str(start + max_results) if start + max_results < len(items) else None+ return page, new_token++def _list_apis(query_params):- max_results = int((query_params.get("maxResults", [100])[0]) if isinstance(query_params.get("maxResults"), list) else query_params.get("maxResults", 100) or 100)- page = [_api_response(aid) for aid in sorted(_apis.keys())]- return json_response({"apis": page[:max_results]})+ items = [_api_response(aid) for aid in sorted(_apis.keys())]+ page, token = _paginate(items, query_params)+ resp: dict = {"apis": page}+ if token is not None:+ resp["nextToken"] = token+ return json_response(resp)def _update_api(api_id, body):@@ -666,7 +738,11 @@ def _list_channel_namespaces(api_id, query_params):return _not_found(f"Api {api_id} not found")namespaces = _channel_namespaces.get(api_id, {})items = [_channel_response(api_id, n) for n in sorted(namespaces.keys())]- return json_response({"channelNamespaces": items})+ page, token = _paginate(items, query_params)+ resp: dict = {"channelNamespaces": page}+ if token is not None:+ resp["nextToken"] = token+ return json_response(resp)def _update_channel_namespace(api_id, name, body):@@ -710,13 +786,16 @@ def _create_api_key(api_id, body):return json_response({"apiKey": _api_key_response(api_id, key_id)})-def _list_api_keys(api_id):+def _list_api_keys(api_id, query_params: dict | None = None):if api_id not in _apis:return _not_found(f"Api {api_id} not found")keys = _api_keys.get(api_id, {})- return json_response({- "apiKeys": [_api_key_response(api_id, kid) for kid in sorted(keys.keys())],- })+ items = [_api_key_response(api_id, kid) for kid in sorted(keys.keys())]+ page, token = _paginate(items, query_params or {})+ resp: dict = {"apiKeys": page}+ if token is not None:+ resp["nextToken"] = token+ return json_response(resp)def _delete_api_key(api_id, key_id):@@ -746,6 +825,13 @@ async def _publish(api_id: str, headers: dict, body: bytes):"Request body must include 'channel' and 'events' (array)",400,)+ # AWS spec: max 5 events per publish.+ if len(events) > _MAX_EVENTS_PER_BATCH:+ return error_response_json(+ "BadRequestException",+ f"events array may contain at most {_MAX_EVENTS_PER_BATCH} entries",+ 400,+ )channel_err = _validate_channel(channel, allow_wildcard=False)if channel_err:@@ -759,7 +845,9 @@ async def _publish(api_id: str, headers: dict, body: bytes):401,)- ok, message = await _authorize_event_op(api_id, str(channel), "publish", _auth_from_headers(headers))+ ok, message = await _authorize_event_op(+ api_id, str(channel), EVENT_PUBLISH, _auth_from_headers(headers), headers+ )if not ok:return error_response_json("UnauthorizedException", message or "Unauthorized", 401)@@ -908,9 +996,12 @@ async def handle_websocket(scope, receive, send, api_id: str):ok, connect_rctx = await asyncio.to_thread(_events_authorizer_invoke,lambda_auth_arn,- "connect",+ api_id,+ EVENT_CONNECT,+ None,None,tok,+ conn_auth or {},)if not ok and await _deny_websocket("connect rejected: AppSync authorizer returned deny or error",@@ -1051,7 +1142,7 @@ async def _handle_client_frame(api_id: str, connection_id: str, frame: dict, out})returnok, message = await _authorize_event_op(- api_id, str(channel), "subscribe", _effective_auth(frame, connection_id),+ api_id, str(channel), EVENT_SUBSCRIBE, _effective_auth(frame, connection_id),)if not ok:await outbox.put({@@ -1061,10 +1152,20 @@ async def _handle_client_frame(api_id: str, connection_id: str, frame: dict, out"message": message or "subscribe rejected"}],})return+ # AWS spec: subscription IDs must be unique per connection. Duplicate → subscribe_error.async with _get_connections_lock():conn = _connections.get(connection_id)- if conn is not None:- conn["subscriptions"][sub_id] = channel+ if conn is None:+ return+ if sub_id in conn["subscriptions"]:+ await outbox.put({+ "type": "subscribe_error",+ "id": sub_id,+ "errors": [{"errorType": "BadRequestException",+ "message": f"Subscription id '{sub_id}' is already in use on this connection"}],+ })+ return+ conn["subscriptions"][sub_id] = channelawait outbox.put({"type": "subscribe_success", "id": sub_id})return@@ -1080,6 +1181,14 @@ async def _handle_client_frame(api_id: str, connection_id: str, frame: dict, out"message": "'id', 'channel' and 'events' (array) are required"}],})return+ if len(events) > _MAX_EVENTS_PER_BATCH:+ await outbox.put({+ "type": "publish_error",+ "id": pub_id,+ "errors": [{"errorType": "BadRequestException",+ "message": f"events array may contain at most {_MAX_EVENTS_PER_BATCH} entries"}],+ })+ returnchannel_err = _validate_channel(channel, allow_wildcard=False)if channel_err:await outbox.put({@@ -1098,7 +1207,7 @@ async def _handle_client_frame(api_id: str, connection_id: str, frame: dict, out})returnok, message = await _authorize_event_op(- api_id, str(channel), "publish", _effective_auth(frame, connection_id),+ api_id, str(channel), EVENT_PUBLISH, _effective_auth(frame, connection_id),)if not ok:await outbox.put({@@ -1119,11 +1228,22 @@ async def _handle_client_frame(api_id: str, connection_id: str, frame: dict, outif ftype == "unsubscribe":sub_id = frame.get("id")+ removed = Falseasync with _get_connections_lock():conn = _connections.get(connection_id)- if conn is not None:+ if conn is not None and sub_id in conn["subscriptions"]:conn["subscriptions"].pop(sub_id, None)- await outbox.put({"type": "unsubscribe_success", "id": sub_id})+ removed = True+ if removed:+ await outbox.put({"type": "unsubscribe_success", "id": sub_id})+ else:+ # AWS spec: unknown sub_id → unsubscribe_error with UnknownOperationError.+ await outbox.put({+ "type": "unsubscribe_error",+ "id": sub_id,+ "errors": [{"errorType": "UnknownOperationError",+ "message": f"Unknown operation id {sub_id}"}],+ })returnawait outbox.put({diff --git a/ministack/services/cloudfront_keyvaluestore.py b/ministack/services/cloudfront_keyvaluestore.pyindex df8a77e3..f8fc8cec 100644--- a/ministack/services/cloudfront_keyvaluestore.py+++ b/ministack/services/cloudfront_keyvaluestore.py@@ -8,10 +8,12 @@ Supports:DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys"""+import base64import copyimport jsonimport loggingimport re+from datetime import datetimefrom urllib.parse import unquotefrom ministack.core.persistence import load_state@@ -20,9 +22,9 @@ from ministack.core.responses import AccountScopedDict, json_response, new_uuidlogger = logging.getLogger("cloudfront-keyvaluestore")# ----------------------------------------------------------------------------# Path regexes — ARN contains a slash (e.g. arn:aws:cloudfront::123:key-value-store/name)-# The store name portion ([a-zA-Z0-9-_]+) never contains a slash, so we anchor-# the /keys boundary against the name segment to avoid ambiguity.+# Path regexes — ARN contains a slash (e.g. arn:aws:cloudfront::123:key-value-store/name).+# The store-name segment ([a-zA-Z0-9_-]+) never contains a slash, so the+# /keys boundary anchors unambiguously against the trailing name segment.# ---------------------------------------------------------------------------_KEY_RE = re.compile(r"^/key-value-stores/(arn:.+?/[a-zA-Z0-9_-]+)/keys/(.+)$")_KEYS_RE = re.compile(r"^/key-value-stores/(arn:.+?/[a-zA-Z0-9_-]+)/keys/?$")@@ -147,48 +149,69 @@ def _describe_store(arn: str):breakitems = store["items"]+ epoch = 0+ if kvs_meta and kvs_meta.get("LastModifiedTime"):+ try:+ epoch = int(datetime.fromisoformat(kvs_meta["LastModifiedTime"].replace("Z", "+00:00")).timestamp())+ except (ValueError, AttributeError):+ epoch = 0resp = {"KvsARN": arn,"ItemCount": len(items),"TotalSizeInBytes": _compute_size(items),"Status": "READY",- "Created": 0,- "LastModified": 0,+ "Created": epoch,+ "LastModified": epoch,}- if kvs_meta and kvs_meta.get("LastModifiedTime"):- resp["Created"] = 0- resp["LastModified"] = 0-return 200, {"Content-Type": "application/json", "ETag": store["etag"]}, json.dumps(resp).encode()+_LIST_KEYS_MAX = 50 # AWS spec cap.+++def _qp_first(query_params, key):+ v = query_params.get(key)+ if isinstance(v, list):+ return v[0] if v else None+ return v++def _list_keys(arn: str, query_params):store = _get_store(arn)if store is None:return _error("ResourceNotFoundException", f"Key value store {arn} was not found.", 404)- max_results = (- int((query_params.get("MaxResults") or [None])[0] or "10")- if isinstance(query_params.get("MaxResults"), list)- else int(query_params.get("MaxResults", "10") or "10")- )- next_token = None- if isinstance(query_params.get("NextToken"), list):- next_token = query_params["NextToken"][0] if query_params["NextToken"] else None- elif isinstance(query_params.get("NextToken"), str):- next_token = query_params["NextToken"] or None+ raw_max = _qp_first(query_params, "MaxResults")+ try:+ max_results = int(raw_max) if raw_max not in (None, "") else 10+ except (TypeError, ValueError):+ max_results = 10+ max_results = max(1, min(max_results, _LIST_KEYS_MAX)) # AWS spec: cap at 50.+ next_token = _qp_first(query_params, "NextToken") or Noneall_keys = sorted(store["items"].keys())start_idx = 0- if next_token and next_token in all_keys:- start_idx = all_keys.index(next_token)+ if next_token:+ try:+ cursor = base64.urlsafe_b64decode(next_token + "=" * (-len(next_token) % 4)).decode("utf-8")+ except (ValueError, UnicodeDecodeError):+ return _error("ValidationException", "NextToken is not valid.", 400)+ # Resume after the cursor key (exclusive) so successive pages don't+ # re-emit the boundary key.+ for i, k in enumerate(all_keys):+ if k > cursor:+ start_idx = i+ break+ else:+ start_idx = len(all_keys)page = all_keys[start_idx : start_idx + max_results]items = [{"Key": k, "Value": store["items"][k]} for k in page]resp = {"Items": items}if start_idx + max_results < len(all_keys):- resp["NextToken"] = all_keys[start_idx + max_results]+ last = page[-1]+ resp["NextToken"] = base64.urlsafe_b64encode(last.encode("utf-8")).decode("ascii").rstrip("=")return json_response(resp)@@ -252,7 +275,11 @@ def _delete_key(arn: str, key: str, headers):if if_match != store["etag"]:return _error("ConflictException", "The provided If-Match value does not match the current ETag.", 409)- store["items"].pop(key, None)+ # AWS spec: deleting a non-existent key returns ResourceNotFoundException, not 200.+ if key not in store["items"]:+ return _error("ResourceNotFoundException", f"Key {key} was not found.", 404)++ del store["items"][key]store["etag"] = new_uuid()resp = {@@ -278,20 +305,38 @@ def _update_keys(arn: str, headers, body):except (json.JSONDecodeError, TypeError):return _error("ValidationException", "Invalid JSON body.", 400)- puts = data.get("Puts", [])- deletes = data.get("Deletes", [])-- for item in puts:+ puts = data.get("Puts", []) or []+ deletes = data.get("Deletes", []) or []+ if not isinstance(puts, list) or not isinstance(deletes, list):+ return _error("ValidationException", "Puts and Deletes must be arrays.", 400)++ # AWS UpdateKeys is atomic: validate every entry first, then commit. A+ # single bad item rejects the whole batch so the store never sees a+ # partial write.+ validated_puts: list[tuple[str, str]] = []+ for i, item in enumerate(puts):+ if not isinstance(item, dict):+ return _error("ValidationException", f"Puts[{i}] must be an object.", 400)k = item.get("Key")v = item.get("Value")- if k is not None and v is not None:- store["items"][k] = v-- for item in deletes:+ if not isinstance(k, str) or not k:+ return _error("ValidationException", f"Puts[{i}].Key must be a non-empty string.", 400)+ if not isinstance(v, str):+ return _error("ValidationException", f"Puts[{i}].Value must be a string.", 400)+ validated_puts.append((k, v))+ validated_deletes: list[str] = []+ for i, item in enumerate(deletes):+ if not isinstance(item, dict):+ return _error("ValidationException", f"Deletes[{i}] must be an object.", 400)k = item.get("Key")- if k is not None:- store["items"].pop(k, None)-+ if not isinstance(k, str) or not k:+ return _error("ValidationException", f"Deletes[{i}].Key must be a non-empty string.", 400)+ validated_deletes.append(k)++ for k, v in validated_puts:+ store["items"][k] = v+ for k in validated_deletes:+ store["items"].pop(k, None)store["etag"] = new_uuid()resp = {diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex 1f28d14f..49ce8973 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -392,6 +392,7 @@ def _create_table(data):_tables[name]["LatestStreamArn"] = f"{_tables[name]['TableArn']}/stream/{stream_label}"if data.get("Tags"):_tags[_tables[name]["TableArn"]] = data["Tags"]+ logger.info("DynamoDB table created: %s", name)return json_response({"TableDescription": _table_description(name)})diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.pyindex 00a07eb9..67b9ea03 100644--- a/ministack/services/eventbridge.py+++ b/ministack/services/eventbridge.py@@ -22,6 +22,7 @@ Supports: CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, Descriimport copyimport fnmatch+import calendarimport hashlibimport jsonimport logging@@ -311,15 +312,19 @@ def _list_event_buses(data):buses = []for n, b in _event_buses.items():if n.startswith(prefix):- policy = _event_bus_policies.get(n)- buses.append({+ entry = {"Name": b["Name"],"Arn": b["Arn"],"Description": b.get("Description", ""),"CreationTime": b["CreationTime"],"LastModifiedTime": b.get("LastModifiedTime", b.get("CreationTime")),- "Policy": json.dumps(policy) if policy else ""- })+ }+ # AWS spec: Policy is optional; omit when no policy is set rather+ # than returning an empty string (Java SDK v2 sees a stray empty).+ policy = _event_bus_policies.get(n)+ if policy:+ entry["Policy"] = json.dumps(policy)+ buses.append(entry)return json_response({"EventBuses": buses})@@ -328,15 +333,17 @@ def _describe_event_bus(data):bus = _event_buses.get(name)if not bus:return error_response_json("ResourceNotFoundException", f"Event bus {name} not found", 400)- policy = _event_bus_policies.get(name)out = {"Name": bus["Name"],"Arn": bus["Arn"],"Description": bus.get("Description", ""),"CreationTime": bus["CreationTime"],"LastModifiedTime": bus.get("LastModifiedTime", bus.get("CreationTime")),- "Policy": json.dumps(policy) if policy else "",}+ # AWS spec: Policy is optional; omit when no policy is set.+ policy = _event_bus_policies.get(name)+ if policy:+ out["Policy"] = json.dumps(policy)for k in ("LogConfig", "DeadLetterConfig", "KmsKeyIdentifier"):if k in bus:out[k] = bus[k]@@ -390,12 +397,19 @@ def _rule_key(rule_name: str, bus_name: str) -> str:return f"{bus_name}|{rule_name}"+_RATE_RE = re.compile(r"^rate\(\d+\s+(minute|minutes|hour|hours|day|days)\)$")++def _validate_schedule_expression(expr: str) -> bool:if not expr:return True- rate_pattern = re.compile(r"^rate\(\d+\s+(minute|minutes|hour|hours|day|days)\)$")- cron_pattern = re.compile(r"^cron\(.+\)$")- return bool(rate_pattern.match(expr) or cron_pattern.match(expr))+ if _RATE_RE.match(expr):+ return True+ if expr.startswith("cron("):+ # Reuses the structural parser so PutRule rejects bad cron syntax (DoM/DoW+ # both non-'?', unknown tokens, malformed L/W/#) the same way real AWS does.+ return _parse_cron_fields(expr) is not None+ return Falsedef _put_rule(data):@@ -462,9 +476,32 @@ def _delete_rule(data):return json_response({})+def _opaque_offset_encode(offset: int) -> str:+ """AWS NextToken values are opaque (base64-style) per the EventBridge spec —+ not a raw integer offset. Encode the cursor so SDKs that round-trip and+ inspect the value see something opaque rather than a leakable index."""+ import base64 as _b64+ return _b64.urlsafe_b64encode(str(offset).encode("ascii")).decode("ascii").rstrip("=")+++def _opaque_offset_decode(token: str) -> int:+ import base64 as _b64+ if not token:+ return 0+ try:+ padded = token + "=" * (-len(token) % 4)+ return int(_b64.urlsafe_b64decode(padded.encode("ascii")).decode("ascii"))+ except (ValueError, UnicodeDecodeError):+ return 0++def _list_rules(data):prefix = data.get("NamePrefix", "")bus = data.get("EventBusName", "default")+ # AWS spec: ListRules supports NextToken + Limit (1..100, default 100).+ limit = int(data.get("Limit", 100))+ if limit < 1 or limit > 100:+ limit = 100rules = []for key, r in _rules.items():if r.get("EventBusName", "default") != bus:@@ -472,7 +509,13 @@ def _list_rules(data):if prefix and not r["Name"].startswith(prefix):continuerules.append(_rule_out(r))- return json_response({"Rules": rules})+ rules.sort(key=lambda x: x["Name"])+ start = _opaque_offset_decode(data.get("NextToken", ""))+ page = rules[start:start + limit]+ resp = {"Rules": page}+ if start + limit < len(rules):+ resp["NextToken"] = _opaque_offset_encode(start + limit)+ return json_response(resp)def _describe_rule(data):@@ -518,6 +561,11 @@ def _rule_out(rule):out["Description"] = rule["Description"]if rule.get("RoleArn"):out["RoleArn"] = rule["RoleArn"]+ # AWS spec members on DescribeRule/RuleResponse — emit when populated.+ if rule.get("ManagedBy"):+ out["ManagedBy"] = rule["ManagedBy"]+ if rule.get("CreatedBy"):+ out["CreatedBy"] = rule["CreatedBy"]return out@@ -585,16 +633,11 @@ def _list_rule_names_by_target(data):matched.append(_rules[key]["Name"])matched = sorted(set(matched))- start = 0- if next_token:- try:- start = int(next_token)- except ValueError:- start = 0+ start = _opaque_offset_decode(next_token)page = matched[start:start + limit]resp = {"RuleNames": page}if start + limit < len(matched):- resp["NextToken"] = str(start + limit)+ resp["NextToken"] = _opaque_offset_encode(start + limit)return json_response(resp)@@ -648,11 +691,23 @@ def _normalize_bus_name(name):def _put_events(data):entries = data.get("Entries", [])+ # AWS spec: PutEvents.Entries list min=1 max=10. Real AWS rejects with+ # ValidationException; matching that here so SDKs see the same constraint.+ if len(entries) > 10:+ return error_response_json(+ "ValidationException",+ "1 validation error detected: Value '%d' at 'entries' failed to satisfy constraint: "+ "Member must have length less than or equal to 10" % len(entries),+ 400,+ )results = []for entry in entries:event_id = new_uuid()bus_name = _normalize_bus_name(entry.get("EventBusName", "default"))- event_time = _now_ts()+ # AWS Time is a timestamp shape; ministack convention is int epoch seconds+ # (Java SDK v2 chokes on floats). Persisted in the event_record so+ # archive replay also dispatches the int form.+ event_time = int(_now_ts())event_record = {"EventId": event_id,@@ -764,13 +819,32 @@ def _matches_detail(detail, pattern):if not isinstance(pattern, dict):return Truefor key, expected in pattern.items():- actual = detail.get(key)+ present = isinstance(detail, dict) and key in detail+ actual = detail.get(key) if isinstance(detail, dict) else Noneif isinstance(expected, list):- if actual is None:+ # AWS content-filter: ``[{"exists": true|false}]`` is evaluated+ # against key presence/absence, NOT against the value, so an+ # absent key must NOT short-circuit to False before that check.+ exists_filters = [+ item for item in expected+ if isinstance(item, dict) and "exists" in item+ ]+ if exists_filters:+ if any(item.get("exists") is True for item in exists_filters) and present:+ continue+ if any(item.get("exists") is False for item in exists_filters) and not present:+ continue+ # No exists branch matched and there are no value-level filters+ # left to try — treat as no match.+ if all(isinstance(item, dict) and "exists" in item for item in expected):+ return False+ if not present:return Falseif isinstance(actual, (str, int, float, bool)):matched = Falsefor item in expected:+ if isinstance(item, dict) and "exists" in item:+ continue # already handled aboveif isinstance(item, dict):matched = matched or _matches_content_filter(actual, item)elif actual == item or str(actual) == str(item):@@ -1365,9 +1439,11 @@ def _deactivate_event_source(data):def _describe_event_source(data):name = data.get("Name", "")+ # AWS EventSourceState enum: PENDING | ACTIVE | DELETED. "ENABLED" is not+ # a valid value (Java/Go SDK v2 strict enum parsers reject it).return json_response({"Name": name,- "State": "ENABLED",+ "State": "ACTIVE","Arn": f"arn:aws:events:{get_region()}::event-source/{name}" if name else "",})@@ -1767,12 +1843,117 @@ def _cron_field(field: str, lo: int, hi: int, names: dict | None = None) -> frozreturn frozenset(result)+def _last_day_of_month(year: int, month: int) -> int:+ return calendar.monthrange(year, month)[1]+++def _last_weekday_of_month(year: int, month: int) -> int:+ """Day-of-month of the last Mon-Fri (used by AWS cron LW)."""+ last = _last_day_of_month(year, month)+ for d in range(last, 0, -1):+ if datetime(year, month, d).isoweekday() <= 5:+ return d+ return 1 # unreachable for any real month+++def _nearest_weekday(year: int, month: int, target_day: int) -> int:+ """AWS ``<n>W``: weekday nearest to ``target_day``, never crossing month boundary."""+ last = _last_day_of_month(year, month)+ target_day = min(max(target_day, 1), last)+ iso = datetime(year, month, target_day).isoweekday()+ if iso <= 5:+ return target_day+ if iso == 6: # Saturday → Friday (back 1) unless that crosses month start+ return target_day - 1 if target_day - 1 >= 1 else target_day + 2+ return target_day + 1 if target_day + 1 <= last else target_day - 2 # Sunday → Monday+++def _parse_dom_field(field: str) -> dict | None:+ """Parse AWS cron DoM field. Returns dict with ``days`` set + ``last`` / ``last_weekday`` /+ ``weekday_of`` markers for L, LW, and ``<n>W`` operators. ``None`` on invalid input."""+ if field in ("*", "?"):+ return {"days": frozenset(range(1, 32)), "last": False, "last_weekday": False, "weekday_of": []}+ days: set[int] = set()+ last = False+ last_weekday = False+ weekday_of: list[int] = []+ for part in field.upper().split(","):+ if part == "L":+ last = True+ elif part == "LW":+ last_weekday = True+ elif part.endswith("W"):+ try:+ n = int(part[:-1])+ except ValueError:+ return None+ if not 1 <= n <= 31:+ return None+ weekday_of.append(n)+ else:+ try:+ days.update(_cron_field(part, 1, 31))+ except (ValueError, KeyError):+ return None+ return {"days": frozenset(days), "last": last, "last_weekday": last_weekday, "weekday_of": weekday_of}+++def _parse_dow_field(field: str) -> dict | None:+ """Parse AWS cron DoW field. Returns dict with ``days`` set + ``last_of`` (``<n>L`` = last+ <n> of month) and ``nth`` (``<n>#<k>`` = kth <n> of month). ``None`` on invalid input.+ AWS DoW: 1=SUN..7=SAT."""+ if field in ("*", "?"):+ return {"days": frozenset(range(1, 8)), "last_of": [], "nth": []}+ days: set[int] = set()+ last_of: list[int] = []+ nth: list[tuple[int, int]] = []++ def _resolve_dow(tok: str) -> int | None:+ u = tok.upper()+ if u in _DOW_NAMES:+ return _DOW_NAMES[u]+ try:+ v = int(u)+ except ValueError:+ return None+ return v if 1 <= v <= 7 else None++ for part in field.upper().split(","):+ if "#" in part:+ day_tok, sep, k_tok = part.partition("#")+ try:+ k = int(k_tok)+ except ValueError:+ return None+ n = _resolve_dow(day_tok)+ if n is None or not 1 <= k <= 5:+ return None+ nth.append((n, k))+ elif part.endswith("L") and part != "L":+ n = _resolve_dow(part[:-1])+ if n is None:+ return None+ last_of.append(n)+ elif part == "L":+ # Bare ``L`` in DoW is "Saturday" per AWS (== 7). Real AWS accepts it.+ last_of.append(7)+ else:+ try:+ days.update(_cron_field(part, 1, 7, _DOW_NAMES))+ except (ValueError, KeyError):+ return None+ return {"days": frozenset(days), "last_of": last_of, "nth": nth}++def _parse_cron_fields(expr: str):"""Parse AWS cron(Min Hr DoM Mon DoW Year) into expanded field sets, or return None.Returns an 8-tuple:- (min_set, hr_set, dom_set, mon_set, dow_set, yr_set_or_none, dom_raw, dow_raw)- dom_raw / dow_raw preserve the original token so '?' semantics can be applied.+ (min_set, hr_set, dom_struct, mon_set, dow_struct, yr_set_or_none, dom_raw, dow_raw)+ ``dom_struct`` / ``dow_struct`` are dicts (see ``_parse_dom_field`` / ``_parse_dow_field``)+ so ``L`` / ``W`` / ``#`` operators that depend on the actual date can be evaluated at+ match time. ``dom_raw`` / ``dow_raw`` preserve the original token for the AWS ``?``+ mutual-exclusion rule."""m = re.match(r"^cron\((.+)\)$", expr.strip())if not m:@@ -1781,28 +1962,62 @@ def _parse_cron_fields(expr: str):if len(parts) != 6:return Nonemin_f, hr_f, dom_f, mon_f, dow_f, yr_f = parts+ # AWS rule: exactly one of DoM and DoW must be '?'. Both non-'?' is invalid.+ if dom_f != "?" and dow_f != "?":+ return Nonetry:+ dom_struct = _parse_dom_field(dom_f)+ dow_struct = _parse_dow_field(dow_f)+ if dom_struct is None or dow_struct is None:+ return Nonereturn (_cron_field(min_f, 0, 59),_cron_field(hr_f, 0, 23),- _cron_field(dom_f, 1, 31),+ dom_struct,_cron_field(mon_f, 1, 12, _MONTH_NAMES),- _cron_field(dow_f, 1, 7, _DOW_NAMES),+ dow_struct,_cron_field(yr_f, 1970, 2199) if yr_f not in ("*", "?") else None,- dom_f, # raw token — preserved for '?' mutual-exclusion logic+ dom_f,dow_f,)except (ValueError, KeyError):return None+def _dom_matches(dom_struct: dict, dt: datetime) -> bool:+ if dt.day in dom_struct["days"]:+ return True+ if dom_struct["last"] and dt.day == _last_day_of_month(dt.year, dt.month):+ return True+ if dom_struct["last_weekday"] and dt.day == _last_weekday_of_month(dt.year, dt.month):+ return True+ for n in dom_struct["weekday_of"]:+ if dt.day == _nearest_weekday(dt.year, dt.month, n):+ return True+ return False+++def _dow_matches(dow_struct: dict, dt: datetime) -> bool:+ aws_dow = (dt.isoweekday() % 7) + 1+ if aws_dow in dow_struct["days"]:+ return True+ last = _last_day_of_month(dt.year, dt.month)+ for n in dow_struct["last_of"]:+ if aws_dow == n and dt.day + 7 > last:+ return True+ for n, k in dow_struct["nth"]:+ if aws_dow == n and (dt.day - 1) // 7 + 1 == k:+ return True+ return False++def _cron_next_fire(fields, after_dt: datetime) -> datetime | None:"""Return the first datetime >= (after_dt + 1 min) that satisfies the cron fields.Uses forward-walking with jumps so sparse schedules (monthly, yearly) don'titerate every minute. Returns None if no match is found within 4 years."""- min_s, hr_s, dom_s, mon_s, dow_s, yr_s, dom_raw, dow_raw = fields+ min_s, hr_s, dom_struct, mon_s, dow_struct, yr_s, dom_raw, dow_raw = fieldsdt = after_dt.replace(second=0, microsecond=0) + timedelta(minutes=1)if dt.tzinfo is None:dt = dt.replace(tzinfo=timezone.utc)@@ -1821,16 +2036,13 @@ def _cron_next_fire(fields, after_dt: datetime) -> datetime | None:else:dt = dt.replace(year=dt.year + 1, month=min(mon_s), day=1, hour=0, minute=0)continue- # DoM / DoW: '?' means "don't use this field" (AWS mutual-exclusion rule).- # Convert Python isoweekday (1=MON…7=SUN) → AWS dow (1=SUN…7=SAT):- # aws_dow = (isoweekday % 7) + 1- aws_dow = (dt.isoweekday() % 7) + 1+ # AWS '?' rule: exactly one of DoM/DoW is '?'. The non-'?' field gates the day,+ # supporting L (last day), <n>W (nearest weekday), <n>L (last <n> of month),+ # and <n>#<k> (kth <n> of month).if dom_raw == "?":- day_ok = aws_dow in dow_s- elif dow_raw == "?":- day_ok = dt.day in dom_s+ day_ok = _dow_matches(dow_struct, dt)else:- day_ok = (dt.day in dom_s) or (aws_dow in dow_s)+ day_ok = _dom_matches(dom_struct, dt)if not day_ok:dt = dt.replace(hour=0, minute=0) + timedelta(days=1)continue@@ -1926,10 +2138,20 @@ def _scheduler_loop():logger.exception("EventBridge scheduler tick error")-_scheduler_thread = threading.Thread(- target=_scheduler_loop, daemon=True, name="eb-scheduler"-)-_scheduler_thread.start()+_scheduler_thread: "threading.Thread | None" = None+++def start_scheduler() -> None:+ """Start the eb-scheduler daemon thread (idempotent). Called from the+ gateway lifespan.startup. Kept out of module-import scope so unit tests+ that patch ``_invoke_target`` don't race against a background tick."""+ global _scheduler_thread+ if _scheduler_thread is not None and _scheduler_thread.is_alive():+ return+ _scheduler_thread = threading.Thread(+ target=_scheduler_loop, daemon=True, name="eb-scheduler"+ )+ _scheduler_thread.start()def reset():diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex b7b90bc0..a44a7e6c 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -904,6 +904,8 @@ def _create_function(data: dict):config["Version"] = str(ver_num)_schedule_state_transition(name, _LAMBDA_STATE_TRANSITION_DELAY)+ runtime_or_image = config.get("Runtime") or ("image=" + image_uri if image_uri else "?")+ logger.info("Lambda function created: %s (%s)", name, runtime_or_image)return json_response(config, 201)diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 77790200..86fa2fd5 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -658,6 +658,7 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):if S3_PERSIST:os.makedirs(os.path.join(DATA_DIR, name), exist_ok=True)+ logger.info("S3 bucket created: %s%s", name, f" (region={region})" if region else "")return 200, {"Location": f"/{name}"}, b""diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex 187e8aad..adf3e103 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -217,6 +217,7 @@ def _create_topic(params):i += 1_topics[arn] = topic+ logger.info("SNS topic created: %s%s", name, " (FIFO)" if is_fifo else "")return _xml(200, "CreateTopicResponse",f"<CreateTopicResult><TopicArn>{arn}</TopicArn></CreateTopicResult>")diff --git a/ministack/services/sqs.py b/ministack/services/sqs.pyindex 683bd7b9..c8fb7aaa 100644--- a/ministack/services/sqs.py+++ b/ministack/services/sqs.py@@ -230,6 +230,7 @@ def _act_create_queue(data: dict, _u: str) -> dict:_queues[url] = q_queue_name_to_url[name] = url+ logger.info("SQS queue created: %s%s", name, " (FIFO)" if is_fifo else "")return {"QueueUrl": url}diff --git a/pyproject.toml b/pyproject.tomlindex 238959e0..50a4744a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.3.24"+version = "1.3.25"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex c5ebca7b..5751fb52 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -1220,7 +1220,7 @@ class _WSClient:header = struct.pack("!BBQ", 0x81, 0x80 | 127, length)self._sock.sendall(header + mask + masked)- def recv(self, timeout: float = 3.0) -> str | None:+ def recv(self, timeout: float = 15.0) -> str | None:"""Return the next text or binary frame's payload as a string."""self._sock.settimeout(timeout)try:@@ -1485,7 +1485,7 @@ def test_ws_post_to_connection_from_management_api(apigw, lam):url, data=b"server-push-payload", method="POST",headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},)- r = urllib.request.urlopen(req, timeout=5)+ r = urllib.request.urlopen(req, timeout=30)assert r.status == 200pushed = ws.recv(timeout=3)@@ -1511,7 +1511,7 @@ def test_ws_get_connection_returns_metadata(apigw, lam):url, method="GET",headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},)- r = urllib.request.urlopen(req, timeout=5)+ r = urllib.request.urlopen(req, timeout=30)meta = json.loads(r.read())# Int epoch seconds, per ministack JSON timestamp convention.assert isinstance(meta["ConnectedAt"], int)@@ -1538,7 +1538,7 @@ def test_ws_delete_connection_closes_socket(apigw, lam):url, method="DELETE",headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},)- r = urllib.request.urlopen(req, timeout=5)+ r = urllib.request.urlopen(req, timeout=30)assert r.status in (200, 204)# Give the server a moment to close, then subsequent recv returns None.@@ -1560,7 +1560,7 @@ def test_ws_post_to_unknown_connection_returns_410(apigw, lam):headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},)with pytest.raises(urllib.error.HTTPError) as exc_info:- urllib.request.urlopen(req, timeout=5)+ urllib.request.urlopen(req, timeout=30)assert exc_info.value.code == 410@@ -1718,7 +1718,7 @@ def test_apigwv2_path_based_execute_api_http(apigw, lam):import urllib.requesturl = f"http://localhost:{_EXECUTE_PORT}/_aws/execute-api/{http_api_id}/prod/hello"- r = urllib.request.urlopen(url, timeout=5)+ r = urllib.request.urlopen(url, timeout=30)assert r.status == 200payload = json.loads(r.read())assert payload["eventType"] == "MESSAGE" or payload.get("action") == "GET /hello" or "hello" in str(payload)@@ -1763,7 +1763,7 @@ def test_apigwv1_path_based_restapi_legacy_user_request(apigw_v1, lam):apigw_v1.create_deployment(restApiId=api_id, stageName="prod")url = f"http://localhost:{_EXECUTE_PORT}/restapis/{api_id}/prod/_user_request_/hello"- r = urllib.request.urlopen(url, timeout=5)+ r = urllib.request.urlopen(url, timeout=30)assert r.status == 200@@ -1854,7 +1854,7 @@ def handler(event, context):url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/live/hello"req = urllib.request.Request(url)req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")- r = urllib.request.urlopen(req, timeout=5)+ r = urllib.request.urlopen(req, timeout=30)assert r.status == 200assert r.read() == b"hello-from-alias"@@ -1888,7 +1888,7 @@ def test_apigwv2_cors_preflight_echoes_configured_origin(apigw):req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")req.add_header("Origin", "http://localhost:3000")req.add_header("Access-Control-Request-Method", "GET")- r = urllib.request.urlopen(req, timeout=5)+ r = urllib.request.urlopen(req, timeout=30)assert r.status == 204assert r.headers["Access-Control-Allow-Origin"] == "http://localhost:3000"assert r.headers["Access-Control-Allow-Credentials"] == "true"@@ -1913,7 +1913,7 @@ def test_apigwv2_cors_preflight_denies_non_allowlisted_origin(apigw):req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")req.add_header("Origin", "http://evil.example.com")with pytest.raises(urllib.error.HTTPError) as exc_info:- urllib.request.urlopen(req, timeout=5)+ urllib.request.urlopen(req, timeout=30)assert exc_info.value.code == 403@@ -1929,7 +1929,7 @@ def test_apigwv2_cors_preflight_403_when_no_configuration(apigw):req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")req.add_header("Origin", "http://localhost:3000")with pytest.raises(urllib.error.HTTPError) as exc_info:- urllib.request.urlopen(req, timeout=5)+ urllib.request.urlopen(req, timeout=30)assert exc_info.value.code == 403@@ -1957,7 +1957,7 @@ def test_apigwv2_default_stage_serves_from_root(apigw, lam):url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/api/hello"req = urllib.request.Request(url)req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")- r = urllib.request.urlopen(req, timeout=5)+ r = urllib.request.urlopen(req, timeout=30)assert r.status == 200@@ -1982,7 +1982,7 @@ def test_apigwv2_named_stage_still_requires_prefix(apigw, lam):url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/live/api/hello"req = urllib.request.Request(url)req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")- r = urllib.request.urlopen(req, timeout=5)+ r = urllib.request.urlopen(req, timeout=30)assert r.status == 200@@ -2013,7 +2013,7 @@ def test_apigwv2_integration_wrapped_function_arn(apigw, lam):req = urllib.request.Request(f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/hello")req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")- r = urllib.request.urlopen(req, timeout=5)+ r = urllib.request.urlopen(req, timeout=30)assert r.status == 200assert r.read() == b"wrapped-plain"@@ -2043,7 +2043,7 @@ def test_apigwv2_integration_wrapped_alias_arn(apigw, lam):req = urllib.request.Request(f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/hello")req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")- r = urllib.request.urlopen(req, timeout=5)+ r = urllib.request.urlopen(req, timeout=30)assert r.status == 200assert r.read() == b"wrapped-alias"diff --git a/tests/test_appsync_dns_defaults.py b/tests/test_appsync_dns_defaults.pydeleted file mode 100644index bd3ab58f..00000000--- a/tests/test_appsync_dns_defaults.py+++ /dev/null@@ -1,60 +0,0 @@-"""Unit tests for AppSync Events ``dns`` defaults (no live MiniStack)."""--from __future__ import annotations--import asyncio--from ministack.core.responses import set_request_region---def test_default_dns_localhost_with_region(monkeypatch):- monkeypatch.delenv("APPSYNC_EVENTS_HTTP_HOST_TEMPLATE", raising=False)- monkeypatch.delenv("APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE", raising=False)- monkeypatch.setenv("MINISTACK_HOST", "localhost")- monkeypatch.setenv("GATEWAY_PORT", "4566")- set_request_region("us-east-1")-- from ministack.services.appsync_events import _default_dns_for_api-- d = _default_dns_for_api("abc123")- assert d["HTTP"] == "abc123.appsync-api.us-east-1.localhost:4566"- assert d["REALTIME"] == "abc123.appsync-realtime-api.us-east-1.localhost:4566"---def test_dns_templates_override_when_both_set(monkeypatch):- monkeypatch.setenv(- "APPSYNC_EVENTS_HTTP_HOST_TEMPLATE",- "{api_id}.appsync-api.custom:{port}",- )- monkeypatch.setenv(- "APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE",- "{api_id}.appsync-realtime-api.custom:{port}",- )- monkeypatch.setenv("GATEWAY_PORT", "8080")- set_request_region("eu-west-2")-- from ministack.services.appsync_events import _default_dns_for_api-- d = _default_dns_for_api("x")- assert d["HTTP"] == "x.appsync-api.custom:8080"- assert d["REALTIME"] == "x.appsync-realtime-api.custom:8080"---def test_appsync_events_service_hosts_are_not_s3_virtual_hosts():- from ministack.app import _handle_s3_vhost_request-- for host in (- "appsync-api.eu-west-2.localhost:4566",- "appsync-realtime-api.eu-west-2.localhost:4566",- ):- result = asyncio.run(- _handle_s3_vhost_request(- host,- "/v2/apis",- "GET",- {"host": host},- b"",- {},- )- )- assert result is Nonediff --git a/tests/test_appsync_events.py b/tests/test_appsync_events.pyindex a4d334fc..bced12e1 100644--- a/tests/test_appsync_events.py+++ b/tests/test_appsync_events.py@@ -10,6 +10,7 @@ Covers:- WebSocket publish frame (``publish_success`` + fan-out to peers).- Server-pushed ``ka`` keep-alive frames.- Channel path regex validation (1..5 segments, alphanumeric + dash).+ - DNS defaults for {apiId}.appsync-(api|realtime-api) hosts.Uses a stdlib WebSocket client (no new runtime deps)."""@@ -786,9 +787,12 @@ def test_publish_rejects_segment_with_bad_chars(api):def test_subscribe_rejects_invalid_channel_path(api):+ # Underscores are rejected by the AWS channel-segment grammar+ # (alphanumerics + dash only). Leading slash is OPTIONAL per AWS spec,+ # so "default/foo" without one is valid; pick an actually-bad channel.ws = _open_subscriber(api)try:- ws.send_json({"type": "subscribe", "id": "sub-bad", "channel": "default/no-leading-slash"})+ ws.send_json({"type": "subscribe", "id": "sub-bad", "channel": "/default/bad_seg"})err = _drain_until(ws, lambda f: f.get("type") == "subscribe_error", timeout=2.0)assert err is not Noneassert err["id"] == "sub-bad"@@ -883,8 +887,8 @@ def test_http_publish_invokes_lambda_authorizer(monkeypatch):calls = []- def _fake_invoke(arn, operation, channel, authorization_token):- calls.append((arn, operation, channel, authorization_token))+ def _fake_invoke(arn, api_id_arg, operation, channel, namespace, authorization_token, request_headers):+ calls.append((arn, api_id_arg, operation, channel, namespace, authorization_token))return authorization_token == "allow", {"tenant": "local"}monkeypatch.setattr(ae, "_events_authorizer_invoke", _fake_invoke)@@ -895,9 +899,72 @@ def test_http_publish_invokes_lambda_authorizer(monkeypatch):allowed = asyncio.run(ae._publish(api_id, {"authorization": "allow"}, publish_body))assert allowed[0] == 200+ # AWS Lambda authorizer payload uses EVENT_PUBLISH (per the AppSync Events spec).assert calls[-1] == ("arn:aws:lambda:us-east-1:000000000000:function:authz",- "publish",+ api_id,+ ae.EVENT_PUBLISH,"/default/room",+ "default","allow",)++++# ---------------------------------------------------------------------------+# DNS defaults — unit tests for the {api_id}.appsync-(api|realtime-api) hosts+# ---------------------------------------------------------------------------+from ministack.core.responses import set_request_region+++def test_default_dns_localhost_with_region(monkeypatch):+ monkeypatch.delenv("APPSYNC_EVENTS_HTTP_HOST_TEMPLATE", raising=False)+ monkeypatch.delenv("APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE", raising=False)+ monkeypatch.setenv("MINISTACK_HOST", "localhost")+ monkeypatch.setenv("GATEWAY_PORT", "4566")+ set_request_region("us-east-1")++ from ministack.services.appsync_events import _default_dns_for_api++ d = _default_dns_for_api("abc123")+ assert d["HTTP"] == "abc123.appsync-api.us-east-1.localhost:4566"+ assert d["REALTIME"] == "abc123.appsync-realtime-api.us-east-1.localhost:4566"+++def test_dns_templates_override_when_both_set(monkeypatch):+ monkeypatch.setenv(+ "APPSYNC_EVENTS_HTTP_HOST_TEMPLATE",+ "{api_id}.appsync-api.custom:{port}",+ )+ monkeypatch.setenv(+ "APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE",+ "{api_id}.appsync-realtime-api.custom:{port}",+ )+ monkeypatch.setenv("GATEWAY_PORT", "8080")+ set_request_region("eu-west-2")++ from ministack.services.appsync_events import _default_dns_for_api++ d = _default_dns_for_api("x")+ assert d["HTTP"] == "x.appsync-api.custom:8080"+ assert d["REALTIME"] == "x.appsync-realtime-api.custom:8080"+++def test_appsync_events_service_hosts_are_not_s3_virtual_hosts():+ from ministack.app import _handle_s3_vhost_request++ for host in (+ "appsync-api.eu-west-2.localhost:4566",+ "appsync-realtime-api.eu-west-2.localhost:4566",+ ):+ result = asyncio.run(+ _handle_s3_vhost_request(+ host,+ "/v2/apis",+ "GET",+ {"host": host},+ b"",+ {},+ )+ )+ assert result is Nonediff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.pyindex 27281dfd..df7e56c1 100644--- a/tests/test_eventbridge.py+++ b/tests/test_eventbridge.py@@ -409,7 +409,8 @@ def test_eventbridge_endpoints_and_partner_stubs(eb):eb.activate_event_source(Name="aws.partner/saas/foo")eb.deactivate_event_source(Name="aws.partner/saas/foo")src = eb.describe_event_source(Name="aws.partner/saas/foo")- assert src["State"] == "ENABLED"+ # AWS EventSourceState enum: PENDING / ACTIVE / DELETED. (Was "ENABLED" — invalid.)+ assert src["State"] == "ACTIVE"r = eb.create_partner_event_source(Name="saas.src", Account="111111111111")assert "EventSourceArn" in r@@ -1232,14 +1233,27 @@ def test_scheduler_parse_rate_seconds(expr, expected):@_pytest.fixture()def isolated_scheduler():- """Save and restore scheduler module state so unit tests don't bleed."""+ """Save and restore scheduler module state so unit tests don't bleed.++ Also installs a MagicMock as ``_invoke_target`` for the **entire test+ duration** (yielded as the fixture value). This is wider than a+ ``with patch(...)`` block: any concurrent caller (the eb-scheduler daemon+ if it's running, an in-process ASGI lifespan, etc.) hits the mock too,+ so tests can assert on call counts without racing.+ """+ from unittest.mock import MagicMock+saved_rules = dict(_eb._rules._data)saved_targets = dict(_eb._targets._data)saved_fired = dict(_eb._rule_last_fired)+ saved_invoke = _eb._invoke_target_eb._rules._data.clear()_eb._targets._data.clear()_eb._rule_last_fired.clear()- yield+ mock_invoke = MagicMock(name="_invoke_target")+ _eb._invoke_target = mock_invoke+ yield mock_invoke+ _eb._invoke_target = saved_invoke_eb._rules._data.clear()_eb._rules._data.update(saved_rules)_eb._targets._data.clear()@@ -1270,21 +1284,18 @@ from unittest.mock import patch as _patchdef test_scheduler_first_sight_initializes_countdown(isolated_scheduler):"""First tick records the timestamp but must NOT dispatch."""_seed_rule()- with _patch("ministack.services.eventbridge._invoke_target") as mock_invoke:- _eb._tick_scheduled_rules()+ _eb._tick_scheduled_rules()assert _STATE_KEY in _eb._rule_last_fired- mock_invoke.assert_not_called()+ isolated_scheduler.assert_not_called()def test_scheduler_fires_after_interval(isolated_scheduler):"""Tick dispatches when last-fired is older than the rule interval."""_seed_rule()_eb._rule_last_fired[_STATE_KEY] = _eb._now_ts() - 65 # 65 s ago > 60 s interval- with _patch("ministack.services.eventbridge._invoke_target") as mock_invoke:- _eb._tick_scheduled_rules()- mock_invoke.assert_called_once()- _, kwargs = mock_invoke.call_args- target_arg = mock_invoke.call_args[0][0]+ _eb._tick_scheduled_rules()+ isolated_scheduler.assert_called_once()+ target_arg = isolated_scheduler.call_args[0][0]assert target_arg["Id"] == "t1"@@ -1292,18 +1303,16 @@ def test_scheduler_skips_rule_before_interval(isolated_scheduler):"""Tick must NOT dispatch when interval hasn't elapsed."""_seed_rule()_eb._rule_last_fired[_STATE_KEY] = _eb._now_ts() - 10 # only 10 s ago- with _patch("ministack.services.eventbridge._invoke_target") as mock_invoke:- _eb._tick_scheduled_rules()- mock_invoke.assert_not_called()+ _eb._tick_scheduled_rules()+ isolated_scheduler.assert_not_called()def test_scheduler_skips_disabled_rule(isolated_scheduler):"""Disabled rules must never be dispatched even if past interval."""_seed_rule(state="DISABLED")_eb._rule_last_fired[_STATE_KEY] = _eb._now_ts() - 120- with _patch("ministack.services.eventbridge._invoke_target") as mock_invoke:- _eb._tick_scheduled_rules()- mock_invoke.assert_not_called()+ _eb._tick_scheduled_rules()+ isolated_scheduler.assert_not_called()@_pytest.mark.parametrize("expr,valid", [@@ -1312,10 +1321,20 @@ def test_scheduler_skips_disabled_rule(isolated_scheduler):("cron(0 0 ? * MON-FRI *)", True), # midnight Mon–Fri("cron(30 6 1 * ? *)", True), # 06:30 on 1st of each month("cron(0 0 1 1 ? 2030)", True), # specific year+ ("cron(0 0 L * ? *)", True), # last day of every month+ ("cron(0 0 LW * ? *)", True), # last weekday of every month+ ("cron(0 12 15W * ? *)", True), # nearest weekday to the 15th+ ("cron(0 12 ? * 6L *)", True), # last Friday of every month (AWS Fri=6)+ ("cron(0 9 ? * 2#1 *)", True), # first Monday of every month (AWS Mon=2)("rate(1 minute)", False), # not a cron expression("", False),("cron(0 12 * * *)", False), # 5 fields — missing Year("cron()", False),+ ("cron(0 12 * * * *)", False), # both DoM and DoW non-'?' — AWS rejects+ ("cron(0 12 1 * MON *)", False), # both DoM and DoW non-'?' — AWS rejects+ ("cron(0 12 32W * ? *)", False), # day-of-month out of range in <n>W+ ("cron(0 12 ? * 8L *)", False), # AWS DoW only goes 1..7+ ("cron(0 12 ? * 6#6 *)", False), # nth occurrence only valid 1..5])def test_scheduler_parse_cron_fields_validity(expr, valid):result = _eb._parse_cron_fields(expr)@@ -1349,10 +1368,9 @@ def test_scheduler_cron_next_fire_weekday():def test_scheduler_cron_first_sight_initializes_countdown(isolated_scheduler):"""First tick of a cron() rule records the timestamp but must NOT dispatch."""_seed_rule(schedule="cron(0 12 * * ? *)")- with _patch("ministack.services.eventbridge._invoke_target") as mock_invoke:- _eb._tick_scheduled_rules()+ _eb._tick_scheduled_rules()assert _STATE_KEY in _eb._rule_last_fired- mock_invoke.assert_not_called()+ isolated_scheduler.assert_not_called()def test_scheduler_cron_fires_after_scheduled_time(isolated_scheduler):@@ -1360,9 +1378,8 @@ def test_scheduler_cron_fires_after_scheduled_time(isolated_scheduler):_seed_rule(schedule="cron(0 * * * ? *)") # every hour on the hour# last_fired 2 hours ago → next occurrence is ~1 hour ago → should fire now_eb._rule_last_fired[_STATE_KEY] = _eb._now_ts() - 7200- with _patch("ministack.services.eventbridge._invoke_target") as mock_invoke:- _eb._tick_scheduled_rules()- mock_invoke.assert_called_once()+ _eb._tick_scheduled_rules()+ isolated_scheduler.assert_called_once()def test_scheduler_cron_skips_before_scheduled_time(isolated_scheduler):@@ -1370,9 +1387,70 @@ def test_scheduler_cron_skips_before_scheduled_time(isolated_scheduler):_seed_rule(schedule="cron(0 * * * ? *)") # every hour on the hour# last_fired 10 s ago → next occurrence is ~59m50s from now → must not fire_eb._rule_last_fired[_STATE_KEY] = _eb._now_ts() - 10- with _patch("ministack.services.eventbridge._invoke_target") as mock_invoke:- _eb._tick_scheduled_rules()- mock_invoke.assert_not_called()+ _eb._tick_scheduled_rules()+ isolated_scheduler.assert_not_called()+++def test_scheduler_cron_last_day_of_month():+ """cron(0 0 L * ? *): next fire after Jan 30 is Jan 31 (last day)."""+ from datetime import datetime as _dt, timezone as _tz+ fields = _eb._parse_cron_fields("cron(0 0 L * ? *)")+ after = _dt(2024, 1, 30, 12, 0, tzinfo=_tz.utc)+ # Jan has 31 days+ assert _eb._cron_next_fire(fields, after) == _dt(2024, 1, 31, 0, 0, tzinfo=_tz.utc)+ # Feb 2024 (leap year) has 29 days+ after = _dt(2024, 2, 1, 0, 0, tzinfo=_tz.utc)+ assert _eb._cron_next_fire(fields, after) == _dt(2024, 2, 29, 0, 0, tzinfo=_tz.utc)+++def test_scheduler_cron_last_weekday_of_month():+ """cron(0 0 LW * ? *): last Mon-Fri of the month."""+ from datetime import datetime as _dt, timezone as _tz+ fields = _eb._parse_cron_fields("cron(0 0 LW * ? *)")+ # March 2024: 31st = Sunday → last weekday is Fri Mar 29.+ after = _dt(2024, 3, 1, 0, 0, tzinfo=_tz.utc)+ assert _eb._cron_next_fire(fields, after) == _dt(2024, 3, 29, 0, 0, tzinfo=_tz.utc)+++def test_scheduler_cron_nearest_weekday():+ """cron(0 12 15W * ? *): nearest Mon-Fri to the 15th, never crossing month."""+ from datetime import datetime as _dt, timezone as _tz+ fields = _eb._parse_cron_fields("cron(0 12 15W * ? *)")+ # Jan 15 2024 = Monday → fires on the 15th itself.+ assert _eb._cron_next_fire(fields, _dt(2024, 1, 14, 0, 0, tzinfo=_tz.utc)) == _dt(2024, 1, 15, 12, 0, tzinfo=_tz.utc)+ # Jun 15 2024 = Saturday → fires on Friday Jun 14.+ assert _eb._cron_next_fire(fields, _dt(2024, 6, 1, 0, 0, tzinfo=_tz.utc)) == _dt(2024, 6, 14, 12, 0, tzinfo=_tz.utc)+ # Sep 15 2024 = Sunday → fires on Monday Sep 16.+ assert _eb._cron_next_fire(fields, _dt(2024, 9, 1, 0, 0, tzinfo=_tz.utc)) == _dt(2024, 9, 16, 12, 0, tzinfo=_tz.utc)+++def test_scheduler_cron_last_dow_of_month():+ """cron(0 12 ? * 6L *): last Friday of the month (AWS Friday = 6)."""+ from datetime import datetime as _dt, timezone as _tz+ fields = _eb._parse_cron_fields("cron(0 12 ? * 6L *)")+ # Jan 2024: Fridays are 5, 12, 19, 26 → last is Fri Jan 26.+ assert _eb._cron_next_fire(fields, _dt(2024, 1, 1, 0, 0, tzinfo=_tz.utc)) == _dt(2024, 1, 26, 12, 0, tzinfo=_tz.utc)+ # Mar 2024: Fridays are 1, 8, 15, 22, 29 → last is Fri Mar 29.+ assert _eb._cron_next_fire(fields, _dt(2024, 3, 1, 0, 0, tzinfo=_tz.utc)) == _dt(2024, 3, 29, 12, 0, tzinfo=_tz.utc)+++def test_scheduler_cron_nth_dow_of_month():+ """cron(0 9 ? * 2#1 *): first Monday of every month (AWS Monday = 2)."""+ from datetime import datetime as _dt, timezone as _tz+ fields = _eb._parse_cron_fields("cron(0 9 ? * 2#1 *)")+ # Jan 2024: Mondays are 1, 8, 15, 22, 29 → 1st Monday = Jan 1.+ assert _eb._cron_next_fire(fields, _dt(2023, 12, 31, 0, 0, tzinfo=_tz.utc)) == _dt(2024, 1, 1, 9, 0, tzinfo=_tz.utc)+ # Feb 2024: Mondays are 5, 12, 19, 26 → 1st = Feb 5.+ assert _eb._cron_next_fire(fields, _dt(2024, 1, 2, 0, 0, tzinfo=_tz.utc)) == _dt(2024, 2, 5, 9, 0, tzinfo=_tz.utc)+++def test_scheduler_validate_rejects_dom_and_dow_both_non_question_mark():+ """PutRule must reject cron expressions where both DoM and DoW are non-'?' (AWS rule)."""+ assert _eb._validate_schedule_expression("cron(0 12 * * * *)") is False+ assert _eb._validate_schedule_expression("cron(0 12 1 * MON *)") is False+ # Valid: at least one of DoM/DoW is '?'.+ assert _eb._validate_schedule_expression("cron(0 12 * * ? *)") is True+ assert _eb._validate_schedule_expression("cron(0 12 ? * MON *)") is Truedef test_scheduler_no_error_without_targets(isolated_scheduler):@@ -1380,9 +1458,8 @@ def test_scheduler_no_error_without_targets(isolated_scheduler):_seed_rule()_eb._targets._data[_STATE_KEY] = [] # empty targets list_eb._rule_last_fired[_STATE_KEY] = _eb._now_ts() - 120- with _patch("ministack.services.eventbridge._invoke_target") as mock_invoke:- _eb._tick_scheduled_rules()- mock_invoke.assert_not_called()+ _eb._tick_scheduled_rules()+ isolated_scheduler.assert_not_called()def test_scheduler_reset_clears_last_fired(isolated_scheduler):@@ -1405,9 +1482,8 @@ def test_scheduler_first_sight_with_old_creation_time_fires_immediately(isolated"CreationTime": _eb._now_ts() - 120, # created 2 min ago, interval = 1 min}_eb._targets._data[_STATE_KEY] = list(_DUMMY_TARGET)- with _patch("ministack.services.eventbridge._invoke_target") as mock_invoke:- _eb._tick_scheduled_rules()- mock_invoke.assert_called_once()+ _eb._tick_scheduled_rules()+ isolated_scheduler.assert_called_once()def test_scheduler_first_sight_with_recent_creation_time_waits(isolated_scheduler):@@ -1422,6 +1498,5 @@ def test_scheduler_first_sight_with_recent_creation_time_waits(isolated_schedule"CreationTime": _eb._now_ts() - 5, # created 5s ago, interval = 60s}_eb._targets._data[_STATE_KEY] = list(_DUMMY_TARGET)- with _patch("ministack.services.eventbridge._invoke_target") as mock_invoke:- _eb._tick_scheduled_rules()- mock_invoke.assert_not_called()+ _eb._tick_scheduled_rules()+ isolated_scheduler.assert_not_called()