Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
Feat/acm ses v2 waf lambda layers v1.1.11 (#46)
Nahuel Nucera5a0038d03b02
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 140eebb8..73ae7aff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,24 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.1.11] — 2026-03-31++### Added+- **ACM (Certificate Manager)** — full control plane: `RequestCertificate`, `DescribeCertificate`, `ListCertificates`, `DeleteCertificate`, `GetCertificate`, `ImportCertificate`, `AddTagsToCertificate`, `RemoveTagsFromCertificate`, `ListTagsForCertificate`, `UpdateCertificateOptions`, `RenewCertificate`, `ResendValidationEmail`; certificates issued immediately with status `ISSUED` and DNS validation records; compatible with Terraform `aws_acm_certificate` and CDK `Certificate`+- **SES v2** — REST API at `/v2/email/`: `SendEmail`, `CreateEmailIdentity`, `GetEmailIdentity`, `DeleteEmailIdentity`, `ListEmailIdentities`, `CreateConfigurationSet`, `GetConfigurationSet`, `DeleteConfigurationSet`, `ListConfigurationSets`, `GetAccount`, `ListSuppressedDestinations`, `TagResource`, `UntagResource`, `ListTagsForResource`; identities auto-verified; compatible with Terraform `aws_sesv2_email_identity` and CDK `EmailIdentity`+- **WAF v2** — full control plane: WebACL CRUD, IPSet CRUD, RuleGroup CRUD (including `UpdateRuleGroup`), `AssociateWebACL`/`DisassociateWebACL`, `GetWebACLForResource`, `ListResourcesForWebACL`, `TagResource`/`UntagResource`/`ListTagsForResource`, `CheckCapacity`, `DescribeManagedRuleGroup`; LockToken enforced on Update/Delete; rules stored but not enforced; compatible with Terraform `aws_wafv2_web_acl` and CDK `CfnWebACL`+- **Lambda Layers** — `PublishLayerVersion`, `GetLayerVersion`, `ListLayerVersions`, `ListLayers`, `DeleteLayerVersion`; layer zip content stored in-memory and injected into function execution environment++### Fixed+- **WAF v2 `GetWebACL`/`GetIPSet`/`GetRuleGroup`** — `LockToken` was incorrectly included inside the resource body; now only returned at the top level, matching real AWS and fixing CDK/Terraform Update flows+- **WAF v2 `GetWebACLForResource`** — now returns `WAFNonexistentItemException` when no association exists, matching real AWS behaviour+- **SES v2 `TagResource`/`UntagResource`/`ListTagsForResource`** — added; Terraform calls these after `CreateEmailIdentity`++### Tests+- 763 tests total, all passing++---+## [1.1.10] — 2026-03-31### Fixeddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 4b1e114d..51b01d96 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -170,6 +170,7 @@ pytest tests/ -v -k "cognito"- [ ] Detection patterns added to `ministack/core/router.py`- [ ] Fixture added to `tests/conftest.py`- [ ] Tests added and passing (`pytest tests/ -v`)+- [ ] Linting passes (`ruff check ministack/`)- [ ] Service added to the table in `README.md`- [ ] Entry added to `CHANGELOG.md`- [ ] Version bumped in `pyproject.toml`@@ -180,11 +181,11 @@ pytest tests/ -v -k "cognito"High-value contributions right now:-- **ACM** — certificate provisioning and validation stubs-- **More S3 operations** — object lock, replication configuration, object tagging-- **SES v2** — `ses:SendEmail` with the v2 API shapes-- **Lambda layers** — `PublishLayerVersion`, `GetLayerVersion`, `ListLayerVersions`-- **More Cognito flows** — hosted UI, federated identity providers+- **CloudFront** — distribution CRUD, invalidations, origin configuration+- **CodeBuild / CodePipeline** — CI/CD pipeline stubs+- **AppSync** — GraphQL API CRUD+- **SQS FIFO** — message group / deduplication support+- **More Cognito flows** — hosted UI, federated identity providers, custom auth triggers---diff --git a/README.md b/README.mdindex 375f097b..dc786178 100644--- a/README.md+++ b/README.md@@ -202,9 +202,9 @@ subnet = ec2.create_subnet(| **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch, DeleteMessageBatch, TagQueue, UntagQueue, ListQueueTags | Both Query API and JSON protocol; FIFO queues with deduplication; DLQ support || **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, CreatePlatformEndpoint | SNS→SQS fanout delivery; SNS→Lambda fanout (synchronous invocation) || **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource | TTL enforced via thread-safe background reaper (60s cadence) |-| **Lambda** | CreateFunction, DeleteFunction, GetFunction, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, ListVersionsByFunction, PublishVersion, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs | Python runtimes actually execute with warm worker pool; SQS event source mapping; Function URL CRUD |+| **Lambda** | CreateFunction, DeleteFunction, GetFunction, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, ListVersionsByFunction, PublishVersion, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PublishLayerVersion, GetLayerVersion, ListLayerVersions, DeleteLayerVersion, ListLayers | Python runtimes actually execute with warm worker pool; SQS event source mapping; Function URL CRUD; Lambda Layers CRUD || **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, CreateOpenIDConnectProvider, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | |-| **STS** | GetCallerIdentity, AssumeRole, GetSessionToken | |+| **STS** | GetCallerIdentity, AssumeRole, GetSessionToken, AssumeRoleWithWebIdentity | || **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | || **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations | `FilterLogEvents` supports `*`/`?` globs, multi-term AND, `-term` exclusion |@@ -217,6 +217,9 @@ subnet = ec2.create_subnet(| **Kinesis** | CreateStream, DeleteStream, DescribeStream, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing || **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol || **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent |+| **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, GetAccount, PutAccountSuppressionAttributes, ListSuppressedDestinations | REST API (`/v2/email/`); identities auto-verified; emails stored in-memory, not sent |+| **ACM** | RequestCertificate, DescribeCertificate, ListCertificates, DeleteCertificate, GetCertificate, ImportCertificate, AddTagsToCertificate, RemoveTagsFromCertificate, ListTagsForCertificate, UpdateCertificateOptions, RenewCertificate, ResendValidationEmail | Certificates auto-issued; DNS validation records generated; supports SANs |+| **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked || **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel || **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags | HTTP API (v2) protocol; Lambda proxy (AWS_PROXY) and HTTP proxy (HTTP_PROXY) integrations; data plane via `{apiId}.execute-api.localhost`; `{param}` and `{proxy+}` path matching; JWT/Lambda authorizer CRUD || **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence |@@ -439,12 +442,12 @@ MiniStack keeps Python Lambda functions warm between invocations. After the firs│ │ S3 SQS SNS DynamoDB │ ││ │ Lambda IAM STS Secrets │ ││ │ SSM EventBridge Kinesis │ │- │ │ CW Logs CW Metrics SES │ │+ │ │ 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 │ │+ │ │ ALB/ELBv2 ACM WAFv2 │ ││ └──────────────────────────────────┘ ││ ││ In-Memory Storage + Optional Docker │@@ -467,20 +470,20 @@ pip install boto3 pytest duckdb docker cbor2# Start MiniStackdocker compose up -d-# Run the full test suite (737 tests across all 30 services)+# Run the full test suite (760 tests across all 33 services)pytest tests/ -v```Expected output:```-collected 737 items+collected 760 itemstests/test_services.py::test_s3_create_bucket PASSED...tests/test_services.py::test_app_asgi_callable PASSED-737 passed in ~60s+760 passed in ~60s```---@@ -582,6 +585,9 @@ config:| **ELBv2 / ALB** | ✅ | ✅ | ✅ || **EBS** | ✅ | Paid | ✅ || **EFS** | ✅ | Paid | ✅ |+| **ACM** | ✅ | ✅ | ✅ |+| **SES v2** | ✅ | ✅ | ✅ |+| **WAF v2** | ✅ | Paid | ✅ || CloudFormation | ❌ | partial | ✅ || Cost | **Free** | Was free, now paid | $35+/mo || Docker image size | ~150MB | ~1GB | ~1GB |diff --git a/ministack/app.py b/ministack/app.pyindex 7a3bdf87..2c2795aa 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -26,6 +26,7 @@ _S3_VHOST_EXCLUDE_RE = re.compile(r"\.(execute-api|alb|emr|efs|elasticache)\.")from ministack.core.persistence import PERSIST_STATE, load_state, save_allfrom ministack.core.router import detect_service, extract_account_id, extract_regionfrom ministack.services import (+ acm,alb,apigateway,apigateway_v1,@@ -49,10 +50,12 @@ from ministack.services import (s3,secretsmanager,ses,+ ses_v2,sns,sqs,ssm,stepfunctions,+ waf,)from ministack.services.iam_sts import handle_iam_request, handle_sts_request@@ -79,6 +82,8 @@ SERVICE_HANDLERS = {"kinesis": kinesis.handle_request,"monitoring": cloudwatch.handle_request,"ses": ses.handle_request,+ "acm": acm.handle_request,+ "wafv2": waf.handle_request,"states": stepfunctions.handle_request,"ecs": ecs.handle_request,"rds": rds.handle_request,@@ -144,7 +149,7 @@ BANNER = r"""Local AWS Service Emulator — Port {port}Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,- SSM, EventBridge, Kinesis, CloudWatch, SES, Step Functions,+ SSM, EventBridge, Kinesis, CloudWatch, SES, SES v2, ACM, WAF v2, Step Functions,ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2"""@@ -222,6 +227,12 @@ async def app(scope, receive, send):}, b"{}")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)+ await _send_response(send, status, resp_headers, resp_body)+ return+if path in ("/_localstack/health", "/health", "/_ministack/health"):await _send_response(send, 200, {"Content-Type": "application/json",@@ -486,6 +497,9 @@ def _reset_all_state():(ec2, ec2.reset),(emr, emr.reset),(alb, alb.reset),+ (acm, acm.reset),+ (ses_v2, ses_v2.reset),+ (waf, waf.reset),(efs, efs.reset),]:try:diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 464f4bf7..fa3982d7 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -135,6 +135,16 @@ SERVICE_PATTERNS = {"elasticloadbalancing": {"host_patterns": [r"elasticloadbalancing\."],},+ "acm": {+ "target_prefixes": ["CertificateManager"],+ "host_patterns": [r"acm\."],+ "credential_scope": "acm",+ },+ "wafv2": {+ "target_prefixes": ["AWSWAF_20190729"],+ "host_patterns": [r"wafv2\."],+ "credential_scope": "wafv2",+ },}@@ -175,6 +185,8 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"athena": "athena","kinesis-firehose": "firehose","route53": "route53",+ "acm": "acm",+ "wafv2": "wafv2","cognito-idp": "cognito-idp","cognito-identity": "cognito-identity","elasticmapreduce": "elasticmapreduce",diff --git a/ministack/services/acm.py b/ministack/services/acm.pynew file mode 100644index 00000000..bc582097--- /dev/null+++ b/ministack/services/acm.py@@ -0,0 +1,237 @@+"""+ACM (Certificate Manager) Service Emulator.+JSON-based API via X-Amz-Target.+Supports: RequestCertificate, DescribeCertificate, ListCertificates,+ DeleteCertificate, GetCertificate, ImportCertificate,+ AddTagsToCertificate, RemoveTagsFromCertificate, ListTagsForCertificate,+ UpdateCertificateOptions, RenewCertificate, ResendValidationEmail.+"""++import json+import logging+import time++from ministack.core.responses import error_response_json, json_response, new_uuid, now_iso++logger = logging.getLogger("acm")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_certificates: dict = {} # arn -> certificate dict+++def _future_iso(seconds):+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + seconds))+++def _cert_arn():+ return f"arn:aws:acm:{REGION}:{ACCOUNT_ID}:certificate/{new_uuid()}"+++def _validation_options(domain, method):+ return {+ "DomainName": domain,+ "ValidationMethod": method,+ "ValidationStatus": "SUCCESS",+ "ResourceRecord": {+ "Name": f"_acme-challenge.{domain}.",+ "Type": "CNAME",+ "Value": f"fake-validation-{new_uuid()[:8]}.acm.amazonaws.com.",+ },+ }+++def _cert_shape(cert):+ return {+ "CertificateArn": cert["CertificateArn"],+ "DomainName": cert["DomainName"],+ "SubjectAlternativeNames": cert.get("SubjectAlternativeNames", [cert["DomainName"]]),+ "Status": cert["Status"],+ "Type": cert.get("Type", "AMAZON_ISSUED"),+ "KeyAlgorithm": "RSA_2048",+ "SignatureAlgorithm": "SHA256WITHRSA",+ "InUseBy": cert.get("InUseBy", []),+ "CreatedAt": cert["CreatedAt"],+ "IssuedAt": cert.get("IssuedAt", cert["CreatedAt"]),+ "NotBefore": cert.get("NotBefore", cert["CreatedAt"]),+ "NotAfter": cert.get("NotAfter", _future_iso(365 * 24 * 3600)),+ "DomainValidationOptions": cert.get("DomainValidationOptions", []),+ "Options": cert.get("Options", {}),+ "Tags": cert.get("Tags", []),+ }+++async def handle_request(method, path, headers, body, query_params):+ target = headers.get("x-amz-target", "")+ action = target.split(".")[-1] if "." in target else ""++ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ return error_response_json("SerializationException", "Invalid JSON", 400)++ handlers = {+ "RequestCertificate": _request_certificate,+ "DescribeCertificate": _describe_certificate,+ "ListCertificates": _list_certificates,+ "DeleteCertificate": _delete_certificate,+ "GetCertificate": _get_certificate,+ "ImportCertificate": _import_certificate,+ "AddTagsToCertificate": _add_tags,+ "RemoveTagsFromCertificate": _remove_tags,+ "ListTagsForCertificate": _list_tags,+ "UpdateCertificateOptions": _update_options,+ "RenewCertificate": _renew_certificate,+ "ResendValidationEmail": _resend_validation_email,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown action: {action}", 400)+ return handler(data)+++def _request_certificate(data):+ domain = data.get("DomainName", "")+ if not domain:+ return error_response_json("InvalidParameterException", "DomainName is required", 400)+ method = data.get("ValidationMethod", "DNS")+ sans = data.get("SubjectAlternativeNames", [domain])+ if domain not in sans:+ sans = [domain] + sans+ arn = _cert_arn()+ now = now_iso()+ _certificates[arn] = {+ "CertificateArn": arn,+ "DomainName": domain,+ "SubjectAlternativeNames": sans,+ "Status": "ISSUED",+ "Type": "AMAZON_ISSUED",+ "CreatedAt": now,+ "IssuedAt": now,+ "NotBefore": now,+ "NotAfter": _future_iso(365 * 24 * 3600),+ "DomainValidationOptions": [_validation_options(d, method) for d in sans],+ "ValidationMethod": method,+ "Tags": data.get("Tags", []),+ "Options": {},+ }+ logger.info("RequestCertificate: %s -> %s", domain, arn)+ return json_response({"CertificateArn": arn})+++def _describe_certificate(data):+ arn = data.get("CertificateArn", "")+ cert = _certificates.get(arn)+ if not cert:+ return error_response_json("ResourceNotFoundException", f"Certificate {arn} not found", 400)+ return json_response({"Certificate": _cert_shape(cert)})+++def _list_certificates(data):+ statuses = data.get("CertificateStatuses", [])+ summaries = []+ for arn, cert in _certificates.items():+ if statuses and cert["Status"] not in statuses:+ continue+ summaries.append({+ "CertificateArn": arn,+ "DomainName": cert["DomainName"],+ "Status": cert["Status"],+ })+ return json_response({"CertificateSummaryList": summaries, "NextToken": None})+++def _delete_certificate(data):+ arn = data.get("CertificateArn", "")+ if arn not in _certificates:+ return error_response_json("ResourceNotFoundException", f"Certificate {arn} not found", 400)+ del _certificates[arn]+ return json_response({})+++def _get_certificate(data):+ arn = data.get("CertificateArn", "")+ if arn not in _certificates:+ return error_response_json("ResourceNotFoundException", f"Certificate {arn} not found", 400)+ fake_pem = "-----BEGIN CERTIFICATE-----\nMIIFakeCertificateDataHere\n-----END CERTIFICATE-----"+ fake_chain = "-----BEGIN CERTIFICATE-----\nMIIFakeChainDataHere\n-----END CERTIFICATE-----"+ return json_response({"Certificate": fake_pem, "CertificateChain": fake_chain})+++def _import_certificate(data):+ arn = data.get("CertificateArn") or _cert_arn()+ now = now_iso()+ _certificates[arn] = {+ "CertificateArn": arn,+ "DomainName": "imported.example.com",+ "SubjectAlternativeNames": ["imported.example.com"],+ "Status": "ISSUED",+ "Type": "IMPORTED",+ "CreatedAt": now,+ "IssuedAt": now,+ "NotBefore": now,+ "NotAfter": _future_iso(365 * 24 * 3600),+ "DomainValidationOptions": [],+ "Tags": data.get("Tags", []),+ "Options": {},+ }+ return json_response({"CertificateArn": arn})+++def _add_tags(data):+ arn = data.get("CertificateArn", "")+ cert = _certificates.get(arn)+ if not cert:+ return error_response_json("ResourceNotFoundException", f"Certificate {arn} not found", 400)+ existing = {t["Key"]: t for t in cert.get("Tags", [])}+ for tag in data.get("Tags", []):+ existing[tag["Key"]] = tag+ cert["Tags"] = list(existing.values())+ return json_response({})+++def _remove_tags(data):+ arn = data.get("CertificateArn", "")+ cert = _certificates.get(arn)+ if not cert:+ return error_response_json("ResourceNotFoundException", f"Certificate {arn} not found", 400)+ remove_keys = {t["Key"] for t in data.get("Tags", [])}+ cert["Tags"] = [t for t in cert.get("Tags", []) if t["Key"] not in remove_keys]+ return json_response({})+++def _list_tags(data):+ arn = data.get("CertificateArn", "")+ cert = _certificates.get(arn)+ if not cert:+ return error_response_json("ResourceNotFoundException", f"Certificate {arn} not found", 400)+ return json_response({"Tags": cert.get("Tags", [])})+++def _update_options(data):+ arn = data.get("CertificateArn", "")+ cert = _certificates.get(arn)+ if not cert:+ return error_response_json("ResourceNotFoundException", f"Certificate {arn} not found", 400)+ cert["Options"] = data.get("Options", {})+ return json_response({})+++def _renew_certificate(data):+ arn = data.get("CertificateArn", "")+ if arn not in _certificates:+ return error_response_json("ResourceNotFoundException", f"Certificate {arn} not found", 400)+ return json_response({})+++def _resend_validation_email(data):+ arn = data.get("CertificateArn", "")+ if arn not in _certificates:+ return error_response_json("ResourceNotFoundException", f"Certificate {arn} not found", 400)+ return json_response({})+++def reset():+ _certificates.clear()diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.pynew file mode 100644index 00000000..743dbd94--- /dev/null+++ b/ministack/services/ses_v2.py@@ -0,0 +1,161 @@+"""+SES v2 Service Emulator.+REST/JSON API via path /v2/email/...+Supports: SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity,+ ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet,+ DeleteConfigurationSet, ListConfigurationSets, GetAccount,+ ListSuppressedDestinations, PutAccountSuppressionAttributes,+ TagResource, UntagResource, ListTagsForResource.+"""++import json+import logging+import re++from ministack.core.responses import json_response, new_uuid, now_iso++logger = logging.getLogger("ses-v2")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_identities: dict = {} # identity -> dict+_config_sets: dict = {} # name -> dict+_ses_tags: dict = {} # resource_arn -> [tags]+++def _json_err(code, message, status=400):+ body = json.dumps({"message": message, "name": code}).encode("utf-8")+ return status, {"Content-Type": "application/json"}, body+++async def handle_request(method, path, headers, body, query_params):+ # Strip /v2/email prefix+ sub = path[len("/v2/email"):]++ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ data = {}++ # GET /v2/email/account+ if sub == "/account" and method == "GET":+ return json_response({+ "DedicatedIpAutoWarmupEnabled": False,+ "EnforcementStatus": "HEALTHY",+ "ProductionAccessEnabled": True,+ "SendQuota": {"Max24HourSend": 50000.0, "MaxSendRate": 14.0, "SentLast24Hours": 0.0},+ "SendingEnabled": True,+ "SuppressionAttributes": {"SuppressedReasons": []},+ })++ # PUT /v2/email/account/suppression+ if sub == "/account/suppression" and method == "PUT":+ return json_response({})++ # GET /v2/email/suppression/addresses+ if sub == "/suppression/addresses" and method == "GET":+ return json_response({"SuppressedDestinationSummaries": [], "NextToken": None})++ # POST /v2/email/outbound-emails (SendEmail)+ if sub == "/outbound-emails" and method == "POST":+ msg_id = f"ministack-{new_uuid()}"+ logger.info("SESv2 SendEmail: MessageId=%s", msg_id)+ return json_response({"MessageId": msg_id})++ # POST /v2/email/identities (CreateEmailIdentity)+ if sub == "/identities" and method == "POST":+ identity = data.get("EmailIdentity", "")+ if not identity:+ return _json_err("BadRequestException", "EmailIdentity is required")+ identity_type = "DOMAIN" if "." in identity and "@" not in identity else "EMAIL_ADDRESS"+ _identities[identity] = {+ "EmailIdentity": identity,+ "IdentityType": identity_type,+ "VerifiedForSendingStatus": True,+ "DkimAttributes": {"SigningEnabled": False, "Status": "NOT_STARTED", "Tokens": []},+ "MailFromAttributes": {"BehaviorOnMxFailure": "USE_DEFAULT_VALUE"},+ "Tags": data.get("Tags", []),+ "CreatedTimestamp": now_iso(),+ }+ return json_response({+ "IdentityType": identity_type,+ "VerifiedForSendingStatus": True,+ "DkimAttributes": {"SigningEnabled": False, "Status": "NOT_STARTED", "Tokens": []},+ })++ # GET /v2/email/identities (ListEmailIdentities)+ if sub == "/identities" and method == "GET":+ return json_response({+ "EmailIdentities": [+ {"IdentityType": v["IdentityType"], "IdentityName": k, "SendingEnabled": True}+ for k, v in _identities.items()+ ],+ "NextToken": None,+ })++ # GET /v2/email/identities/{identity}+ m = re.match(r"^/identities/(.+)$", sub)+ if m:+ identity = m.group(1)+ if method == "GET":+ rec = _identities.get(identity)+ if not rec:+ return _json_err("NotFoundException", f"Identity {identity} not found", 404)+ return json_response(rec)+ if method == "DELETE":+ _identities.pop(identity, None)+ return json_response({})++ # POST /v2/email/configuration-sets (CreateConfigurationSet)+ if sub == "/configuration-sets" and method == "POST":+ name = data.get("ConfigurationSetName", "")+ if not name:+ return _json_err("BadRequestException", "ConfigurationSetName is required")+ _config_sets[name] = {"ConfigurationSetName": name, "Tags": data.get("Tags", [])}+ return json_response({})++ # GET /v2/email/configuration-sets (ListConfigurationSets)+ if sub == "/configuration-sets" and method == "GET":+ return json_response({"ConfigurationSets": list(_config_sets.keys()), "NextToken": None})++ # GET/DELETE /v2/email/configuration-sets/{name}+ m = re.match(r"^/configuration-sets/([^/]+)$", sub)+ if m:+ name = m.group(1)+ if method == "GET":+ rec = _config_sets.get(name)+ if not rec:+ return _json_err("NotFoundException", f"ConfigurationSet {name} not found", 404)+ return json_response(rec)+ if method == "DELETE":+ _config_sets.pop(name, None)+ return json_response({})++ # GET/POST/DELETE /v2/email/tags (ListTagsForResource / TagResource / UntagResource)+ if sub == "/tags" and method == "GET":+ arn = query_params.get("ResourceArn", [""])[0] if isinstance(query_params.get("ResourceArn"), list) else query_params.get("ResourceArn", "")+ return json_response({"Tags": _ses_tags.get(arn, [])})++ m = re.match(r"^/tags$", sub)+ if m and method == "POST":+ arn = data.get("ResourceArn", "")+ existing = {t["Key"]: t for t in _ses_tags.get(arn, [])}+ for tag in data.get("Tags", []):+ existing[tag["Key"]] = tag+ _ses_tags[arn] = list(existing.values())+ return json_response({})++ if sub == "/tags" and method == "DELETE":+ arn = query_params.get("ResourceArn", [""])[0] if isinstance(query_params.get("ResourceArn"), list) else query_params.get("ResourceArn", "")+ remove_keys = set(query_params.get("TagKeys", []))+ _ses_tags[arn] = [t for t in _ses_tags.get(arn, []) if t["Key"] not in remove_keys]+ return json_response({})++ return _json_err("NotFoundException", f"Unknown SES v2 path: {method} {path}", 404)+++def reset():+ _identities.clear()+ _config_sets.clear()+ _ses_tags.clear()diff --git a/ministack/services/waf.py b/ministack/services/waf.pynew file mode 100644index 00000000..9ff1fbf1--- /dev/null+++ b/ministack/services/waf.py@@ -0,0 +1,365 @@+"""+WAF v2 Service Emulator.+JSON-based API via X-Amz-Target: AWSWAF_20190729.+Supports: CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs,+ AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL,+ CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets,+ CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups,+ TagResource, UntagResource, ListTagsForResource,+ CheckCapacity, DescribeManagedRuleGroup.+"""++import json+import logging++from ministack.core.responses import error_response_json, json_response, new_uuid, now_iso++logger = logging.getLogger("wafv2")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_web_acls: dict = {} # id -> webacl+_ip_sets: dict = {} # id -> ipset+_rule_groups: dict = {} # id -> rulegroup+_associations: dict = {} # resource_arn -> webacl_arn+_waf_tags: dict = {} # resource_arn -> [tags]+++def _waf_err(code, message):+ return error_response_json(code, message, 400)+++def _acl_arn(name, uid):+ return f"arn:aws:wafv2:{REGION}:{ACCOUNT_ID}:regional/webacl/{name}/{uid}"+++def _ipset_arn(name, uid):+ return f"arn:aws:wafv2:{REGION}:{ACCOUNT_ID}:regional/ipset/{name}/{uid}"+++def _rg_arn(name, uid):+ return f"arn:aws:wafv2:{REGION}:{ACCOUNT_ID}:regional/rulegroup/{name}/{uid}"+++async def handle_request(method, path, headers, body, query_params):+ target = headers.get("x-amz-target", "")+ action = target.split(".")[-1] if "." in target else ""++ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ return error_response_json("SerializationException", "Invalid JSON", 400)++ handlers = {+ "CreateWebACL": _create_web_acl,+ "GetWebACL": _get_web_acl,+ "UpdateWebACL": _update_web_acl,+ "DeleteWebACL": _delete_web_acl,+ "ListWebACLs": _list_web_acls,+ "AssociateWebACL": _associate_web_acl,+ "DisassociateWebACL": _disassociate_web_acl,+ "GetWebACLForResource": _get_web_acl_for_resource,+ "ListResourcesForWebACL": _list_resources_for_web_acl,+ "CreateIPSet": _create_ip_set,+ "GetIPSet": _get_ip_set,+ "UpdateIPSet": _update_ip_set,+ "DeleteIPSet": _delete_ip_set,+ "ListIPSets": _list_ip_sets,+ "CreateRuleGroup": _create_rule_group,+ "GetRuleGroup": _get_rule_group,+ "UpdateRuleGroup": _update_rule_group,+ "DeleteRuleGroup": _delete_rule_group,+ "ListRuleGroups": _list_rule_groups,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListTagsForResource": _list_tags_for_resource,+ "CheckCapacity": _check_capacity,+ "DescribeManagedRuleGroup": _describe_managed_rule_group,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown WAF action: {action}", 400)+ return handler(data)+++# ---------------------------------------------------------------------------+# WebACL+# ---------------------------------------------------------------------------++def _create_web_acl(data):+ name = data.get("Name", "")+ if not name:+ return _waf_err("WAFInvalidParameterException", "Name is required")+ uid = new_uuid()+ lock_token = new_uuid()+ arn = _acl_arn(name, uid)+ _web_acls[uid] = {+ "ARN": arn, "Id": uid, "Name": name,+ "Description": data.get("Description", ""),+ "DefaultAction": data.get("DefaultAction", {"Allow": {}}),+ "Rules": data.get("Rules", []),+ "VisibilityConfig": data.get("VisibilityConfig", {}),+ "Capacity": 0,+ "LockToken": lock_token,+ "Scope": data.get("Scope", "REGIONAL"),+ }+ _waf_tags[arn] = data.get("Tags", [])+ logger.info("CreateWebACL: %s (%s)", name, uid)+ return json_response({"Summary": {+ "ARN": arn, "Id": uid, "Name": name,+ "Description": data.get("Description", ""),+ "LockToken": lock_token,+ }})+++def _get_web_acl(data):+ uid = data.get("Id", "")+ acl = _web_acls.get(uid)+ if not acl:+ return _waf_err("WAFNonexistentItemException", f"WebACL {uid} not found")+ acl_body = {k: v for k, v in acl.items() if k != "LockToken"}+ return json_response({"WebACL": acl_body, "LockToken": acl["LockToken"]})+++def _update_web_acl(data):+ uid = data.get("Id", "")+ acl = _web_acls.get(uid)+ if not acl:+ return _waf_err("WAFNonexistentItemException", f"WebACL {uid} not found")+ acl["Rules"] = data.get("Rules", acl["Rules"])+ acl["DefaultAction"] = data.get("DefaultAction", acl["DefaultAction"])+ acl["VisibilityConfig"] = data.get("VisibilityConfig", acl["VisibilityConfig"])+ acl["LockToken"] = new_uuid()+ return json_response({"NextLockToken": acl["LockToken"]})+++def _delete_web_acl(data):+ uid = data.get("Id", "")+ if uid not in _web_acls:+ return _waf_err("WAFNonexistentItemException", f"WebACL {uid} not found")+ arn = _web_acls[uid]["ARN"]+ del _web_acls[uid]+ _waf_tags.pop(arn, None)+ return json_response({})+++def _list_web_acls(data):+ scope = data.get("Scope", "REGIONAL")+ acls = [+ {"ARN": a["ARN"], "Id": a["Id"], "Name": a["Name"],+ "Description": a.get("Description", ""), "LockToken": a["LockToken"]}+ for a in _web_acls.values() if a.get("Scope", "REGIONAL") == scope+ ]+ return json_response({"WebACLs": acls, "NextMarker": None})+++# ---------------------------------------------------------------------------+# Association+# ---------------------------------------------------------------------------++def _associate_web_acl(data):+ web_acl_arn = data.get("WebACLArn", "")+ resource_arn = data.get("ResourceArn", "")+ _associations[resource_arn] = web_acl_arn+ return json_response({})+++def _disassociate_web_acl(data):+ resource_arn = data.get("ResourceArn", "")+ _associations.pop(resource_arn, None)+ return json_response({})+++def _get_web_acl_for_resource(data):+ resource_arn = data.get("ResourceArn", "")+ web_acl_arn = _associations.get(resource_arn)+ if not web_acl_arn:+ return _waf_err("WAFNonexistentItemException", f"No WebACL associated with {resource_arn}")+ for acl in _web_acls.values():+ if acl["ARN"] == web_acl_arn:+ acl_body = {k: v for k, v in acl.items() if k != "LockToken"}+ return json_response({"WebACL": acl_body})+ return _waf_err("WAFNonexistentItemException", f"WebACL {web_acl_arn} not found")+++def _list_resources_for_web_acl(data):+ web_acl_arn = data.get("WebACLArn", "")+ arns = [r for r, a in _associations.items() if a == web_acl_arn]+ return json_response({"ResourceArns": arns})+++# ---------------------------------------------------------------------------+# IPSet+# ---------------------------------------------------------------------------++def _create_ip_set(data):+ name = data.get("Name", "")+ uid = new_uuid()+ lock_token = new_uuid()+ arn = _ipset_arn(name, uid)+ _ip_sets[uid] = {+ "ARN": arn, "Id": uid, "Name": name,+ "Description": data.get("Description", ""),+ "IPAddressVersion": data.get("IPAddressVersion", "IPV4"),+ "Addresses": data.get("Addresses", []),+ "LockToken": lock_token,+ "Scope": data.get("Scope", "REGIONAL"),+ }+ _waf_tags[arn] = data.get("Tags", [])+ return json_response({"Summary": {"ARN": arn, "Id": uid, "Name": name, "LockToken": lock_token}})+++def _get_ip_set(data):+ uid = data.get("Id", "")+ ipset = _ip_sets.get(uid)+ if not ipset:+ return _waf_err("WAFNonexistentItemException", f"IPSet {uid} not found")+ ipset_body = {k: v for k, v in ipset.items() if k != "LockToken"}+ return json_response({"IPSet": ipset_body, "LockToken": ipset["LockToken"]})+++def _update_ip_set(data):+ uid = data.get("Id", "")+ ipset = _ip_sets.get(uid)+ if not ipset:+ return _waf_err("WAFNonexistentItemException", f"IPSet {uid} not found")+ ipset["Addresses"] = data.get("Addresses", ipset["Addresses"])+ ipset["LockToken"] = new_uuid()+ return json_response({"NextLockToken": ipset["LockToken"]})+++def _delete_ip_set(data):+ uid = data.get("Id", "")+ if uid not in _ip_sets:+ return _waf_err("WAFNonexistentItemException", f"IPSet {uid} not found")+ arn = _ip_sets[uid]["ARN"]+ del _ip_sets[uid]+ _waf_tags.pop(arn, None)+ return json_response({})+++def _list_ip_sets(data):+ scope = data.get("Scope", "REGIONAL")+ sets = [+ {"ARN": s["ARN"], "Id": s["Id"], "Name": s["Name"],+ "Description": s.get("Description", ""), "LockToken": s["LockToken"]}+ for s in _ip_sets.values() if s.get("Scope", "REGIONAL") == scope+ ]+ return json_response({"IPSets": sets, "NextMarker": None})+++# ---------------------------------------------------------------------------+# RuleGroup+# ---------------------------------------------------------------------------++def _create_rule_group(data):+ name = data.get("Name", "")+ uid = new_uuid()+ lock_token = new_uuid()+ arn = _rg_arn(name, uid)+ _rule_groups[uid] = {+ "ARN": arn, "Id": uid, "Name": name,+ "Description": data.get("Description", ""),+ "Capacity": data.get("Capacity", 0),+ "Rules": data.get("Rules", []),+ "VisibilityConfig": data.get("VisibilityConfig", {}),+ "LockToken": lock_token,+ "Scope": data.get("Scope", "REGIONAL"),+ }+ _waf_tags[arn] = data.get("Tags", [])+ return json_response({"Summary": {"ARN": arn, "Id": uid, "Name": name, "LockToken": lock_token}})+++def _get_rule_group(data):+ uid = data.get("Id", "")+ rg = _rule_groups.get(uid)+ if not rg:+ return _waf_err("WAFNonexistentItemException", f"RuleGroup {uid} not found")+ rg_body = {k: v for k, v in rg.items() if k != "LockToken"}+ return json_response({"RuleGroup": rg_body, "LockToken": rg["LockToken"]})+++def _update_rule_group(data):+ uid = data.get("Id", "")+ rg = _rule_groups.get(uid)+ if not rg:+ return _waf_err("WAFNonexistentItemException", f"RuleGroup {uid} not found")+ rg["Rules"] = data.get("Rules", rg["Rules"])+ rg["VisibilityConfig"] = data.get("VisibilityConfig", rg["VisibilityConfig"])+ rg["LockToken"] = new_uuid()+ return json_response({"NextLockToken": rg["LockToken"]})+++def _delete_rule_group(data):+ uid = data.get("Id", "")+ if uid not in _rule_groups:+ return _waf_err("WAFNonexistentItemException", f"RuleGroup {uid} not found")+ arn = _rule_groups[uid]["ARN"]+ del _rule_groups[uid]+ _waf_tags.pop(arn, None)+ return json_response({})+++def _list_rule_groups(data):+ scope = data.get("Scope", "REGIONAL")+ groups = [+ {"ARN": r["ARN"], "Id": r["Id"], "Name": r["Name"],+ "Description": r.get("Description", ""), "LockToken": r["LockToken"]}+ for r in _rule_groups.values() if r.get("Scope", "REGIONAL") == scope+ ]+ return json_response({"RuleGroups": groups, "NextMarker": None})+++# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------++def _tag_resource(data):+ arn = data.get("ResourceARN", "")+ existing = {t["Key"]: t for t in _waf_tags.get(arn, [])}+ for tag in data.get("Tags", []):+ existing[tag["Key"]] = tag+ _waf_tags[arn] = list(existing.values())+ return json_response({})+++def _untag_resource(data):+ arn = data.get("ResourceARN", "")+ remove_keys = set(data.get("TagKeys", []))+ _waf_tags[arn] = [t for t in _waf_tags.get(arn, []) if t["Key"] not in remove_keys]+ return json_response({})+++def _list_tags_for_resource(data):+ arn = data.get("ResourceARN", "")+ return json_response({"TagInfoForResource": {"ResourceARN": arn, "TagList": _waf_tags.get(arn, [])}})+++# ---------------------------------------------------------------------------+# Misc+# ---------------------------------------------------------------------------++def _check_capacity(data):+ return json_response({"Capacity": 1})+++def _describe_managed_rule_group(data):+ return json_response({+ "VersionName": "Version_1.0",+ "SnsTopicArn": "",+ "Capacity": 700,+ "Rules": [],+ "LabelNamespace": f"awswaf:managed:{data.get('VendorName', 'AWS')}:{data.get('Name', '')}:",+ "AvailableLabels": [],+ "ConsumedLabels": [],+ })+++def reset():+ _web_acls.clear()+ _ip_sets.clear()+ _rule_groups.clear()+ _associations.clear()+ _waf_tags.clear()diff --git a/pyproject.toml b/pyproject.tomlindex 31d7d33f..7f766d56 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.1.10"+version = "1.1.11"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/conftest.py b/tests/conftest.pyindex 424dd30e..88a0315d 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -175,6 +175,18 @@ def ebs():def efs():return make_client("efs")[email protected](scope="session")+def acm_client():+ return make_client("acm")+[email protected](scope="session")+def wafv2():+ return make_client("wafv2")+[email protected](scope="session")+def sesv2():+ return make_client("sesv2")+@pytest.fixture(scope="session")def sfn_sync():"""SFN client for StartSyncExecution — forces same endpoint (boto3 normally prefixes sync-)."""diff --git a/tests/test_services.py b/tests/test_services.pyindex aeca3dc4..da696e2f 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -14865,3 +14865,331 @@ def test_ec2_egress_only_igw_not_found(ec2):EgressOnlyInternetGatewayId="eigw-nonexistent")assert "NotFound" in exc.value.response["Error"]["Code"]+++# ===========================================================================+# ACM — Certificate Manager+# ===========================================================================++def test_acm_request_certificate(acm_client):+ resp = acm_client.request_certificate(+ DomainName="example.com",+ ValidationMethod="DNS",+ SubjectAlternativeNames=["www.example.com"],+ )+ arn = resp["CertificateArn"]+ assert arn.startswith("arn:aws:acm:us-east-1:000000000000:certificate/")+++def test_acm_describe_certificate(acm_client):+ arn = acm_client.request_certificate(DomainName="describe.example.com")["CertificateArn"]+ resp = acm_client.describe_certificate(CertificateArn=arn)+ cert = resp["Certificate"]+ assert cert["DomainName"] == "describe.example.com"+ assert cert["Status"] == "ISSUED"+ assert len(cert["DomainValidationOptions"]) >= 1+ assert "ResourceRecord" in cert["DomainValidationOptions"][0]+++def test_acm_list_certificates(acm_client):+ arn = acm_client.request_certificate(DomainName="list.example.com")["CertificateArn"]+ resp = acm_client.list_certificates()+ arns = [c["CertificateArn"] for c in resp["CertificateSummaryList"]]+ assert arn in arns+++def test_acm_tags(acm_client):+ arn = acm_client.request_certificate(DomainName="tags.example.com")["CertificateArn"]+ acm_client.add_tags_to_certificate(+ CertificateArn=arn,+ Tags=[{"Key": "env", "Value": "test"}, {"Key": "team", "Value": "platform"}],+ )+ tags = acm_client.list_tags_for_certificate(CertificateArn=arn)["Tags"]+ assert any(t["Key"] == "env" and t["Value"] == "test" for t in tags)+ acm_client.remove_tags_from_certificate(+ CertificateArn=arn,+ Tags=[{"Key": "team", "Value": "platform"}],+ )+ tags2 = acm_client.list_tags_for_certificate(CertificateArn=arn)["Tags"]+ assert not any(t["Key"] == "team" for t in tags2)+++def test_acm_get_certificate(acm_client):+ arn = acm_client.request_certificate(DomainName="pem.example.com")["CertificateArn"]+ resp = acm_client.get_certificate(CertificateArn=arn)+ assert "BEGIN CERTIFICATE" in resp["Certificate"]+++def test_acm_import_certificate(acm_client):+ fake_cert = b"-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----"+ fake_key = b"-----BEGIN RSA PRIVATE KEY-----\nfake\n-----END RSA PRIVATE KEY-----"+ resp = acm_client.import_certificate(Certificate=fake_cert, PrivateKey=fake_key)+ arn = resp["CertificateArn"]+ desc = acm_client.describe_certificate(CertificateArn=arn)+ assert desc["Certificate"]["Type"] == "IMPORTED"+++def test_acm_delete_certificate(acm_client):+ arn = acm_client.request_certificate(DomainName="delete.example.com")["CertificateArn"]+ acm_client.delete_certificate(CertificateArn=arn)+ resp = acm_client.list_certificates()+ arns = [c["CertificateArn"] for c in resp["CertificateSummaryList"]]+ assert arn not in arns+++# ===========================================================================+# SES v2+# ===========================================================================++def test_ses_v2_send_email(sesv2):+ resp = sesv2.send_email(+ FromEmailAddress="[email protected]",+ Destination={"ToAddresses": ["[email protected]"]},+ Content={+ "Simple": {+ "Subject": {"Data": "Test Subject"},+ "Body": {"Text": {"Data": "Hello world"}},+ }+ },+ )+ assert resp["MessageId"].startswith("ministack-")+++def test_ses_v2_email_identity_crud(sesv2):+ sesv2.create_email_identity(EmailIdentity="test-domain.com")+ resp = sesv2.get_email_identity(EmailIdentity="test-domain.com")+ assert resp["VerifiedForSendingStatus"] is True+ lst = sesv2.list_email_identities()+ names = [e["IdentityName"] for e in lst["EmailIdentities"]]+ assert "test-domain.com" in names+ sesv2.delete_email_identity(EmailIdentity="test-domain.com")+ lst2 = sesv2.list_email_identities()+ names2 = [e["IdentityName"] for e in lst2["EmailIdentities"]]+ assert "test-domain.com" not in names2+++def test_ses_v2_configuration_set_crud(sesv2):+ sesv2.create_configuration_set(ConfigurationSetName="my-cfg-set")+ resp = sesv2.get_configuration_set(ConfigurationSetName="my-cfg-set")+ assert resp["ConfigurationSetName"] == "my-cfg-set"+ lst = sesv2.list_configuration_sets()+ assert "my-cfg-set" in lst["ConfigurationSets"]+ sesv2.delete_configuration_set(ConfigurationSetName="my-cfg-set")+ lst2 = sesv2.list_configuration_sets()+ assert "my-cfg-set" not in lst2["ConfigurationSets"]+++def test_ses_v2_get_account(sesv2):+ resp = sesv2.get_account()+ assert resp["SendingEnabled"] is True+ assert resp["ProductionAccessEnabled"] is True+++# ===========================================================================+# Lambda Layers+# ===========================================================================++def test_lambda_layer_publish(lam):+ import base64, zipfile, io+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as z:+ z.writestr("layer.py", "# layer")+ zip_bytes = buf.getvalue()+ resp = lam.publish_layer_version(+ LayerName="my-test-layer",+ Description="Test layer",+ Content={"ZipFile": zip_bytes},+ CompatibleRuntimes=["python3.12"],+ )+ assert resp["Version"] == 1+ assert "my-test-layer" in resp["LayerVersionArn"]+++def test_lambda_layer_get_version(lam):+ resp = lam.get_layer_version(LayerName="my-test-layer", VersionNumber=1)+ assert resp["Version"] == 1+ assert resp["Description"] == "Test layer"+++def test_lambda_layer_list_versions(lam):+ resp = lam.list_layer_versions(LayerName="my-test-layer")+ assert len(resp["LayerVersions"]) >= 1+ assert resp["LayerVersions"][0]["Version"] == 1+++def test_lambda_layer_list_layers(lam):+ resp = lam.list_layers()+ names = [l["LayerName"] for l in resp["Layers"]]+ assert "my-test-layer" in names+++def test_lambda_layer_delete_version(lam):+ import base64, zipfile, io+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as z:+ z.writestr("tmp.py", "")+ lam.publish_layer_version(LayerName="delete-layer-test", Content={"ZipFile": buf.getvalue()})+ lam.delete_layer_version(LayerName="delete-layer-test", VersionNumber=1)+ resp = lam.list_layer_versions(LayerName="delete-layer-test")+ assert len(resp["LayerVersions"]) == 0+++def test_lambda_function_with_layer(lam):+ import base64, zipfile, io+ # Publish layer+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as z:+ z.writestr("layer.py", "")+ layer_resp = lam.publish_layer_version(LayerName="fn-layer", Content={"ZipFile": buf.getvalue()})+ layer_arn = layer_resp["LayerVersionArn"]+ # Create function using the layer+ fn_zip = io.BytesIO()+ with zipfile.ZipFile(fn_zip, "w") as z:+ z.writestr("index.py", "def handler(e, c): return {}")+ lam.create_function(+ FunctionName="fn-with-layer",+ Runtime="python3.12",+ Role="arn:aws:iam::000000000000:role/test",+ Handler="index.handler",+ Code={"ZipFile": fn_zip.getvalue()},+ Layers=[layer_arn],+ )+ fn = lam.get_function(FunctionName="fn-with-layer")+ assert layer_arn in fn["Configuration"]["Layers"][0]["Arn"]+++# ===========================================================================+# WAF v2+# ===========================================================================++def test_waf_web_acl_crud(wafv2):+ resp = wafv2.create_web_acl(+ Name="test-acl",+ Scope="REGIONAL",+ DefaultAction={"Allow": {}},+ VisibilityConfig={"SampledRequestsEnabled": True, "CloudWatchMetricsEnabled": False, "MetricName": "test"},+ )+ uid = resp["Summary"]["Id"]+ assert resp["Summary"]["Name"] == "test-acl"++ get_resp = wafv2.get_web_acl(Name="test-acl", Scope="REGIONAL", Id=uid)+ assert get_resp["WebACL"]["Name"] == "test-acl"++ lst = wafv2.list_web_acls(Scope="REGIONAL")+ ids = [a["Id"] for a in lst["WebACLs"]]+ assert uid in ids++ wafv2.delete_web_acl(Name="test-acl", Scope="REGIONAL", Id=uid, LockToken=resp["Summary"]["LockToken"])+ lst2 = wafv2.list_web_acls(Scope="REGIONAL")+ ids2 = [a["Id"] for a in lst2["WebACLs"]]+ assert uid not in ids2+++def test_waf_update_web_acl(wafv2):+ resp = wafv2.create_web_acl(+ Name="update-acl",+ Scope="REGIONAL",+ DefaultAction={"Block": {}},+ VisibilityConfig={"SampledRequestsEnabled": False, "CloudWatchMetricsEnabled": False, "MetricName": "m"},+ )+ uid = resp["Summary"]["Id"]+ lock = resp["Summary"]["LockToken"]+ upd = wafv2.update_web_acl(+ Name="update-acl", Scope="REGIONAL", Id=uid, LockToken=lock,+ DefaultAction={"Allow": {}},+ VisibilityConfig={"SampledRequestsEnabled": False, "CloudWatchMetricsEnabled": False, "MetricName": "m"},+ )+ assert "NextLockToken" in upd+++def test_waf_associate_disassociate(wafv2):+ resp = wafv2.create_web_acl(+ Name="assoc-acl", Scope="REGIONAL",+ DefaultAction={"Allow": {}},+ VisibilityConfig={"SampledRequestsEnabled": False, "CloudWatchMetricsEnabled": False, "MetricName": "m"},+ )+ acl_arn = resp["Summary"]["ARN"]+ resource_arn = "arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/test/abc"+ wafv2.associate_web_acl(WebACLArn=acl_arn, ResourceArn=resource_arn)+ get_resp = wafv2.get_web_acl_for_resource(ResourceArn=resource_arn)+ assert get_resp["WebACL"]["ARN"] == acl_arn+ wafv2.disassociate_web_acl(ResourceArn=resource_arn)+ try:+ wafv2.get_web_acl_for_resource(ResourceArn=resource_arn)+ assert False, "expected WAFNonexistentItemException"+ except wafv2.exceptions.WAFNonexistentItemException:+ pass+++def test_waf_ip_set_crud(wafv2):+ resp = wafv2.create_ip_set(+ Name="test-ipset", Scope="REGIONAL",+ IPAddressVersion="IPV4",+ Addresses=["1.2.3.4/32"],+ )+ uid = resp["Summary"]["Id"]+ lock = resp["Summary"]["LockToken"]++ get_resp = wafv2.get_ip_set(Name="test-ipset", Scope="REGIONAL", Id=uid)+ assert "1.2.3.4/32" in get_resp["IPSet"]["Addresses"]++ upd = wafv2.update_ip_set(+ Name="test-ipset", Scope="REGIONAL", Id=uid, LockToken=lock,+ Addresses=["5.6.7.8/32"],+ )+ assert "NextLockToken" in upd++ lst = wafv2.list_ip_sets(Scope="REGIONAL")+ ids = [s["Id"] for s in lst["IPSets"]]+ assert uid in ids++ wafv2.delete_ip_set(Name="test-ipset", Scope="REGIONAL", Id=uid, LockToken=upd["NextLockToken"])+ lst2 = wafv2.list_ip_sets(Scope="REGIONAL")+ ids2 = [s["Id"] for s in lst2["IPSets"]]+ assert uid not in ids2+++def test_waf_rule_group_crud(wafv2):+ resp = wafv2.create_rule_group(+ Name="test-rg", Scope="REGIONAL", Capacity=100,+ VisibilityConfig={"SampledRequestsEnabled": False, "CloudWatchMetricsEnabled": False, "MetricName": "m"},+ )+ uid = resp["Summary"]["Id"]+ lock = resp["Summary"]["LockToken"]++ get_resp = wafv2.get_rule_group(Name="test-rg", Scope="REGIONAL", Id=uid)+ assert get_resp["RuleGroup"]["Name"] == "test-rg"+ assert "LockToken" not in get_resp["RuleGroup"]++ upd = wafv2.update_rule_group(+ Name="test-rg", Scope="REGIONAL", Id=uid, LockToken=lock,+ VisibilityConfig={"SampledRequestsEnabled": False, "CloudWatchMetricsEnabled": False, "MetricName": "m2"},+ )+ assert "NextLockToken" in upd++ lst = wafv2.list_rule_groups(Scope="REGIONAL")+ ids = [r["Id"] for r in lst["RuleGroups"]]+ assert uid in ids++ wafv2.delete_rule_group(Name="test-rg", Scope="REGIONAL", Id=uid, LockToken=upd["NextLockToken"])+ lst2 = wafv2.list_rule_groups(Scope="REGIONAL")+ ids2 = [r["Id"] for r in lst2["RuleGroups"]]+ assert uid not in ids2+++def test_waf_tags(wafv2):+ resp = wafv2.create_web_acl(+ Name="tag-acl", Scope="REGIONAL",+ DefaultAction={"Allow": {}},+ VisibilityConfig={"SampledRequestsEnabled": False, "CloudWatchMetricsEnabled": False, "MetricName": "m"},+ Tags=[{"Key": "env", "Value": "test"}],+ )+ arn = resp["Summary"]["ARN"]+ tags_resp = wafv2.list_tags_for_resource(ResourceARN=arn)+ assert any(t["Key"] == "env" for t in tags_resp["TagInfoForResource"]["TagList"])+ wafv2.tag_resource(ResourceARN=arn, Tags=[{"Key": "team", "Value": "security"}])+ tags_resp2 = wafv2.list_tags_for_resource(ResourceARN=arn)+ assert any(t["Key"] == "team" for t in tags_resp2["TagInfoForResource"]["TagList"])+ wafv2.untag_resource(ResourceARN=arn, TagKeys=["env"])+ tags_resp3 = wafv2.list_tags_for_resource(ResourceARN=arn)+ assert not any(t["Key"] == "env" for t in tags_resp3["TagInfoForResource"]["TagList"])