Skip to content

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

Fix/performance (#309)

Nahuel Nuceraed30df61718a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0141f9f4..3757802f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,28 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [Unreleased]
+
+### Added
+- **EventBridge Scheduler service** — full `scheduler` API: CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource. Supports schedule groups, cascading deletes, name prefix/state filters, and `at()`/`cron()`/`rate()` expressions. 21 tests.
+- **CloudFormation `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup`** — CFN/CDK stacks using EventBridge Scheduler resources now provision correctly and are queryable via the Scheduler API.
+- **CloudFormation `AWS::CodeBuild::Project`** — CDK/Terraform stacks declaring CodeBuild projects now provision correctly. Supports Name, Source, Artifacts, Environment, ServiceRole, Tags, and Fn::GetAtt Arn. Contributed by @AdigaAkhil (#352)
+- **Cognito OAuth2/OIDC managed login UI** — `/oauth2/authorize` serves a browser-based login form, `/oauth2/token` supports authorization_code (with PKCE S256/plain), refresh_token, and client_credentials grants, `/oauth2/userInfo` returns OIDC claims, `/logout` redirects to logout URI. Full hosted UI flow for local development. Contributed by @kjdev (#344)
+- **ECS `ListContainerInstances` and `DescribeContainerInstances`** — stub endpoints return empty results (MiniStack runs tasks directly as Docker containers, no EC2 container instance layer).
+
+### Fixed
+- **DynamoDB CFN StreamSpecification** — CloudFormation DynamoDB tables with `StreamViewType` but no explicit `StreamEnabled` now correctly enable streams. `Fn::GetAtt StreamArn` returns a valid stream ARN. Contributed by @davidtme (#349)
+- **IAM/STS split** — IAM and STS are now separate modules (`iam.py` and `sts.py`), each with standard `handle_request`. Eliminates the `func_name` parameter hack in the lazy loader.
+- **IAM user inline policy persistence** — `PutUserPolicy` data was not included in `get_state()`/`restore_state()`, causing inline policies to be lost on restart with `PERSIST_STATE=1`.
+- **AutoScaling state persistence** — added `get_state()`, `restore_state()`, and `reset()` to autoscaling service. ASG, launch config, policy, hook, scheduled action, and tag state is now persisted and reset correctly.
+- **Health endpoint version** — `/_ministack/health` now returns the real package version instead of hardcoded `3.0.0.dev`.
+
+### Improved
+- **Lazy service imports** — service modules are now loaded on first request instead of at startup. Idle RAM drops from ~59 MB to ~21 MB (64% reduction). Startup time drops from ~1.2s to ~0.5s (2.5x faster). Services that are never called consume zero memory.
+- **Removed pip from Docker image** — pip is no longer present in the final image (security hardening, reduced attack surface).
+
+---
+
## [1.2.18] — 2026-04-15
### Fixed
diff --git a/Dockerfile b/Dockerfile
index d78639c6..50b5c6a0 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -22,7 +22,9 @@ LABEL maintainer="MiniStack" \
description="Local AWS Service Emulator — drop-in LocalStack replacement"
# Upgrade base packages to pick up latest security patches.
-RUN apk upgrade --no-cache && apk add --no-cache nodejs bash && rm -f /usr/bin/wget /bin/wget
+RUN apk upgrade --no-cache && apk add --no-cache nodejs bash && rm -f /usr/bin/wget /bin/wget \
+ && rm -rf /usr/local/lib/python3.12/site-packages/pip* \
+ /usr/local/bin/pip*
WORKDIR /opt/ministack
diff --git a/README.md b/README.md
index 9dae8573..072f5a97 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
<h1 align="center">MiniStack</h1>
<p align="center"><strong>Free, open-source local AWS emulator. Free forever.</strong></p>
-<p align="center">43 AWS services on a single port · Terraform compatible · Real databases · MIT licensed</p>
+<p align="center">40+ AWS services on a single port · Terraform compatible · Real databases · MIT licensed</p>
<p align="center">
<a href="https://github.com/ministackorg/ministack/releases"><img src="https://img.shields.io/github/v/release/ministackorg/ministack" alt="GitHub release"></a>
@@ -26,10 +26,10 @@
LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.
-- **43 AWS services** emulated on a single port (4566)
+- **40+ AWS services** emulated on a single port (4566)
- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK
- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers
-- **Tiny footprint** — ~270MB image, ~45MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM
+- **Tiny footprint** — ~270MB image, ~21MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM
- **Fast startup** — under 2 seconds
- **MIT licensed** — use it, fork it, contribute to it
@@ -450,6 +450,8 @@ subnet = ec2.create_subnet(
| `AWS::AutoScaling::ScalingPolicy` | Policy ARN | Arn, PolicyName |
| `AWS::AutoScaling::LifecycleHook` | Hook name | LifecycleHookName |
| `AWS::AutoScaling::ScheduledAction` | Action ARN | Arn, ScheduledActionName |
+| `AWS::Scheduler::Schedule` | Schedule name | Arn |
+| `AWS::Scheduler::ScheduleGroup` | Group name | Arn |
| `AWS::CloudFormation::WaitCondition` | Condition ID | — |
| `AWS::CloudFormation::WaitConditionHandle` | Handle URL | — |
@@ -480,6 +482,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if
| **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; builds complete immediately with SUCCEEDED status; project and build metadata stored in-memory |
| **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; deployments complete immediately; session-based configuration retrieval with token rotation |
| **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 10 operations; SFTP server and user management; SSH key rotation; LOGICAL home directory mappings to S3; in-memory state |
+| **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported |
---
@@ -687,7 +690,7 @@ Install DuckDB for full Athena SQL compatibility: `pip install ministack[full]`.
When `PERSIST_STATE=1`, MiniStack saves service state to `STATE_DIR` on shutdown and reloads it on startup. Writes are atomic (write-to-tmp then rename) to prevent corruption on crash.
-Services currently supporting persistence: **All 43 services** — API Gateway v1/v2, ALB, ACM, AppConfig, AppSync, Athena, Cloud Map, CloudFront, CloudWatch, CloudWatch Logs, CodeBuild, Cognito, DynamoDB, EC2, ECR, ECS, EFS, ElastiCache, EMR, EventBridge, Firehose, Glue, IAM/STS, Kinesis, KMS, Lambda, RDS, Route 53, S3, Secrets Manager, SES, SES v2, SNS, SQS, SSM, Step Functions, Transfer Family, WAF v2
+Services currently supporting persistence: **All services** — API Gateway v1/v2, ALB, ACM, AppConfig, AppSync, Athena, Cloud Map, CloudFront, CloudWatch, CloudWatch Logs, CodeBuild, Cognito, DynamoDB, EC2, ECR, ECS, EFS, ElastiCache, EMR, EventBridge, EventBridge Scheduler, Firehose, Glue, IAM/STS, Kinesis, KMS, Lambda, RDS, Route 53, S3, Secrets Manager, SES, SES v2, SNS, SQS, SSM, Step Functions, Transfer Family, WAF v2
```bash
docker run -p 4566:4566 \
@@ -750,19 +753,21 @@ MiniStack also sets the standard Lambda runtime environment before the handler m
│ └────────────────┬───────────────────┘ │
│ │ │
│ ┌────────────────────────────────────┐ │
- │ │ Service Handlers │ │
+ │ │ Service Handlers (lazy-loaded) │ │
│ │ │ │
- │ │ S3 SQS SNS DynamoDB │ │
- │ │ Lambda IAM STS Secrets │ │
- │ │ SSM EventBridge Kinesis │ │
- │ │ CW Logs CW Metrics SES SESv2 │ │
- │ │ Step Functions API GW v1/v2 │ │
- │ │ ECS RDS ElastiCache Glue │ │
- │ │ Athena Firehose Route53 │ │
- │ │ Cognito EC2 EMR EBS EFS │ │
- │ │ ALB/ELBv2 ACM WAF v2 │ │
- │ │ CloudFormation KMS ECR │ │
- │ │ CloudFront AppSync │ │
+ │ │ S3 SQS SNS DynamoDB │ │
+ │ │ Lambda IAM STS Secrets │ │
+ │ │ SSM Events Kinesis CW │ │
+ │ │ CW Logs SES SESv2 ACM │ │
+ │ │ Step Functions API GW v1/v2 │ │
+ │ │ ECS RDS ElastiCache Glue │ │
+ │ │ Athena Firehose Route53 │ │
+ │ │ Cognito EC2 EMR EBS EFS │ │
+ │ │ ALB/ELBv2 WAF v2 KMS ECR │ │
+ │ │ CloudFormation CloudFront │ │
+ │ │ AppSync Cloud Map CodeBuild │ │
+ │ │ AutoScaling AppConfig │ │
+ │ │ RDS Data S3 Files Scheduler │ │
│ └────────────────────────────────────┘ │
│ │
│ In-Memory Storage + Optional Docker │
@@ -785,7 +790,7 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (1,207 tests across all 43 services)
+# Run the full test suite (1,300+ tests across all services)
pytest tests/ -v
```
diff --git a/ministack/app.py b/ministack/app.py
index cda9b6ba..dd10c59b 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -24,6 +24,12 @@ from urllib.parse import parse_qs, urlparse
_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
_MINISTACK_PORT = os.environ.get("GATEWAY_PORT", "4566")
+try:
+ from importlib.metadata import version as _pkg_version
+ _VERSION = _pkg_version("ministack")
+except Exception:
+ _VERSION = "dev"
+
# Matches host headers like "{apiId}.execute-api.<host>" or "{apiId}.execute-api.<host>:4566"
_EXECUTE_API_RE = re.compile(
r"^([a-f0-9]{8})\.execute-api\." + re.escape(_MINISTACK_HOST) + r"(?::\d+)?$"
@@ -40,52 +46,57 @@ _S3_VHOST_EXCLUDE_RE = re.compile(r"\.(execute-api|alb|emr|efs|elasticache|s3-co
from ministack.core.persistence import PERSIST_STATE, load_state, save_all
from ministack.core.responses import set_request_account_id
from ministack.core.router import detect_service, extract_access_key_id, extract_account_id, extract_region
-from ministack.services import (
- acm,
- alb,
- apigateway,
- autoscaling,
- apigateway_v1,
- appconfig,
- appsync,
- athena,
- cloudformation,
- cloudwatch,
- cloudwatch_logs,
- cognito,
- dynamodb,
- ec2,
- ecr,
- ecs,
- efs,
- elasticache,
- emr,
- eventbridge,
- firehose,
- glue,
- kinesis,
- kms,
- lambda_svc,
- rds,
- rds_data,
- route53,
- s3,
- secretsmanager,
- ses,
- ses_v2,
- sns,
- sqs,
- ssm,
- stepfunctions,
- waf,
- cloudfront,
- servicediscovery,
- s3files,
- codebuild,
- transfer,
-)
-from ministack.services import iam_sts
-from ministack.services.iam_sts import handle_iam_request, handle_sts_request
+
+# ---------------------------------------------------------------------------
+# Lazy service loader — modules are imported on first request, not at startup.
+# This saves ~20 MB of idle RAM and speeds up boot.
+# ---------------------------------------------------------------------------
+_loaded_modules: dict = {}
+
+
+class _ErrorModule:
+ """Stub returned when a service module fails to import."""
+ def __init__(self, name: str, error: str):
+ self._name = name
+ self._error = error
+
+ async def handle_request(self, method, path, headers, body, query_params):
+ return 500, {"Content-Type": "application/json"}, \
+ json.dumps({"__type": "ServiceUnavailable",
+ "message": f"Service module '{self._name}' failed to load: {self._error}"}).encode()
+
+ def get_state(self):
+ return {}
+
+ def restore_state(self, data):
+ pass
+
+ def load_persisted_state(self, data):
+ pass
+
+ def reset(self):
+ pass
+
+
+def _get_module(name: str):
+ """Import and cache a service module by short name (e.g. 's3', 'lambda_svc')."""
+ mod = _loaded_modules.get(name)
+ if mod is None:
+ try:
+ mod = __import__(f"ministack.services.{name}", fromlist=["handle_request"])
+ except (ModuleNotFoundError, ImportError) as e:
+ logger.warning("Service module failed to load: %s - %s", name, e)
+ mod = _ErrorModule(name, str(e))
+ _loaded_modules[name] = mod
+ return mod
+
+
+def _lazy_handler(module_name: str):
+ """Return a callable that lazily imports module_name and delegates to handle_request."""
+ async def _handler(method, path, headers, body, query_params):
+ mod = _get_module(module_name)
+ return await mod.handle_request(method, path, headers, body, query_params)
+ return _handler
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
logging.basicConfig(
@@ -96,50 +107,51 @@ logging.basicConfig(
logger = logging.getLogger("ministack")
SERVICE_HANDLERS = {
- "s3": s3.handle_request,
- "sqs": sqs.handle_request,
- "cloudformation": cloudformation.handle_request,
- "sns": sns.handle_request,
- "dynamodb": dynamodb.handle_request,
- "lambda": lambda_svc.handle_request,
- "iam": handle_iam_request,
- "sts": handle_sts_request,
- "secretsmanager": secretsmanager.handle_request,
- "logs": cloudwatch_logs.handle_request,
- "ssm": ssm.handle_request,
- "events": eventbridge.handle_request,
- "kinesis": kinesis.handle_request,
- "monitoring": cloudwatch.handle_request,
- "ses": ses.handle_request,
- "acm": acm.handle_request,
- "wafv2": waf.handle_request,
- "states": stepfunctions.handle_request,
- "ecr": ecr.handle_request,
- "ecs": ecs.handle_request,
- "rds": rds.handle_request,
- "elasticache": elasticache.handle_request,
- "glue": glue.handle_request,
- "athena": athena.handle_request,
- "apigateway": apigateway.handle_request,
- "firehose": firehose.handle_request,
- "route53": route53.handle_request,
- "cognito-idp": cognito.handle_request,
- "cognito-identity": cognito.handle_request,
- "ec2": ec2.handle_request,
- "elasticmapreduce": emr.handle_request,
- "elasticloadbalancing": alb.handle_request,
- "elasticfilesystem": efs.handle_request,
- "kms": kms.handle_request,
- "cloudfront": cloudfront.handle_request,
- "codebuild": codebuild.handle_request,
- "transfer": transfer.handle_request,
- "appsync": appsync.handle_request,
- "servicediscovery": servicediscovery.handle_request,
- "s3files": s3files.handle_request,
- "rds-data": rds_data.handle_request,
- "autoscaling": autoscaling.handle_request,
- "appconfig": appconfig.handle_request,
- "appconfigdata": appconfig.handle_request,
+ "s3": _lazy_handler("s3"),
+ "sqs": _lazy_handler("sqs"),
+ "cloudformation": _lazy_handler("cloudformation"),
+ "sns": _lazy_handler("sns"),
+ "dynamodb": _lazy_handler("dynamodb"),
+ "lambda": _lazy_handler("lambda_svc"),
+ "iam": _lazy_handler("iam"),
+ "sts": _lazy_handler("sts"),
+ "secretsmanager": _lazy_handler("secretsmanager"),
+ "logs": _lazy_handler("cloudwatch_logs"),
+ "ssm": _lazy_handler("ssm"),
+ "events": _lazy_handler("eventbridge"),
+ "kinesis": _lazy_handler("kinesis"),
+ "monitoring": _lazy_handler("cloudwatch"),
+ "ses": _lazy_handler("ses"),
+ "acm": _lazy_handler("acm"),
+ "wafv2": _lazy_handler("waf"),
+ "states": _lazy_handler("stepfunctions"),
+ "ecr": _lazy_handler("ecr"),
+ "ecs": _lazy_handler("ecs"),
+ "rds": _lazy_handler("rds"),
+ "elasticache": _lazy_handler("elasticache"),
+ "glue": _lazy_handler("glue"),
+ "athena": _lazy_handler("athena"),
+ "apigateway": _lazy_handler("apigateway"),
+ "firehose": _lazy_handler("firehose"),
+ "route53": _lazy_handler("route53"),
+ "cognito-idp": _lazy_handler("cognito"),
+ "cognito-identity": _lazy_handler("cognito"),
+ "ec2": _lazy_handler("ec2"),
+ "elasticmapreduce": _lazy_handler("emr"),
+ "elasticloadbalancing": _lazy_handler("alb"),
+ "elasticfilesystem": _lazy_handler("efs"),
+ "kms": _lazy_handler("kms"),
+ "cloudfront": _lazy_handler("cloudfront"),
+ "codebuild": _lazy_handler("codebuild"),
+ "transfer": _lazy_handler("transfer"),
+ "appsync": _lazy_handler("appsync"),
+ "servicediscovery": _lazy_handler("servicediscovery"),
+ "s3files": _lazy_handler("s3files"),
+ "rds-data": _lazy_handler("rds_data"),
+ "autoscaling": _lazy_handler("autoscaling"),
+ "appconfig": _lazy_handler("appconfig"),
+ "appconfigdata": _lazy_handler("appconfig"),
+ "scheduler": _lazy_handler("scheduler"),
}
SERVICE_NAME_ALIASES = {
@@ -274,8 +286,7 @@ async def app(scope, receive, send):
if path.startswith("/_ministack/lambda-layers/") and method == "GET":
lp = path.split("/") # ['', '_ministack', 'lambda-layers', name, ver, 'content']
if len(lp) >= 6 and lp[5] == "content" and lp[4].isdigit():
- from ministack.services import lambda_svc
- status, resp_headers, resp_body = lambda_svc.serve_layer_content(lp[3], int(lp[4]))
+ status, resp_headers, resp_body = _get_module("lambda_svc").serve_layer_content(lp[3], int(lp[4]))
await _send_response(send, status, resp_headers, resp_body)
return
@@ -286,36 +297,36 @@ async def app(scope, receive, send):
_pool_id = path.rsplit("/.well-known/jwks.json", 1)[0].lstrip("/")
if _pool_id:
_region = extract_region(headers) or "us-east-1"
- status, resp_headers, resp_body = cognito.well_known_jwks(_pool_id)
+ status, resp_headers, resp_body = _get_module("cognito").well_known_jwks(_pool_id)
await _send_response(send, status, resp_headers, resp_body)
return
elif path.endswith("/.well-known/openid-configuration"):
_pool_id = path.rsplit("/.well-known/openid-configuration", 1)[0].lstrip("/")
if _pool_id:
_region = extract_region(headers) or "us-east-1"
- status, resp_headers, resp_body = cognito.well_known_openid_configuration(_pool_id, _region)
+ status, resp_headers, resp_body = _get_module("cognito").well_known_openid_configuration(_pool_id, _region)
await _send_response(send, status, resp_headers, resp_body)
return
# Cognito OAuth2 / Managed Login UI endpoints
if path == "/oauth2/authorize" and method == "GET":
- status, resp_headers, resp_body = cognito.handle_oauth2_authorize(method, path, headers, query_params)
+ status, resp_headers, resp_body = _get_module("cognito").handle_oauth2_authorize(method, path, headers, query_params)
await _send_response(send, status, resp_headers, resp_body)
return
- if path == "/login" and method == "POST":
- status, resp_headers, resp_body = cognito.handle_login_submit(method, path, headers, body, query_params)
+ if path in ("/oauth2/login", "/login") and method == "POST":
+ status, resp_headers, resp_body = _get_module("cognito").handle_login_submit(method, path, headers, body, query_params)
await _send_response(send, status, resp_headers, resp_body)
return
if path == "/oauth2/token" and method == "POST":
- status, resp_headers, resp_body = cognito.handle_oauth2_token(method, path, headers, body, query_params)
+ status, resp_headers, resp_body = _get_module("cognito").handle_oauth2_token(method, path, headers, body, query_params)
await _send_response(send, status, resp_headers, resp_body)
return
if path in ("/oauth2/userInfo", "/oauth2/userinfo") and method in ("GET", "POST"):
- status, resp_headers, resp_body = cognito.handle_oauth2_userinfo(method, path, headers, body, query_params)
+ status, resp_headers, resp_body = _get_module("cognito").handle_oauth2_userinfo(method, path, headers, body, query_params)
await _send_response(send, status, resp_headers, resp_body)
return
if path == "/logout" and method == "GET":
- status, resp_headers, resp_body = cognito.handle_logout(method, path, headers, query_params)
+ status, resp_headers, resp_body = _get_module("cognito").handle_logout(method, path, headers, query_params)
await _send_response(send, status, resp_headers, resp_body)
return
@@ -380,8 +391,8 @@ async def app(scope, receive, send):
bucket_name = arn.split(":::")[-1].split("/")[0] if ":::" in arn else arn.split("/")[0]
if method == "GET":
- # ListTagsForResource — return real tags from s3._bucket_tags
- tags = s3._bucket_tags.get(bucket_name, {})
+ # ListTagsForResource — return real tags from _get_module("s3")._bucket_tags
+ tags = _get_module("s3")._bucket_tags.get(bucket_name, {})
tag_members = "".join(
f"<member><Key>{k}</Key><Value>{v}</Value></member>"
for k, v in tags.items()
@@ -397,13 +408,13 @@ async def app(scope, receive, send):
"x-amzn-requestid": request_id,
}, xml_body)
elif method == "PUT":
- # TagResource — merge tags into s3._bucket_tags
+ # TagResource — merge tags into _get_module("s3")._bucket_tags
try:
payload = json.loads(body) if body else {}
new_tags = {t["Key"]: t["Value"] for t in payload.get("Tags", [])}
- existing = s3._bucket_tags.get(bucket_name, {})
+ existing = _get_module("s3")._bucket_tags.get(bucket_name, {})
existing.update(new_tags)
- s3._bucket_tags[bucket_name] = existing
+ _get_module("s3")._bucket_tags[bucket_name] = existing
except Exception as e:
logger.warning("S3 Control TagResource parse error: %s", e)
await _send_response(send, 204, {
@@ -414,10 +425,10 @@ async def app(scope, receive, send):
keys_to_remove = query_params.get("tagKeys", [])
if isinstance(keys_to_remove, str):
keys_to_remove = [keys_to_remove]
- tags = s3._bucket_tags.get(bucket_name, {})
+ tags = _get_module("s3")._bucket_tags.get(bucket_name, {})
for k in keys_to_remove:
tags.pop(k, None)
- s3._bucket_tags[bucket_name] = tags
+ _get_module("s3")._bucket_tags[bucket_name] = tags
await _send_response(send, 204, {
"x-amzn-requestid": request_id,
}, b"")
@@ -436,13 +447,13 @@ async def app(scope, receive, send):
# RDS Data API — /Execute, /BeginTransaction, /CommitTransaction, /RollbackTransaction, /BatchExecute
if path in ("/Execute", "/BeginTransaction", "/CommitTransaction", "/RollbackTransaction", "/BatchExecute"):
- status, resp_headers, resp_body = await rds_data.handle_request(method, path, headers, body, query_params)
+ status, resp_headers, resp_body = await _get_module("rds_data").handle_request(method, path, headers, body, query_params)
await _send_response(send, status, resp_headers, resp_body)
return
# SES v2 REST API — /v2/email/...
if path.startswith("/v2/email"):
- status, resp_headers, resp_body = await ses_v2.handle_request(method, path, headers, body, query_params)
+ status, resp_headers, resp_body = await _get_module("ses_v2").handle_request(method, path, headers, body, query_params)
await _send_response(send, status, resp_headers, resp_body)
return
@@ -453,7 +464,7 @@ async def app(scope, receive, send):
}, json.dumps({
"services": {s: "available" for s in SERVICE_HANDLERS},
"edition": "light",
- "version": "3.0.0.dev",
+ "version": _VERSION,
}).encode())
return
@@ -479,12 +490,12 @@ async def app(scope, receive, send):
stage = path_parts[0] if path_parts else "$default"
execute_path = "/" + path_parts[1] if len(path_parts) > 1 else "/"
try:
- if api_id in apigateway_v1._rest_apis:
- status, resp_headers, resp_body = await apigateway_v1.handle_execute(
+ if api_id in _get_module("apigateway_v1")._rest_apis:
+ status, resp_headers, resp_body = await _get_module("apigateway_v1").handle_execute(
api_id, stage, method, execute_path, headers, body, query_params
)
else:
- status, resp_headers, resp_body = await apigateway.handle_execute(
+ status, resp_headers, resp_body = await _get_module("apigateway").handle_execute(
api_id, stage, execute_path, method, headers, body, query_params
)
except Exception as e:
@@ -501,10 +512,10 @@ async def app(scope, receive, send):
# ALB data-plane — two addressing modes:
# 1. Host header matches a configured ALB DNS name or {lb-name}.alb.localhost
# 2. Path prefix /_alb/{lb-name}/... (no DNS config needed for local testing)
- _alb_lb = alb.find_lb_for_host(host)
+ _alb_lb = _get_module("alb").find_lb_for_host(host)
if _alb_lb is None and path.startswith("/_alb/"):
_alb_path_parts = path[6:].split("/", 1)
- _alb_lb = alb._find_lb_by_name(_alb_path_parts[0])
+ _alb_lb = _get_module("alb")._find_lb_by_name(_alb_path_parts[0])
if _alb_lb:
path = "/" + _alb_path_parts[1] if len(_alb_path_parts) > 1 else "/"
@@ -516,7 +527,7 @@ async def app(scope, receive, send):
except ValueError:
pass
try:
- status, resp_headers, resp_body = await alb.dispatch_request(
+ status, resp_headers, resp_body = await _get_module("alb").dispatch_request(
_alb_lb, method, path, headers, body, query_params, _alb_port
)
except Exception as e:
@@ -544,7 +555,7 @@ async def app(scope, receive, send):
if bucket not in _non_s3_hosts:
vhost_path = "/" + bucket + path if path != "/" else "/" + bucket + "/"
try:
- status, resp_headers, resp_body = await s3.handle_request(
+ status, resp_headers, resp_body = await _get_module("s3").handle_request(
method, vhost_path, headers, body, query_params
)
except Exception as e:
@@ -644,48 +655,31 @@ async def _handle_lifespan(scope, receive, send):
elif message["type"] == "lifespan.shutdown":
logger.info("MiniStack shutting down...")
if PERSIST_STATE:
- save_all({
- "apigateway": apigateway.get_state,
- "apigateway_v1": apigateway_v1.get_state,
- "sqs": sqs.get_state,
- "sns": sns.get_state,
- "ssm": ssm.get_state,
- "secretsmanager": secretsmanager.get_state,
- "iam": iam_sts.get_state,
- "dynamodb": dynamodb.get_state,
- "kms": kms.get_state,
- "eventbridge": eventbridge.get_state,
- "cloudwatch_logs": cloudwatch_logs.get_state,
- "kinesis": kinesis.get_state,
- "ec2": ec2.get_state,
- "route53": route53.get_state,
- "cognito": cognito.get_state,
- "ecr": ecr.get_state,
- "cloudwatch": cloudwatch.get_state,
- "s3": s3.get_state,
- "lambda": lambda_svc.get_state,
- "rds": rds.get_state,
- "ecs": ecs.get_state,
- "elasticache": elasticache.get_state,
- "appsync": appsync.get_state,
- "stepfunctions": stepfunctions.get_state,
- "alb": alb.get_state,
- "glue": glue.get_state,
- "efs": efs.get_state,
- "waf": waf.get_state,
- "athena": athena.get_state,
- "emr": emr.get_state,
- "cloudfront": cloudfront.get_state,
- "codebuild": codebuild.get_state,
- "transfer": transfer.get_state,
- "acm": acm.get_state,
- "firehose": firehose.get_state,
- "ses": ses.get_state,
- "ses_v2": ses_v2.get_state,
- "servicediscovery": servicediscovery.get_state,
- "s3files": s3files.get_state,
- "appconfig": appconfig.get_state,
- })
+ # Only save state for modules that were actually loaded
+ _state_map = {
+ "apigateway": "apigateway", "apigateway_v1": "apigateway_v1",
+ "sqs": "sqs", "sns": "sns", "ssm": "ssm",
+ "secretsmanager": "secretsmanager", "iam": "iam",
+ "dynamodb": "dynamodb", "kms": "kms", "eventbridge": "eventbridge",
+ "cloudwatch_logs": "cloudwatch_logs", "kinesis": "kinesis",
+ "ec2": "ec2", "route53": "route53", "cognito": "cognito",
+ "ecr": "ecr", "cloudwatch": "cloudwatch", "s3": "s3",
+ "lambda": "lambda_svc", "rds": "rds", "ecs": "ecs",
+ "elasticache": "elasticache", "appsync": "appsync",
+ "stepfunctions": "stepfunctions", "alb": "alb",
+ "glue": "glue", "efs": "efs", "waf": "waf",
+ "athena": "athena", "emr": "emr", "cloudfront": "cloudfront",
+ "codebuild": "codebuild", "acm": "acm", "firehose": "firehose",
+ "ses": "ses", "ses_v2": "ses_v2",
+ "servicediscovery": "servicediscovery", "s3files": "s3files",
+ "appconfig": "appconfig", "transfer": "transfer",
+ "scheduler": "scheduler", "autoscaling": "autoscaling",
+ }
+ save_dict = {}
+ for key, mod_name in _state_map.items():
+ if mod_name in _loaded_modules:
+ save_dict[key] = _loaded_modules[mod_name].get_state
+ save_all(save_dict)
_stop_docker_containers()
await send({"type": "lifespan.shutdown.complete"})
return
@@ -713,18 +707,11 @@ def _stop_docker_containers():
def _load_persisted_state():
"""Load persisted state for services that support it."""
- data = load_state("apigateway")
- if data:
- apigateway.load_persisted_state(data)
- logger.info("Loaded persisted state for apigateway")
- data_v1 = load_state("apigateway_v1")
- if data_v1:
- apigateway_v1.load_persisted_state(data_v1)
- logger.info("Loaded persisted state for apigateway_v1")
- data_sd = load_state("servicediscovery")
- if data_sd:
- servicediscovery.load_persisted_state(data_sd)
- logger.info("Loaded persisted state for servicediscovery")
+ for svc_key in ("apigateway", "apigateway_v1", "servicediscovery"):
+ data = load_state(svc_key)
+ if data:
+ _get_module(svc_key).load_persisted_state(data)
+ logger.info("Loaded persisted state for %s", svc_key)
async def _wait_for_port(port, timeout=30):
@@ -832,51 +819,26 @@ def _reset_all_state():
"""Wipe all in-memory state across every service module, and persisted files if enabled."""
from ministack.core.persistence import PERSIST_STATE, STATE_DIR
- from ministack.services.iam_sts import reset as _iam_reset
- from ministack.services.s3 import DATA_DIR as S3_DATA_DIR
- from ministack.services.s3 import PERSIST as S3_PERSIST
-
- for mod, fn in [
- (s3, s3.reset), (sqs, sqs.reset), (sns, sns.reset),
- (dynamodb, dynamodb.reset), (lambda_svc, lambda_svc.reset),
- (secretsmanager, secretsmanager.reset), (cloudwatch_logs, cloudwatch_logs.reset),
- (ssm, ssm.reset), (eventbridge, eventbridge.reset), (kinesis, kinesis.reset),
- (cloudwatch, cloudwatch.reset), (ses, ses.reset),
- (stepfunctions, stepfunctions.reset), (ecs, ecs.reset),
- (rds, rds.reset), (elasticache, elasticache.reset),
- (glue, glue.reset), (athena, athena.reset),
- (apigateway, apigateway.reset),
- (apigateway_v1, apigateway_v1.reset),
- (firehose, firehose.reset),
- (route53, route53.reset),
- (cognito, cognito.reset),
- (ec2, ec2.reset),
- (emr, emr.reset),
- (alb, alb.reset),
- (acm, acm.reset),
- (ses_v2, ses_v2.reset),
- (waf, waf.reset),
- (efs, efs.reset),
- (cloudformation, cloudformation.reset),
- (kms, kms.reset),
- (cloudfront, cloudfront.reset),
- (codebuild, codebuild.reset),
- (transfer, transfer.reset),
- (ecr, ecr.reset),
- (appsync, appsync.reset),
- (servicediscovery, servicediscovery.reset),
- (rds_data, rds_data.reset),
- (s3files, s3files.reset),
- (appconfig, appconfig.reset),
- ]:
- try:
- fn()
- except Exception as e:
- logger.warning("reset() failed for %s: %s", mod.__name__, e)
- try:
- _iam_reset()
- except Exception as e:
- logger.warning("reset() failed for iam_sts: %s", e)
+
+ _ALL_SERVICE_MODULES = [
+ "s3", "sqs", "sns", "dynamodb", "lambda_svc", "secretsmanager",
+ "cloudwatch_logs", "ssm", "eventbridge", "kinesis", "cloudwatch",
+ "ses", "stepfunctions", "ecs", "rds", "elasticache", "glue", "athena",
+ "apigateway", "apigateway_v1", "firehose", "route53", "cognito", "ec2",
+ "emr", "alb", "acm", "ses_v2", "waf", "efs", "cloudformation", "kms",
+ "cloudfront", "codebuild", "ecr", "appsync", "servicediscovery",
+ "rds_data", "s3files", "appconfig", "transfer", "scheduler", "autoscaling", "iam",
+ ]
+ for mod_name in _ALL_SERVICE_MODULES:
+ if mod_name in _loaded_modules:
+ mod = _loaded_modules[mod_name]
+ try:
+ mod.reset()
+ except Exception as e:
+ logger.warning("reset() failed for %s: %s", mod_name, e)
+
+ S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3")
+ S3_PERSIST = os.environ.get("S3_PERSIST", "0") == "1"
# Wipe persisted files so a subsequent restart doesn't reload old state
if PERSIST_STATE and os.path.isdir(STATE_DIR):
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 86eed35e..fe512ac5 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -205,6 +205,11 @@ SERVICE_PATTERNS = {
"path_prefixes": ["/configurationsessions", "/configuration"],
"credential_scope": "appconfigdata",
},
+ "scheduler": {
+ "host_patterns": [r"scheduler\."],
+ "path_prefixes": ["/schedules", "/schedule-groups"],
+ "credential_scope": "scheduler",
+ },
}
@@ -265,6 +270,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"autoscaling": "autoscaling",
"appconfig": "appconfig",
"appconfigdata": "appconfigdata",
+ "scheduler": "scheduler",
}
if svc_name in scope_map:
return scope_map[svc_name]
diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.py
index 979595e8..bbf04ca8 100644
--- a/ministack/services/autoscaling.py
+++ b/ministack/services/autoscaling.py
@@ -32,6 +32,39 @@ _scheduled_actions = AccountScopedDict()
_tags = AccountScopedDict() # asg_name -> [{"Key":..., "Value":...}, ...]
+import copy
+
+
+def get_state():
+ return {
+ "asgs": copy.deepcopy(_asgs),
+ "launch_configs": copy.deepcopy(_launch_configs),
+ "policies": copy.deepcopy(_policies),
+ "hooks": copy.deepcopy(_hooks),
+ "scheduled_actions": copy.deepcopy(_scheduled_actions),
+ "tags": copy.deepcopy(_tags),
+ }
+
+
+def restore_state(data):
+ if data:
+ _asgs.update(data.get("asgs", {}))
+ _launch_configs.update(data.get("launch_configs", {}))
+ _policies.update(data.get("policies", {}))
+ _hooks.update(data.get("hooks", {}))
+ _scheduled_actions.update(data.get("scheduled_actions", {}))
+ _tags.update(data.get("tags", {}))
+
+
+def reset():
+ _asgs.clear()
+ _launch_configs.clear()
+ _policies.clear()
+ _hooks.clear()
+ _scheduled_actions.clear()
+ _tags.clear()
+
+
def _p(params, key):
v = params.get(key, "")
return v[0] if isinstance(v, list) else v
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 2b0491ab..0fc7cd5d 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -23,7 +23,7 @@ import ministack.services.ssm as _ssm
import ministack.services.cloudwatch as _cw
import ministack.services.cloudwatch_logs as _cw_logs
import ministack.services.eventbridge as _eb
-import ministack.services.iam_sts as _iam_sts
+import ministack.services.iam as _iam
import ministack.services.apigateway_v1 as _apigw_v1
import ministack.services.appsync as _appsync
import ministack.services.secretsmanager as _sm
@@ -476,12 +476,12 @@ def _iam_role_create(logical_id, props, stack_name):
for t in tags:
role["Tags"].append({"Key": t.get("Key", ""), "Value": t.get("Value", "")})
- _iam_sts._roles[name] = role
+ _iam._roles[name] = role
return name, {"Arn": arn, "RoleId": role_id}
def _iam_role_delete(physical_id, props):
- _iam_sts._roles.pop(physical_id, None)
+ _iam._roles.pop(physical_id, None)
# --- IAM Policy ---
@@ -513,12 +513,12 @@ def _iam_policy_create(logical_id, props, stack_name):
}],
"Tags": [],
}
- _iam_sts._policies[arn] = policy
+ _iam._policies[arn] = policy
# Attach to roles if Roles property specified
roles = props.get("Roles", [])
for role_name in roles:
- role = _iam_sts._roles.get(role_name)
+ role = _iam._roles.get(role_name)
if role:
role["AttachedPolicies"].append({
"PolicyName": name,
@@ -530,7 +530,7 @@ def _iam_policy_create(logical_id, props, stack_name):
def _iam_policy_delete(physical_id, props):
- _iam_sts._policies.pop(physical_id, None)
+ _iam._policies.pop(physical_id, None)
# --- IAM InstanceProfile ---
@@ -543,7 +543,7 @@ def _iam_ip_create(logical_id, props, stack_name):
roles = []
for rname in props.get("Roles", []):
- role = _iam_sts._roles.get(rname)
+ role = _iam._roles.get(rname)
if role:
roles.append(role)
@@ -556,15 +556,15 @@ def _iam_ip_create(logical_id, props, stack_name):
"CreateDate": now_iso(),
"Tags": [],
}
- _iam_sts._instance_profiles[name] = profile
+ _iam._instance_profiles[name] = profile
return arn, {"Arn": arn}
def _iam_ip_delete(physical_id, props):
# physical_id is the ARN -- find the name
- for name, ip in list(_iam_sts._instance_profiles.items()):
+ for name, ip in list(_iam._instance_profiles.items()):
if ip.get("Arn") == physical_id:
- _iam_sts._instance_profiles.pop(name, None)
+ _iam._instance_profiles.pop(name, None)
return
@@ -654,6 +654,57 @@ def _eb_rule_delete(physical_id, props):
_eb._targets.pop(key, None)
+# --- EventBridge Scheduler (AWS::Scheduler::Schedule) ---
+
+
+def _scheduler_schedule_create(logical_id, props, stack_name):
+ import ministack.services.scheduler as _sched
+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)
+ group = props.get("GroupName", "default")
+ _sched._ensure_default_group()
+ body = {
+ "ScheduleExpression": props.get("ScheduleExpression", "rate(1 hour)"),
+ "FlexibleTimeWindow": props.get("FlexibleTimeWindow", {"Mode": "OFF"}),
+ "Target": props.get("Target", {"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop", "RoleArn": "arn:aws:iam::000000000000:role/noop"}),
+ "GroupName": group,
+ "State": props.get("State", "ENABLED"),
+ "Description": props.get("Description", ""),
+ }
+ _sched._create_schedule(name, body)
+ arn = _sched._schedule_arn(group, name)
+ return name, {"Arn": arn}
+
+
+def _scheduler_schedule_delete(physical_id, props):
+ import ministack.services.scheduler as _sched
+ group = props.get("GroupName", "default")
+ key = f"{group}/{physical_id}"
+ sched = _sched._schedules.pop(key, None)
+ if sched:
+ _sched._tags.pop(sched.get("Arn", ""), None)
+
+
+def _scheduler_group_create(logical_id, props, stack_name):
+ import ministack.services.scheduler as _sched
+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)
+ _sched._create_schedule_group(name, {"Tags": props.get("Tags", [])})
+ arn = _sched._group_arn(name)
+ return name, {"Arn": arn}
+
+
+def _scheduler_group_delete(physical_id, props):
+ import ministack.services.scheduler as _sched
+ # Cascade delete child schedules (matches REST API behavior)
+ keys_to_delete = [k for k, v in _sched._schedules.items() if v["GroupName"] == physical_id]
+ for k in keys_to_delete:
+ arn = _sched._schedules[k]["Arn"]
+ del _sched._schedules[k]
+ _sched._tags.pop(arn, None)
+ group = _sched._schedule_groups.pop(physical_id, None)
+ if group:
+ _sched._tags.pop(group.get("Arn", ""), None)
+
+
# --- Kinesis Stream ---
def _kinesis_stream_create(logical_id, props, stack_name):
@@ -1391,7 +1442,7 @@ def _iam_managed_policy_create(logical_id, props, stack_name):
name = props.get("ManagedPolicyName", f"{stack_name}-{logical_id}")
arn = f"arn:aws:iam::{get_account_id()}:policy/{name}"
policy_doc = props.get("PolicyDocument", {})
- _iam_sts._policies[arn] = {
+ _iam._policies[arn] = {
"PolicyName": name,
"PolicyId": new_uuid().replace("-", "")[:21].upper(),
"Arn": arn,
@@ -1408,7 +1459,7 @@ def _iam_managed_policy_create(logical_id, props, stack_name):
def _iam_managed_policy_delete(physical_id, props):
- _iam_sts._policies.pop(physical_id, None)
+ _iam._policies.pop(physical_id, None)
# --- KMS resource provisioners ---
@@ -2696,6 +2747,9 @@ _RESOURCE_HANDLERS = {
"AWS::CloudFront::Distribution": {"create": _cf_distribution_create, "delete": _cf_distribution_delete},
"AWS::CloudWatch::Alarm": {"create": _cw_metric_alarm_create, "delete": _cw_metric_alarm_delete},
"AWS::RDS::DBCluster": {"create": _rds_db_cluster_create, "delete": _rds_db_cluster_delete},
+ # EventBridge Scheduler
+ "AWS::Scheduler::Schedule": {"create": _scheduler_schedule_create, "delete": _scheduler_schedule_delete},
+ "AWS::Scheduler::ScheduleGroup": {"create": _scheduler_group_create, "delete": _scheduler_group_delete},
# CDK metadata — safe to ignore
"AWS::CDK::Metadata": {"create": lambda lid, props, sn: (f"CDKMetadata-{lid}", {}), "delete": lambda pid, props: None},
# AutoScaling
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index a9d414f4..d31a542f 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -215,6 +215,8 @@ def get_state():
"pool_domain_map": copy.deepcopy(_pool_domain_map),
"identity_pools": copy.deepcopy(_identity_pools),
"identity_tags": copy.deepcopy(_identity_tags),
+ "authorization_codes": copy.deepcopy(_authorization_codes),
+ "refresh_tokens": copy.deepcopy(_refresh_tokens),
}
@@ -224,6 +226,8 @@ def restore_state(data):
_pool_domain_map.update(data.get("pool_domain_map", {}))
_identity_pools.update(data.get("identity_pools", {}))
_identity_tags.update(data.get("identity_tags", {}))
+ _authorization_codes.update(data.get("authorization_codes", {}))
+ _refresh_tokens.update(data.get("refresh_tokens", {}))
_restored = load_state("cognito")
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index ef58de5e..a3735b8d 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -1538,6 +1538,19 @@ def _get_task_protection(data):
return json_response({"protectedTasks": [], "failures": []})
+# ---------------------------------------------------------------------------
+# Container instances (stub — MiniStack runs tasks as Docker containers
+# directly, there are no EC2 container instances to register)
+# ---------------------------------------------------------------------------
+
+def _list_container_instances(data):
+ return json_response({"containerInstanceArns": []})
+
+
+def _describe_container_instances(data):
+ return json_response({"containerInstances": [], "failures": []})
+
+
# ---------------------------------------------------------------------------
# Action map (X-Amz-Target dispatch)
# ---------------------------------------------------------------------------
@@ -1588,6 +1601,8 @@ _ACTION_MAP = {
"SubmitContainerStateChange": _submit_container_state_change,
"SubmitAttachmentStateChanges": _submit_attachment_state_changes,
"DiscoverPollEndpoint": _discover_poll_endpoint,
+ "ListContainerInstances": _list_container_instances,
+ "DescribeContainerInstances": _describe_container_instances,
"UpdateTaskProtection": _update_task_protection,
"GetTaskProtection": _get_task_protection,
}
diff --git a/ministack/services/iam_sts.py b/ministack/services/iam.py
similarity index 89%
rename from ministack/services/iam_sts.py
rename to ministack/services/iam.py
index f3301b7f..449abcd5 100644
--- a/ministack/services/iam_sts.py
+++ b/ministack/services/iam.py
@@ -1,5 +1,7 @@
"""
-IAM & STS Service Emulators (AWS-compatible).
+IAM Service Emulator (AWS-compatible).
+
+STS actions are in sts.py.
IAM actions:
CreateUser, GetUser, ListUsers, DeleteUser,
@@ -17,15 +19,12 @@ IAM actions:
UpdateAssumeRolePolicy,
CreateGroup, GetGroup, DeleteGroup, ListGroups,
AddUserToGroup, RemoveUserFromGroup, ListGroupsForUser,
- CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus,
+ CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus,
CreateOpenIDConnectProvider, GetOpenIDConnectProvider, DeleteOpenIDConnectProvider,
TagRole, UntagRole, ListRoleTags,
TagUser, UntagUser, ListUserTags,
TagPolicy, UntagPolicy, ListPolicyTags,
SimulatePrincipalPolicy, SimulateCustomPolicy.
-
-STS actions:
- GetCallerIdentity, AssumeRole, GetSessionToken, GetAccessKeyInfo.
"""
import copy
@@ -70,6 +69,7 @@ def get_state():
"access_keys": copy.deepcopy(_access_keys),
"oidc_providers": copy.deepcopy(_oidc_providers),
"service_linked_role_deletion_tasks": copy.deepcopy(_service_linked_role_deletion_tasks),
+ "user_inline_policies": copy.deepcopy(_user_inline_policies),
}
@@ -83,6 +83,7 @@ def restore_state(data):
_access_keys.update(data.get("access_keys", {}))
_oidc_providers.update(data.get("oidc_providers", {}))
_service_linked_role_deletion_tasks.update(data.get("service_linked_role_deletion_tasks", {}))
+ _user_inline_policies.update(data.get("user_inline_policies", {}))
_restored = load_state("iam")
@@ -93,7 +94,7 @@ if _restored:
# ===================================================================== IAM
# =====================================================================
-async def handle_iam_request(method, path, headers, body, query_params):
+async def handle_request(method, path, headers, body, query_params):
params = dict(query_params)
content_type = headers.get("content-type", "")
target = headers.get("x-amz-target", "")
@@ -1342,145 +1343,6 @@ def _list_policy_tags(p):
ns="iam")
-# ===================================================================== STS
-# =====================================================================
-
-async def handle_sts_request(method, path, headers, body, query_params):
- params = dict(query_params)
- content_type = headers.get("content-type", "")
- target = headers.get("x-amz-target", "")
-
- # JSON protocol (newer SDKs): X-Amz-Target: AWSSecurityTokenServiceV20110615.ActionName
- if "amz-json" in content_type and target.startswith("AWSSecurityTokenServiceV20110615."):
- action_name = target.split(".")[-1]
- params["Action"] = [action_name]
- if body:
- try:
- json_body = json.loads(body)
- for k, v in json_body.items():
- params[k] = [str(v)] if not isinstance(v, list) else v
- except (json.JSONDecodeError, TypeError):
- pass
- elif method == "POST" and body:
- for k, v in parse_qs(body.decode("utf-8", errors="replace")).items():
- params[k] = v
-
- action = _p(params, "Action")
- use_json = "amz-json" in content_type
-
- if action == "GetCallerIdentity":
- if use_json:
- return json_response({"Account": get_account_id(), "Arn": f"arn:aws:iam::{get_account_id()}:root", "UserId": get_account_id()})
- return _xml(200, "GetCallerIdentityResponse",
- f"<GetCallerIdentityResult>"
- f"<Arn>arn:aws:iam::{get_account_id()}:root</Arn>"
- f"<UserId>{get_account_id()}</UserId>"
- f"<Account>{get_account_id()}</Account>"
- f"</GetCallerIdentityResult>",
- ns="sts")
-
- if action == "AssumeRole":
- role_arn = _p(params, "RoleArn")
- session_name = _p(params, "RoleSessionName")
- duration = int(_p(params, "DurationSeconds") or 3600)
- expiration = _future(duration)
- access_key = _gen_session_access_key()
- secret_key = _gen_secret()
- session_token = _gen_session_token()
- role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
- assumed_arn = role_arn.replace(":role/", ":assumed-role/", 1)
- if not assumed_arn.endswith(f"/{session_name}"):
- assumed_arn = f"{assumed_arn}/{session_name}"
- if use_json:
- return json_response({
- "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
- "AssumedRoleUser": {"AssumedRoleId": f"{role_id}:{session_name}", "Arn": assumed_arn},
- "PackedPolicySize": 0,
- })
- return _xml(200, "AssumeRoleResponse",
- f"<AssumeRoleResult>"
- f"<Credentials>"
- f"<AccessKeyId>{access_key}</AccessKeyId>"
- f"<SecretAccessKey>{secret_key}</SecretAccessKey>"
- f"<SessionToken>{session_token}</SessionToken>"
- f"<Expiration>{expiration}</Expiration>"
- f"</Credentials>"
- f"<AssumedRoleUser>"
- f"<AssumedRoleId>{role_id}:{session_name}</AssumedRoleId>"
- f"<Arn>{assumed_arn}</Arn>"
- f"</AssumedRoleUser>"
- f"<PackedPolicySize>0</PackedPolicySize>"
- f"</AssumeRoleResult>",
- ns="sts")
-
- if action == "AssumeRoleWithWebIdentity":
- role_arn = _p(params, "RoleArn")
- session = _p(params, "RoleSessionName", "session")
- duration = int(_p(params, "DurationSeconds") or 3600)
- access_key = _gen_session_access_key()
- secret_key = _gen_secret()
- session_token = _gen_session_token()
- assumed_arn = role_arn.replace(":role/", ":assumed-role/", 1)
- if not assumed_arn.endswith(f"/{session}"):
- assumed_arn = f"{assumed_arn}/{session}"
- role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
- if use_json:
- return json_response({
- "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
- "AssumedRoleUser": {"AssumedRoleId": f"{role_id}:{session}", "Arn": assumed_arn},
- "SubjectFromWebIdentityToken": "test-subject",
- "Audience": "sts.amazonaws.com",
- "Provider": "accounts.google.com",
- })
- return _xml(200, "AssumeRoleWithWebIdentityResponse",
- f"<AssumeRoleWithWebIdentityResult>"
- f"<Credentials>"
- f"<AccessKeyId>{access_key}</AccessKeyId>"
- f"<SecretAccessKey>{secret_key}</SecretAccessKey>"
- f"<SessionToken>{session_token}</SessionToken>"
- f"<Expiration>{_future(duration)}</Expiration>"
- f"</Credentials>"
- f"<AssumedRoleUser>"
- f"<AssumedRoleId>{role_id}:{session}</AssumedRoleId>"
- f"<Arn>{assumed_arn}</Arn>"
- f"</AssumedRoleUser>"
- f"<SubjectFromWebIdentityToken>test-subject</SubjectFromWebIdentityToken>"
- f"<Audience>sts.amazonaws.com</Audience>"
- f"<Provider>accounts.google.com</Provider>"
- f"</AssumeRoleWithWebIdentityResult>",
- ns="sts")
-
- if action == "GetSessionToken":
- duration = int(_p(params, "DurationSeconds") or 43200)
- expiration = _future(duration)
- access_key = _gen_session_access_key()
- secret_key = _gen_secret()
- session_token = _gen_session_token()
- if use_json:
- return json_response({
- "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
- })
- return _xml(200, "GetSessionTokenResponse",
- f"<GetSessionTokenResult>"
- f"<Credentials>"
- f"<AccessKeyId>{access_key}</AccessKeyId>"
- f"<SecretAccessKey>{secret_key}</SecretAccessKey>"
- f"<SessionToken>{session_token}</SessionToken>"
- f"<Expiration>{expiration}</Expiration>"
- f"</Credentials>"
- f"</GetSessionTokenResult>",
- ns="sts")
-
- if action == "GetAccessKeyInfo":
- if use_json:
- return json_response({"Account": get_account_id()})
- return _xml(200, "GetAccessKeyInfoResponse",
- f"<GetAccessKeyInfoResult>"
- f"<Account>{get_account_id()}</Account>"
- f"</GetAccessKeyInfoResult>",
- ns="sts")
-
- return _error(400, "InvalidAction", f"Unknown STS action: {action}", ns="sts")
# ===================================================================== Shared helpers
diff --git a/ministack/services/scheduler.py b/ministack/services/scheduler.py
new file mode 100644
index 00000000..e66b06f4
--- /dev/null
+++ b/ministack/services/scheduler.py
@@ -0,0 +1,416 @@
+"""
+EventBridge Scheduler Service Emulator.
+REST/JSON protocol — /schedules/* and /schedule-groups/* paths.
+
+Supports:
+ Schedules: CreateSchedule, GetSchedule, ListSchedules,
+ UpdateSchedule, DeleteSchedule
+ Groups: CreateScheduleGroup, GetScheduleGroup,
+ ListScheduleGroups, DeleteScheduleGroup
+ Tags: TagResource, UntagResource, ListTagsForResource
+"""
+
+import copy
+import json
+import logging
+import os
+import re
+import time
+
+from ministack.core.responses import AccountScopedDict, get_account_id
+
+logger = logging.getLogger("scheduler")
+
+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+
+# ---------------------------------------------------------------------------
+# State
+# ---------------------------------------------------------------------------
+
+_schedules = AccountScopedDict() # (group, name) -> schedule record
+_schedule_groups = AccountScopedDict() # group_name -> group record
+_tags = AccountScopedDict() # arn -> {key: value}
+
+
+def reset():
+ _schedules.clear()
+ _schedule_groups.clear()
+ _tags.clear()
+
+
+def get_state():
+ return copy.deepcopy({
+ "schedules": dict(_schedules),
+ "schedule_groups": dict(_schedule_groups),
+ "tags": dict(_tags),
+ })
+
+
+def restore_state(data):
+ _schedules.update(data.get("schedules", {}))
+ _schedule_groups.update(data.get("schedule_groups", {}))
+ _tags.update(data.get("tags", {}))
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _now():
+ return time.time()
+
+
+def _schedule_arn(group, name):
+ return f"arn:aws:scheduler:{REGION}:{get_account_id()}:schedule/{group}/{name}"
+
+
+def _group_arn(name):
+ return f"arn:aws:scheduler:{REGION}:{get_account_id()}:schedule-group/{name}"
+
+
+def _json_resp(status, body):
+ return status, {"Content-Type": "application/json"}, json.dumps(body).encode()
+
+
+def _error(status, code, message):
+ return _json_resp(status, {"__type": code, "Message": message})
+
+
+def _ensure_default_group():
+ """Ensure the 'default' group exists."""
+ key = "default"
+ if key not in _schedule_groups:
+ _schedule_groups[key] = {
+ "Arn": _group_arn("default"),
+ "Name": "default",
+ "State": "ACTIVE",
+ "CreationDate": _now(),
+ "LastModificationDate": _now(),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Schedules
+# ---------------------------------------------------------------------------
+
+def _create_schedule(name, body):
+ _ensure_default_group()
+
+ group = body.get("GroupName", "default")
+ key = f"{group}/{name}"
+
+ if key in _schedules:
+ return _error(409, "ConflictException",
+ f"Schedule {name} already exists in group {group}.")
+
+ # Validate required fields
+ if not body.get("ScheduleExpression"):
+ return _error(400, "ValidationException",
+ "1 validation error detected: Value at 'scheduleExpression' failed to satisfy constraint.")
+ if not body.get("FlexibleTimeWindow"):
+ return _error(400, "ValidationException",
+ "1 validation error detected: Value at 'flexibleTimeWindow' failed to satisfy constraint.")
+ if not body.get("Target"):
+ return _error(400, "ValidationException",
+ "1 validation error detected: Value at 'target' failed to satisfy constraint.")
+
+ target = body.get("Target", {})
+ if not target.get("Arn") or not target.get("RoleArn"):
+ return _error(400, "ValidationException",
+ "Target Arn and RoleArn are required.")
+
+ # Validate group exists
+ if group != "default" and group not in _schedule_groups:
+ return _error(404, "ResourceNotFoundException",
+ f"Schedule group {group} does not exist.")
+
+ now = _now()
+ arn = _schedule_arn(group, name)
+
+ _schedules[key] = {
+ "Arn": arn,
+ "Name": name,
+ "GroupName": group,
+ "ScheduleExpression": body["ScheduleExpression"],
+ "ScheduleExpressionTimezone": body.get("ScheduleExpressionTimezone", "UTC"),
+ "FlexibleTimeWindow": body["FlexibleTimeWindow"],
+ "Target": target,
+ "State": body.get("State", "ENABLED"),
+ "ActionAfterCompletion": body.get("ActionAfterCompletion", "NONE"),
+ "Description": body.get("Description", ""),
+ "StartDate": body.get("StartDate"),
+ "EndDate": body.get("EndDate"),
+ "KmsKeyArn": body.get("KmsKeyArn"),
+ "CreationDate": now,
+ "LastModificationDate": now,
+ }
+
+ return _json_resp(200, {"ScheduleArn": arn})
+
+
+def _update_schedule(name, body):
+ group = body.get("GroupName", "default")
+ key = f"{group}/{name}"
+
+ if key not in _schedules:
+ return _error(404, "ResourceNotFoundException",
+ f"Schedule {name} does not exist in group {group}.")
+
+ if not body.get("ScheduleExpression"):
+ return _error(400, "ValidationException",
+ "1 validation error detected: Value at 'scheduleExpression' failed to satisfy constraint.")
+ if not body.get("FlexibleTimeWindow"):
+ return _error(400, "ValidationException",
+ "1 validation error detected: Value at 'flexibleTimeWindow' failed to satisfy constraint.")
+ if not body.get("Target"):
+ return _error(400, "ValidationException",
+ "1 validation error detected: Value at 'target' failed to satisfy constraint.")
+
+ target = body.get("Target", {})
+ existing = _schedules[key]
+ arn = existing["Arn"]
+
+ _schedules[key] = {
+ "Arn": arn,
+ "Name": name,
+ "GroupName": group,
+ "ScheduleExpression": body["ScheduleExpression"],
+ "ScheduleExpressionTimezone": body.get("ScheduleExpressionTimezone", "UTC"),
+ "FlexibleTimeWindow": body["FlexibleTimeWindow"],
+ "Target": target,
+ "State": body.get("State", "ENABLED"),
+ "ActionAfterCompletion": body.get("ActionAfterCompletion", "NONE"),
+ "Description": body.get("Description", ""),
+ "StartDate": body.get("StartDate"),
+ "EndDate": body.get("EndDate"),
+ "KmsKeyArn": body.get("KmsKeyArn"),
+ "CreationDate": existing["CreationDate"],
+ "LastModificationDate": _now(),
+ }
+
+ return _json_resp(200, {"ScheduleArn": arn})
+
+
+def _get_schedule(name, query):
+ group = query.get("groupName", "default")
+ key = f"{group}/{name}"
+
+ sched = _schedules.get(key)
+ if not sched:
+ return _error(404, "ResourceNotFoundException",
+ f"Schedule {name} does not exist in group {group}.")
+
+ result = {k: v for k, v in sched.items() if v is not None}
+ return _json_resp(200, result)
+
+
+def _list_schedules(query):
+ _ensure_default_group()
+
+ group_filter = query.get("ScheduleGroup")
+ name_prefix = query.get("NamePrefix", "")
+ state_filter = query.get("State")
+ max_results = int(query.get("MaxResults", 100))
+
+ results = []
+ for key, sched in _schedules.items():
+ if group_filter and sched["GroupName"] != group_filter:
+ continue
+ if name_prefix and not sched["Name"].startswith(name_prefix):
+ continue
+ if state_filter and sched["State"] != state_filter:
+ continue
+ results.append({
+ "Arn": sched["Arn"],
+ "Name": sched["Name"],
+ "GroupName": sched["GroupName"],
+ "State": sched["State"],
+ "CreationDate": sched["CreationDate"],
+ "LastModificationDate": sched["LastModificationDate"],
+ "Target": {"Arn": sched["Target"].get("Arn", "")},
+ })
+
+ results = results[:max_results]
+ return _json_resp(200, {"Schedules": results})
+
+
+def _delete_schedule(name, query):
+ group = query.get("groupName", "default")
+ key = f"{group}/{name}"
+
+ if key not in _schedules:
+ return _error(404, "ResourceNotFoundException",
+ f"Schedule {name} does not exist in group {group}.")
+
+ arn = _schedules[key]["Arn"]
+ del _schedules[key]
+ _tags.pop(arn, None)
+
+ return _json_resp(200, {})
+
+
+# ---------------------------------------------------------------------------
+# Schedule Groups
+# ---------------------------------------------------------------------------
+
+def _create_schedule_group(name, body):
+ _ensure_default_group()
+
+ if name in _schedule_groups:
+ return _error(409, "ConflictException",
+ f"Schedule group {name} already exists.")
+
+ now = _now()
+ arn = _group_arn(name)
+
+ _schedule_groups[name] = {
+ "Arn": arn,
+ "Name": name,
+ "State": "ACTIVE",
+ "CreationDate": now,
+ "LastModificationDate": now,
+ }
+
+ # Handle tags
+ tags = body.get("Tags", [])
+ if tags:
+ _tags[arn] = {t["Key"]: t["Value"] for t in tags}
+
+ return _json_resp(200, {"ScheduleGroupArn": arn})
+
+
+def _get_schedule_group(name):
+ _ensure_default_group()
+
+ group = _schedule_groups.get(name)
+ if not group:
+ return _error(404, "ResourceNotFoundException",
+ f"Schedule group {name} does not exist.")
+
+ return _json_resp(200, group)
+
+
+def _list_schedule_groups(query):
+ _ensure_default_group()
+
+ name_prefix = query.get("NamePrefix", "")
+ max_results = int(query.get("MaxResults", 100))
+
+ results = []
+ for name, group in _schedule_groups.items():
+ if name_prefix and not name.startswith(name_prefix):
+ continue
+ results.append(group)
+
+ results = results[:max_results]
+ return _json_resp(200, {"ScheduleGroups": results})
+
+
+def _delete_schedule_group(name, query):
+ if name == "default":
+ return _error(400, "ValidationException",
+ "The default schedule group cannot be deleted.")
+
+ if name not in _schedule_groups:
+ return _error(404, "ResourceNotFoundException",
+ f"Schedule group {name} does not exist.")
+
+ # Delete all schedules in this group
+ keys_to_delete = [k for k, v in _schedules.items() if v["GroupName"] == name]
+ for k in keys_to_delete:
+ arn = _schedules[k]["Arn"]
+ del _schedules[k]
+ _tags.pop(arn, None)
+
+ arn = _schedule_groups[name]["Arn"]
+ del _schedule_groups[name]
+ _tags.pop(arn, None)
+
+ return _json_resp(200, {})
+
+
+# ---------------------------------------------------------------------------
+# Tags
+# ---------------------------------------------------------------------------
+
+def _tag_resource(arn, body):
+ tags = body.get("Tags", [])
+ existing = _tags.get(arn, {})
+ existing.update({t["Key"]: t["Value"] for t in tags})
+ _tags[arn] = existing
+ return _json_resp(200, {})
+
+
+def _untag_resource(arn, query):
+ keys = query.get("TagKeys", [])
+ if isinstance(keys, str):
+ keys = [keys]
+ existing = _tags.get(arn, {})
+ for k in keys:
+ existing.pop(k, None)
+ if existing:
+ _tags[arn] = existing
+ else:
+ _tags.pop(arn, None)
+ return _json_resp(200, {})
+
+
+def _list_tags(arn):
+ existing = _tags.get(arn, {})
+ tags = [{"Key": k, "Value": v} for k, v in existing.items()]
+ return _json_resp(200, {"Tags": tags})
+
+
+# ---------------------------------------------------------------------------
+# Request Router
+# ---------------------------------------------------------------------------
+
+async def handle_request(method, path, headers, body_bytes, query_params):
+ try:
+ body = json.loads(body_bytes) if body_bytes else {}
+ except json.JSONDecodeError:
+ body = {}
+
+ query = {k: (v[0] if isinstance(v, list) else v) for k, v in query_params.items()}
+
+ # Schedule routes: /schedules and /schedules/{name}
+ m = re.fullmatch(r"/schedules/([A-Za-z0-9_.@-]+)", path)
+ if m:
+ name = m.group(1)
+ if method == "POST":
+ return _create_schedule(name, body)
+ if method == "GET":
+ return _get_schedule(name, query)
+ if method == "PUT":
+ return _update_schedule(name, body)
+ if method == "DELETE":
+ return _delete_schedule(name, query)
+
+ if path == "/schedules" and method == "GET":
+ return _list_schedules(query)
+
+ # Schedule group routes: /schedule-groups and /schedule-groups/{name}
+ m = re.fullmatch(r"/schedule-groups/([A-Za-z0-9_.@-]+)", path)
+ if m:
+ name = m.group(1)
+ if method == "POST":
+ return _create_schedule_group(name, body)
+ if method == "GET":
+ return _get_schedule_group(name)
+ if method == "DELETE":
+ return _delete_schedule_group(name, query)
+
+ if path == "/schedule-groups" and method == "GET":
+ return _list_schedule_groups(query)
+
+ # Tags routes: /tags/{arn+}
+ if path.startswith("/tags/"):
+ arn = path[6:] # Everything after /tags/
+ if method == "GET":
+ return _list_tags(arn)
+ if method == "POST":
+ return _tag_resource(arn, body)
+ if method == "DELETE":
+ return _untag_resource(arn, query)
+
+ return _error(400, "ValidationException", f"No route for {method} {path}")
diff --git a/ministack/services/sts.py b/ministack/services/sts.py
new file mode 100644
index 00000000..7d3d9872
--- /dev/null
+++ b/ministack/services/sts.py
@@ -0,0 +1,155 @@
+"""
+STS Service Emulator (AWS-compatible).
+
+Actions:
+ GetCallerIdentity, AssumeRole, AssumeRoleWithWebIdentity,
+ GetSessionToken, GetAccessKeyInfo.
+"""
+
+import json
+import time
+from urllib.parse import parse_qs
+
+from ministack.core.responses import get_account_id, json_response, new_uuid
+# Shared helpers — IAM and STS are a natural pair; STS is stateless
+# and reuses IAM's XML builders and credential generators.
+from ministack.services.iam import _p, _xml, _error, _future, \
+ _gen_session_access_key, _gen_secret, _gen_session_token
+
+
+async def handle_request(method, path, headers, body, query_params):
+ params = dict(query_params)
+ content_type = headers.get("content-type", "")
+ target = headers.get("x-amz-target", "")
+
+ # JSON protocol (newer SDKs): X-Amz-Target: AWSSecurityTokenServiceV20110615.ActionName
+ if "amz-json" in content_type and target.startswith("AWSSecurityTokenServiceV20110615."):
+ action_name = target.split(".")[-1]
+ params["Action"] = [action_name]
+ if body:
+ try:
+ json_body = json.loads(body)
+ for k, v in json_body.items():
+ params[k] = [str(v)] if not isinstance(v, list) else v
+ except (json.JSONDecodeError, TypeError):
+ pass
+ elif method == "POST" and body:
+ for k, v in parse_qs(body.decode("utf-8", errors="replace")).items():
+ params[k] = v
+
+ action = _p(params, "Action")
+ use_json = "amz-json" in content_type
+
+ if action == "GetCallerIdentity":
+ if use_json:
+ return json_response({"Account": get_account_id(), "Arn": f"arn:aws:iam::{get_account_id()}:root", "UserId": get_account_id()})
+ return _xml(200, "GetCallerIdentityResponse",
+ f"<GetCallerIdentityResult>"
+ f"<Arn>arn:aws:iam::{get_account_id()}:root</Arn>"
+ f"<UserId>{get_account_id()}</UserId>"
+ f"<Account>{get_account_id()}</Account>"
+ f"</GetCallerIdentityResult>",
+ ns="sts")
+
+ if action == "AssumeRole":
+ role_arn = _p(params, "RoleArn")
+ session_name = _p(params, "RoleSessionName")
+ duration = int(_p(params, "DurationSeconds") or 3600)
+ expiration = _future(duration)
+ access_key = _gen_session_access_key()
+ secret_key = _gen_secret()
+ session_token = _gen_session_token()
+ role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
+ assumed_arn = role_arn.replace(":role/", ":assumed-role/", 1)
+ if not assumed_arn.endswith(f"/{session_name}"):
+ assumed_arn = f"{assumed_arn}/{session_name}"
+ if use_json:
+ return json_response({
+ "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
+ "AssumedRoleUser": {"AssumedRoleId": f"{role_id}:{session_name}", "Arn": assumed_arn},
+ "PackedPolicySize": 0,
+ })
+ return _xml(200, "AssumeRoleResponse",
+ f"<AssumeRoleResult>"
+ f"<Credentials>"
+ f"<AccessKeyId>{access_key}</AccessKeyId>"
+ f"<SecretAccessKey>{secret_key}</SecretAccessKey>"
+ f"<SessionToken>{session_token}</SessionToken>"
+ f"<Expiration>{expiration}</Expiration>"
+ f"</Credentials>"
+ f"<AssumedRoleUser>"
+ f"<AssumedRoleId>{role_id}:{session_name}</AssumedRoleId>"
+ f"<Arn>{assumed_arn}</Arn>"
+ f"</AssumedRoleUser>"
+ f"<PackedPolicySize>0</PackedPolicySize>"
+ f"</AssumeRoleResult>",
+ ns="sts")
+
+ if action == "AssumeRoleWithWebIdentity":
+ role_arn = _p(params, "RoleArn")
+ session = _p(params, "RoleSessionName", "session")
+ duration = int(_p(params, "DurationSeconds") or 3600)
+ access_key = _gen_session_access_key()
+ secret_key = _gen_secret()
+ session_token = _gen_session_token()
+ assumed_arn = role_arn.replace(":role/", ":assumed-role/", 1)
+ if not assumed_arn.endswith(f"/{session}"):
+ assumed_arn = f"{assumed_arn}/{session}"
+ role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
+ if use_json:
+ return json_response({
+ "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
+ "AssumedRoleUser": {"AssumedRoleId": f"{role_id}:{session}", "Arn": assumed_arn},
+ "SubjectFromWebIdentityToken": "test-subject",
+ "Audience": "sts.amazonaws.com",
+ "Provider": "accounts.google.com",
+ })
+ return _xml(200, "AssumeRoleWithWebIdentityResponse",
+ f"<AssumeRoleWithWebIdentityResult>"
+ f"<Credentials>"
+ f"<AccessKeyId>{access_key}</AccessKeyId>"
+ f"<SecretAccessKey>{secret_key}</SecretAccessKey>"
+ f"<SessionToken>{session_token}</SessionToken>"
+ f"<Expiration>{_future(duration)}</Expiration>"
+ f"</Credentials>"
+ f"<AssumedRoleUser>"
+ f"<AssumedRoleId>{role_id}:{session}</AssumedRoleId>"
+ f"<Arn>{assumed_arn}</Arn>"
+ f"</AssumedRoleUser>"
+ f"<SubjectFromWebIdentityToken>test-subject</SubjectFromWebIdentityToken>"
+ f"<Audience>sts.amazonaws.com</Audience>"
+ f"<Provider>accounts.google.com</Provider>"
+ f"</AssumeRoleWithWebIdentityResult>",
+ ns="sts")
+
+ if action == "GetSessionToken":
+ duration = int(_p(params, "DurationSeconds") or 43200)
+ expiration = _future(duration)
+ access_key = _gen_session_access_key()
+ secret_key = _gen_secret()
+ session_token = _gen_session_token()
+ if use_json:
+ return json_response({
+ "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
+ })
+ return _xml(200, "GetSessionTokenResponse",
+ f"<GetSessionTokenResult>"
+ f"<Credentials>"
+ f"<AccessKeyId>{access_key}</AccessKeyId>"
+ f"<SecretAccessKey>{secret_key}</SecretAccessKey>"
+ f"<SessionToken>{session_token}</SessionToken>"
+ f"<Expiration>{expiration}</Expiration>"
+ f"</Credentials>"
+ f"</GetSessionTokenResult>",
+ ns="sts")
+
+ if action == "GetAccessKeyInfo":
+ if use_json:
+ return json_response({"Account": get_account_id()})
+ return _xml(200, "GetAccessKeyInfoResponse",
+ f"<GetAccessKeyInfoResult>"
+ f"<Account>{get_account_id()}</Account>"
+ f"</GetAccessKeyInfoResult>",
+ ns="sts")
+
+ return _error(400, "InvalidAction", f"Unknown STS action: {action}", ns="sts")
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index dd1fe1e2..f8023134 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -1667,3 +1667,45 @@ def test_cfn_codebuild_project_idempotent_delete(cfn, codebuild):
cfn.delete_stack(StackName="cfn-cb-t07")
stack = _wait_stack(cfn, "cfn-cb-t07")
assert stack["StackStatus"] in ("DELETE_COMPLETE", "DOES_NOT_EXIST")
+
+
+def test_cfn_scheduler_schedule(cfn):
+ """AWS::Scheduler::Schedule and ScheduleGroup should provision and delete cleanly."""
+ template = json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Group": {
+ "Type": "AWS::Scheduler::ScheduleGroup",
+ "Properties": {"Name": "cfn-test-group"},
+ },
+ "Schedule": {
+ "Type": "AWS::Scheduler::Schedule",
+ "Properties": {
+ "Name": "cfn-test-schedule",
+ "GroupName": "cfn-test-group",
+ "ScheduleExpression": "rate(5 minutes)",
+ "FlexibleTimeWindow": {"Mode": "OFF"},
+ "Target": {
+ "Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test",
+ },
+ },
+ },
+ },
+ })
+ cfn.create_stack(StackName="cfn-scheduler-test", TemplateBody=template)
+ stack = _wait_stack(cfn, "cfn-scheduler-test")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ resources = {
+ r["ResourceType"]: r
+ for r in cfn.list_stack_resources(StackName="cfn-scheduler-test")["StackResourceSummaries"]
+ }
+ assert "AWS::Scheduler::Schedule" in resources
+ assert resources["AWS::Scheduler::Schedule"]["PhysicalResourceId"] == "cfn-test-schedule"
+ assert "AWS::Scheduler::ScheduleGroup" in resources
+ assert resources["AWS::Scheduler::ScheduleGroup"]["PhysicalResourceId"] == "cfn-test-group"
+
+ cfn.delete_stack(StackName="cfn-scheduler-test")
+ stack = _wait_stack(cfn, "cfn-scheduler-test")
+ assert stack["StackStatus"] == "DELETE_COMPLETE"
diff --git a/tests/test_ministack.py b/tests/test_ministack.py
index 26105df4..c8b9cd3f 100644
--- a/tests/test_ministack.py
+++ b/tests/test_ministack.py
@@ -108,7 +108,7 @@ def test_ministack_package_services_importable():
ssm,
stepfunctions,
)
- from ministack.services.iam_sts import handle_iam_request, handle_sts_request
+ from ministack.services import iam, sts
for mod in [
s3,
@@ -133,7 +133,7 @@ def test_ministack_package_services_importable():
firehose,
route53,
cognito,
+ iam,
+ sts,
]:
assert callable(getattr(mod, "handle_request", None)), f"{mod.__name__} missing handle_request"
- assert callable(handle_iam_request)
- assert callable(handle_sts_request)
diff --git a/tests/test_package.py b/tests/test_package.py
index 54bc6e92..552494be 100644
--- a/tests/test_package.py
+++ b/tests/test_package.py
@@ -57,7 +57,7 @@ def test_package_services_importable():
ssm,
stepfunctions,
)
- from ministack.services.iam_sts import handle_iam_request, handle_sts_request
+ from ministack.services import iam, sts
for mod in [
s3,
@@ -82,7 +82,7 @@ def test_package_services_importable():
firehose,
route53,
cognito,
+ iam,
+ sts,
]:
assert callable(getattr(mod, "handle_request", None)), f"{mod.__name__} missing handle_request"
- assert callable(handle_iam_request)
- assert callable(handle_sts_request)
diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py
new file mode 100644
index 00000000..b31ef4bb
--- /dev/null
+++ b/tests/test_scheduler.py
@@ -0,0 +1,457 @@
+import json
+import time
+import pytest
+import boto3
+from botocore.exceptions import ClientError
+
+ENDPOINT = "http://localhost:4566"
+REGION = "us-east-1"
+
+
[email protected](scope="module")
+def scheduler():
+ return boto3.client("scheduler", endpoint_url=ENDPOINT,
+ aws_access_key_id="test", aws_secret_access_key="test",
+ region_name=REGION)
+
+
[email protected](scope="module")
+def cfn():
+ return boto3.client("cloudformation", endpoint_url=ENDPOINT,
+ aws_access_key_id="test", aws_secret_access_key="test",
+ region_name=REGION)
+
+
+def _uid():
+ import uuid
+ return uuid.uuid4().hex[:8]
+
+
+# ---------------------------------------------------------------------------
+# Schedule Groups
+# ---------------------------------------------------------------------------
+
+def test_scheduler_default_group_exists(scheduler):
+ """The 'default' group should always exist."""
+ resp = scheduler.get_schedule_group(Name="default")
+ assert resp["Name"] == "default"
+ assert resp["State"] == "ACTIVE"
+ assert "Arn" in resp
+ assert "schedule-group/default" in resp["Arn"]
+
+
+def test_scheduler_create_get_delete_group(scheduler):
+ name = f"test-group-{_uid()}"
+ resp = scheduler.create_schedule_group(Name=name)
+ arn = resp["ScheduleGroupArn"]
+ assert f"schedule-group/{name}" in arn
+
+ # Get
+ resp = scheduler.get_schedule_group(Name=name)
+ assert resp["Name"] == name
+ assert resp["State"] == "ACTIVE"
+ assert resp["Arn"] == arn
+
+ # Delete
+ scheduler.delete_schedule_group(Name=name)
+ with pytest.raises(ClientError) as exc:
+ scheduler.get_schedule_group(Name=name)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_scheduler_create_duplicate_group(scheduler):
+ name = f"dup-group-{_uid()}"
+ scheduler.create_schedule_group(Name=name)
+ with pytest.raises(ClientError) as exc:
+ scheduler.create_schedule_group(Name=name)
+ assert exc.value.response["Error"]["Code"] == "ConflictException"
+ scheduler.delete_schedule_group(Name=name)
+
+
+def test_scheduler_cannot_delete_default_group(scheduler):
+ with pytest.raises(ClientError) as exc:
+ scheduler.delete_schedule_group(Name="default")
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+
+
+def test_scheduler_list_groups(scheduler):
+ name = f"list-group-{_uid()}"
+ scheduler.create_schedule_group(Name=name)
+ resp = scheduler.list_schedule_groups()
+ names = [g["Name"] for g in resp["ScheduleGroups"]]
+ assert "default" in names
+ assert name in names
+ scheduler.delete_schedule_group(Name=name)
+
+
+def test_scheduler_list_groups_name_prefix(scheduler):
+ prefix = f"pfx-{_uid()}"
+ scheduler.create_schedule_group(Name=f"{prefix}-a")
+ scheduler.create_schedule_group(Name=f"{prefix}-b")
+ resp = scheduler.list_schedule_groups(NamePrefix=prefix)
+ names = [g["Name"] for g in resp["ScheduleGroups"]]
+ assert len(names) == 2
+ assert all(n.startswith(prefix) for n in names)
+ scheduler.delete_schedule_group(Name=f"{prefix}-a")
+ scheduler.delete_schedule_group(Name=f"{prefix}-b")
+
+
+# ---------------------------------------------------------------------------
+# Schedules — CRUD
+# ---------------------------------------------------------------------------
+
+def test_scheduler_create_get_delete_schedule(scheduler):
+ name = f"test-sched-{_uid()}"
+ resp = scheduler.create_schedule(
+ Name=name,
+ ScheduleExpression="rate(1 hour)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={
+ "Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test",
+ },
+ )
+ arn = resp["ScheduleArn"]
+ assert f"schedule/default/{name}" in arn
+
+ # Get
+ resp = scheduler.get_schedule(Name=name)
+ assert resp["Name"] == name
+ assert resp["GroupName"] == "default"
+ assert resp["ScheduleExpression"] == "rate(1 hour)"
+ assert resp["State"] == "ENABLED"
+ assert resp["FlexibleTimeWindow"]["Mode"] == "OFF"
+ assert resp["Target"]["Arn"] == "arn:aws:lambda:us-east-1:000000000000:function:noop"
+ assert resp["Target"]["RoleArn"] == "arn:aws:iam::000000000000:role/test"
+ assert "CreationDate" in resp
+ assert "LastModificationDate" in resp
+
+ # Delete
+ scheduler.delete_schedule(Name=name)
+ with pytest.raises(ClientError) as exc:
+ scheduler.get_schedule(Name=name)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_scheduler_create_schedule_in_custom_group(scheduler):
+ group = f"custom-group-{_uid()}"
+ name = f"sched-{_uid()}"
+ scheduler.create_schedule_group(Name=group)
+
+ resp = scheduler.create_schedule(
+ Name=name,
+ GroupName=group,
+ ScheduleExpression="cron(0 12 * * ? *)",
+ FlexibleTimeWindow={"Mode": "FLEXIBLE", "MaximumWindowInMinutes": 15},
+ Target={
+ "Arn": "arn:aws:sqs:us-east-1:000000000000:my-queue",
+ "RoleArn": "arn:aws:iam::000000000000:role/test",
+ "Input": '{"key":"value"}',
+ },
+ )
+ assert f"schedule/{group}/{name}" in resp["ScheduleArn"]
+
+ resp = scheduler.get_schedule(Name=name, GroupName=group)
+ assert resp["GroupName"] == group
+ assert resp["ScheduleExpression"] == "cron(0 12 * * ? *)"
+ assert resp["FlexibleTimeWindow"]["Mode"] == "FLEXIBLE"
+ assert resp["FlexibleTimeWindow"]["MaximumWindowInMinutes"] == 15
+ assert resp["Target"]["Input"] == '{"key":"value"}'
+
+ scheduler.delete_schedule(Name=name, GroupName=group)
+ scheduler.delete_schedule_group(Name=group)
+
+
+def test_scheduler_create_duplicate_schedule(scheduler):
+ name = f"dup-sched-{_uid()}"
+ scheduler.create_schedule(
+ Name=name,
+ ScheduleExpression="rate(5 minutes)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ )
+ with pytest.raises(ClientError) as exc:
+ scheduler.create_schedule(
+ Name=name,
+ ScheduleExpression="rate(10 minutes)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ )
+ assert exc.value.response["Error"]["Code"] == "ConflictException"
+ scheduler.delete_schedule(Name=name)
+
+
+def test_scheduler_delete_nonexistent_schedule(scheduler):
+ with pytest.raises(ClientError) as exc:
+ scheduler.delete_schedule(Name="nonexistent-schedule-xyz")
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_scheduler_get_nonexistent_schedule(scheduler):
+ with pytest.raises(ClientError) as exc:
+ scheduler.get_schedule(Name="nonexistent-schedule-xyz")
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+# ---------------------------------------------------------------------------
+# UpdateSchedule
+# ---------------------------------------------------------------------------
+
+def test_scheduler_update_schedule(scheduler):
+ name = f"upd-sched-{_uid()}"
+ scheduler.create_schedule(
+ Name=name,
+ ScheduleExpression="rate(1 hour)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:old",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ State="ENABLED",
+ )
+
+ resp = scheduler.update_schedule(
+ Name=name,
+ ScheduleExpression="rate(30 minutes)",
+ FlexibleTimeWindow={"Mode": "FLEXIBLE", "MaximumWindowInMinutes": 5},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:new",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ State="DISABLED",
+ Description="Updated schedule",
+ )
+ assert "ScheduleArn" in resp
+
+ resp = scheduler.get_schedule(Name=name)
+ assert resp["ScheduleExpression"] == "rate(30 minutes)"
+ assert resp["State"] == "DISABLED"
+ assert resp["Description"] == "Updated schedule"
+ assert resp["Target"]["Arn"] == "arn:aws:lambda:us-east-1:000000000000:function:new"
+
+ scheduler.delete_schedule(Name=name)
+
+
+def test_scheduler_update_nonexistent_schedule(scheduler):
+ with pytest.raises(ClientError) as exc:
+ scheduler.update_schedule(
+ Name="nonexistent-xyz",
+ ScheduleExpression="rate(1 hour)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ )
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+# ---------------------------------------------------------------------------
+# ListSchedules
+# ---------------------------------------------------------------------------
+
+def test_scheduler_list_schedules(scheduler):
+ prefix = f"ls-{_uid()}"
+ for i in range(3):
+ scheduler.create_schedule(
+ Name=f"{prefix}-{i}",
+ ScheduleExpression="rate(1 hour)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ )
+ resp = scheduler.list_schedules(NamePrefix=prefix)
+ names = [s["Name"] for s in resp["Schedules"]]
+ assert len(names) == 3
+ # Each item should have abbreviated Target with just Arn
+ for s in resp["Schedules"]:
+ assert "Arn" in s["Target"]
+ assert "CreationDate" in s
+
+ for i in range(3):
+ scheduler.delete_schedule(Name=f"{prefix}-{i}")
+
+
+def test_scheduler_list_schedules_filter_by_group(scheduler):
+ group = f"filter-group-{_uid()}"
+ scheduler.create_schedule_group(Name=group)
+ scheduler.create_schedule(
+ Name=f"in-group-{_uid()}", GroupName=group,
+ ScheduleExpression="rate(1 hour)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ )
+ scheduler.create_schedule(
+ Name=f"in-default-{_uid()}",
+ ScheduleExpression="rate(1 hour)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ )
+
+ resp = scheduler.list_schedules(GroupName=group)
+ assert all(s["GroupName"] == group for s in resp["Schedules"])
+ assert len(resp["Schedules"]) == 1
+
+ # Cleanup
+ scheduler.delete_schedule_group(Name=group)
+
+
+def test_scheduler_list_schedules_filter_by_state(scheduler):
+ name_e = f"enabled-{_uid()}"
+ name_d = f"disabled-{_uid()}"
+ for n, s in [(name_e, "ENABLED"), (name_d, "DISABLED")]:
+ scheduler.create_schedule(
+ Name=n, State=s,
+ ScheduleExpression="rate(1 hour)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ )
+ resp = scheduler.list_schedules(State="DISABLED", NamePrefix="disabled-")
+ assert all(s["State"] == "DISABLED" for s in resp["Schedules"])
+ scheduler.delete_schedule(Name=name_e)
+ scheduler.delete_schedule(Name=name_d)
+
+
+# ---------------------------------------------------------------------------
+# Schedule with at() expression
+# ---------------------------------------------------------------------------
+
+def test_scheduler_at_expression(scheduler):
+ name = f"at-sched-{_uid()}"
+ scheduler.create_schedule(
+ Name=name,
+ ScheduleExpression="at(2030-01-01T00:00:00)",
+ ScheduleExpressionTimezone="America/New_York",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ ActionAfterCompletion="DELETE",
+ )
+ resp = scheduler.get_schedule(Name=name)
+ assert resp["ScheduleExpression"] == "at(2030-01-01T00:00:00)"
+ assert resp["ScheduleExpressionTimezone"] == "America/New_York"
+ assert resp["ActionAfterCompletion"] == "DELETE"
+ scheduler.delete_schedule(Name=name)
+
+
+# ---------------------------------------------------------------------------
+# Tags
+# ---------------------------------------------------------------------------
+
+def test_scheduler_tag_schedule(scheduler):
+ name = f"tag-sched-{_uid()}"
+ resp = scheduler.create_schedule(
+ Name=name,
+ ScheduleExpression="rate(1 hour)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ )
+ arn = resp["ScheduleArn"]
+
+ scheduler.tag_resource(ResourceArn=arn, Tags=[
+ {"Key": "env", "Value": "test"},
+ {"Key": "team", "Value": "platform"},
+ ])
+
+ resp = scheduler.list_tags_for_resource(ResourceArn=arn)
+ tags = {t["Key"]: t["Value"] for t in resp["Tags"]}
+ assert tags == {"env": "test", "team": "platform"}
+
+ scheduler.untag_resource(ResourceArn=arn, TagKeys=["team"])
+ resp = scheduler.list_tags_for_resource(ResourceArn=arn)
+ tags = {t["Key"]: t["Value"] for t in resp["Tags"]}
+ assert tags == {"env": "test"}
+
+ scheduler.delete_schedule(Name=name)
+
+
+def test_scheduler_tag_group(scheduler):
+ name = f"tag-group-{_uid()}"
+ scheduler.create_schedule_group(Name=name, Tags=[
+ {"Key": "env", "Value": "prod"},
+ ])
+ arn = scheduler.get_schedule_group(Name=name)["Arn"]
+ resp = scheduler.list_tags_for_resource(ResourceArn=arn)
+ tags = {t["Key"]: t["Value"] for t in resp["Tags"]}
+ assert tags == {"env": "prod"}
+ scheduler.delete_schedule_group(Name=name)
+
+
+# ---------------------------------------------------------------------------
+# Delete group cascades to schedules
+# ---------------------------------------------------------------------------
+
+def test_scheduler_delete_group_deletes_schedules(scheduler):
+ group = f"cascade-group-{_uid()}"
+ scheduler.create_schedule_group(Name=group)
+ for i in range(3):
+ scheduler.create_schedule(
+ Name=f"cascade-{i}", GroupName=group,
+ ScheduleExpression="rate(1 hour)",
+ FlexibleTimeWindow={"Mode": "OFF"},
+ Target={"Arn": "arn:aws:lambda:us-east-1:000000000000:function:noop",
+ "RoleArn": "arn:aws:iam::000000000000:role/test"},
+ )
+ resp = scheduler.list_schedules(GroupName=group)
+ assert len(resp["Schedules"]) == 3
+
+ scheduler.delete_schedule_group(Name=group)
+
+ # Group gone
+ with pytest.raises(ClientError) as exc:
+ scheduler.get_schedule_group(Name=group)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+# ---------------------------------------------------------------------------
+# CloudFormation integration
+# ---------------------------------------------------------------------------
+
+def test_scheduler_cfn_creates_schedule(cfn, scheduler):
+ """AWS::Scheduler::Schedule via CFN should be queryable via Scheduler API."""
+ uid = _uid()
+ sched_name = f"cfn-sched-{uid}"
+ group_name = f"cfn-group-{uid}"
+
+ template = json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Group": {
+ "Type": "AWS::Scheduler::ScheduleGroup",
+ "Properties": {"Name": group_name},
+ },
+ "Schedule": {
+ "Type": "AWS::Scheduler::Schedule",
+ "Properties": {
+ "Name": sched_name,
+ "GroupName": group_name,
+ "ScheduleExpression": "rate(10 minutes)",
+ "FlexibleTimeWindow": {"Mode": "OFF"},
+ "Target": {
+ "Arn": "arn:aws:lambda:us-east-1:000000000000:function:cfn-target",
+ "RoleArn": "arn:aws:iam::000000000000:role/test",
+ },
+ },
+ },
+ },
+ })
+
+ stack_name = f"sched-stack-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ time.sleep(2)
+
+ stack = cfn.describe_stacks(StackName=stack_name)["Stacks"][0]
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ # Verify via Scheduler API
+ resp = scheduler.get_schedule(Name=sched_name, GroupName=group_name)
+ assert resp["Name"] == sched_name
+ assert resp["GroupName"] == group_name
+ assert resp["ScheduleExpression"] == "rate(10 minutes)"
+
+ resp = scheduler.get_schedule_group(Name=group_name)
+ assert resp["Name"] == group_name
+
+ # Delete stack
+ cfn.delete_stack(StackName=stack_name)
+ time.sleep(1)