Skip to content

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

feat: AppSync service, Cognito JWKS/OIDC, 9 CFN resource types, EC2 DescribeVpcAttribute, 955 tests (v1.1.32) (#108)

Nahuel Nucerafb5ba7860063
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 06e8dc4c..07a24a85 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,19 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.32] — 2026-04-04
+
+### Added
+- **AppSync service** — CreateGraphQLApi, GetGraphQLApi, ListGraphQLApis, UpdateGraphQLApi, DeleteGraphQLApi, CreateApiKey, ListApiKeys, DeleteApiKey, CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, DeleteResolver, CreateType, ListTypes, GetType, TagResource, UntagResource, ListTagsForResource; REST/JSON API under `/v1/apis`; in-memory state with persistence
+- **Cognito JWKS/OIDC endpoints** — `/.well-known/jwks.json` returns real RSA public key; `/.well-known/openid-configuration` returns OpenID Connect discovery document; enables real JWT validation in Amplify/CDK auth flows
+- **9 new CloudFormation resource types** — `AWS::ApiGateway::RestApi`, `AWS::ApiGateway::Resource`, `AWS::ApiGateway::Method`, `AWS::ApiGateway::Deployment`, `AWS::ApiGateway::Stage`, `AWS::Lambda::EventSourceMapping`, `AWS::Lambda::Alias`, `AWS::SQS::QueuePolicy`, `AWS::SNS::TopicPolicy`; unblocks Serverless Framework and CDK deployments
+- **EC2 `DescribeVpcAttribute`** — returns EnableDnsSupport, EnableDnsHostnames, EnableNetworkAddressUsageMetrics; fixes Terraform VPC module failing after ModifyVpcAttribute. Reported by @betorvs
+
+### Tests
+- 955 tests total, all passing
+
+---
+
## [1.1.31] — 2026-04-04
### Fixed
@@ -17,6 +30,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **README: stale test count and service count** — updated to 948 tests, 37 services
- **README: CloudFront in Terraform endpoints, architecture diagram, comparison table**
+### Tests
+- 948 tests total, all passing
+
---
## [1.1.30] — 2026-04-03
diff --git a/README.md b/README.md
index ed2fd8fb..8bb5b923 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,7 @@
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.
-- **37 AWS services** emulated on a single port (4566)
+- **38 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** — ~200MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM
@@ -272,12 +272,13 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if
| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; result pagination; column type metadata |
| **Firehose** | CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination, TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream, StartDeliveryStreamEncryption, StopDeliveryStreamEncryption | S3 destinations write records to the local S3 emulator; all other destination types buffer in-memory; concurrency-safe `UpdateDestination` via `VersionId` |
| **Route53** | CreateHostedZone, GetHostedZone, DeleteHostedZone, ListHostedZones, ListHostedZonesByName, UpdateHostedZoneComment, ChangeResourceRecordSets (CREATE/UPSERT/DELETE), ListResourceRecordSets, GetChange, CreateHealthCheck, GetHealthCheck, DeleteHealthCheck, ListHealthChecks, UpdateHealthCheck, ChangeTagsForResource, ListTagsForResource | REST/XML protocol; SOA + NS records auto-created; CallerReference idempotency; alias records, weighted/failover/latency routing; marker-based pagination |
-| **EC2** | RunInstances, DescribeInstances, DescribeInstanceAttribute, DescribeInstanceTypes, TerminateInstances, StopInstances, StartInstances, RebootInstances, DescribeImages, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, CreateTags, DeleteTags, DescribeTags, CreateNatGateway, DescribeNatGateways, DeleteNatGateway, CreateNetworkAcl, DescribeNetworkAcls, DeleteNetworkAcl, CreateNetworkAclEntry, DeleteNetworkAclEntry, ReplaceNetworkAclEntry, ReplaceNetworkAclAssociation, CreateFlowLogs, DescribeFlowLogs, DeleteFlowLogs, CreateVpcPeeringConnection, AcceptVpcPeeringConnection, DescribeVpcPeeringConnections, DeleteVpcPeeringConnection, CreateDhcpOptions, AssociateDhcpOptions, DescribeDhcpOptions, DeleteDhcpOptions, CreateEgressOnlyInternetGateway, DescribeEgressOnlyInternetGateways, DeleteEgressOnlyInternetGateway, DescribeInstanceCreditSpecifications, DescribeInstanceMaintenanceOptions, DescribeInstanceAutoRecoveryAttribute, ModifyInstanceMaintenanceOptions, DescribeInstanceTopology, DescribeSpotInstanceRequests, DescribeCapacityReservations | In-memory state only — no real VMs; default VPC, subnet, security group, internet gateway, and route table always present; rules stored but not enforced (matches LocalStack); Terraform v6 compatible |
+| **EC2** | RunInstances, DescribeInstances, DescribeInstanceAttribute, DescribeInstanceTypes, DescribeVpcAttribute, TerminateInstances, StopInstances, StartInstances, RebootInstances, DescribeImages, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, CreateTags, DeleteTags, DescribeTags, CreateNatGateway, DescribeNatGateways, DeleteNatGateway, CreateNetworkAcl, DescribeNetworkAcls, DeleteNetworkAcl, CreateNetworkAclEntry, DeleteNetworkAclEntry, ReplaceNetworkAclEntry, ReplaceNetworkAclAssociation, CreateFlowLogs, DescribeFlowLogs, DeleteFlowLogs, CreateVpcPeeringConnection, AcceptVpcPeeringConnection, DescribeVpcPeeringConnections, DeleteVpcPeeringConnection, CreateDhcpOptions, AssociateDhcpOptions, DescribeDhcpOptions, DeleteDhcpOptions, CreateEgressOnlyInternetGateway, DescribeEgressOnlyInternetGateways, DeleteEgressOnlyInternetGateway, DescribeInstanceCreditSpecifications, DescribeInstanceMaintenanceOptions, DescribeInstanceAutoRecoveryAttribute, ModifyInstanceMaintenanceOptions, DescribeInstanceTopology, DescribeSpotInstanceRequests, DescribeCapacityReservations | In-memory state only — no real VMs; default VPC, subnet, security group, internet gateway, and route table always present; rules stored but not enforced (matches LocalStack); Terraform v6 compatible |
| **EBS** | CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus, AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications, EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CopySnapshot, ModifySnapshotAttribute, DescribeSnapshotAttribute | Part of EC2 Query/XML service; attach/detach updates volume state; snapshots stored as completed immediately; Pro-only on LocalStack — free here |
| **EFS** | CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget, DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups, CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint, TagResource, UntagResource, ListTagsForResource, PutLifecycleConfiguration, DescribeLifecycleConfiguration, PutBackupPolicy, DescribeBackupPolicy, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist; Pro-only on LocalStack — free here |
| **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here |
| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP SOFTWARE_TOKEN_MFA challenge flow; MFA config and per-user enrollment stored in-memory |
| **ECR** | CreateRepository, DescribeRepositories, DeleteRepository, ListImages, DescribeImages, PutImage, BatchGetImage, BatchDeleteImage, GetAuthorizationToken, GetRepositoryPolicy, SetRepositoryPolicy, DeleteRepositoryPolicy, PutLifecyclePolicy, GetLifecyclePolicy, DeleteLifecyclePolicy, ListTagsForResource, TagResource, UntagResource, PutImageTagMutability, PutImageScanningConfiguration, DescribeRegistry, GetDownloadUrlForLayer, BatchCheckLayerAvailability, InitiateLayerUpload, UploadLayerPart, CompleteLayerUpload | In-memory image registry; Docker V2 manifest support; authorization token generation; lifecycle policies; tag mutability; Pro-only on LocalStack — free here |
+| **AppSync** | CreateGraphQLApi, GetGraphQLApi, ListGraphQLApis, UpdateGraphQLApi, DeleteGraphQLApi, CreateApiKey, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, DeleteResolver, CreateType, ListTypes, GetType, TagResource, UntagResource, ListTagsForResource | REST/JSON API under `/v1/apis`; GraphQL API management for Amplify/CDK |
---
@@ -518,7 +519,7 @@ Layers that ship npm packages work too — MiniStack resolves the `nodejs/node_m
│ │ Cognito EC2 EMR EBS EFS │ │
│ │ ALB/ELBv2 ACM WAF v2 │ │
│ │ CloudFormation KMS ECR │ │
- │ │ CloudFront │ │
+ │ │ CloudFront AppSync │ │
│ └────────────────────────────────────┘ │
│ │
│ In-Memory Storage + Optional Docker │
@@ -541,20 +542,20 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (948 tests across all 37 services)
+# Run the full test suite (955 tests across all 38 services)
pytest tests/ -v
```
Expected output:
```
-collected 948 items
+collected 955 items
tests/test_services.py::test_s3_create_bucket PASSED
...
tests/test_services.py::test_app_asgi_callable PASSED
-948 passed in ~100s
+955 passed in ~100s
```
---
@@ -578,6 +579,7 @@ provider "aws" {
endpoints {
acm = "http://localhost:4566"
apigateway = "http://localhost:4566"
+ appsync = "http://localhost:4566"
athena = "http://localhost:4566"
cloudformation = "http://localhost:4566"
cloudwatch = "http://localhost:4566"
@@ -678,6 +680,7 @@ See [`Testcontainers/java-testcontainers`](Testcontainers/java-testcontainers),
| **KMS** | ✅ | Paid | ✅ Free |
| **ECR** | ✅ | ✅ | ✅ |
| **CloudFront** | ✅ | Paid | ✅ |
+| **AppSync** | ✅ | NO | ✅ |
| Cost | **Free** | Was free, now paid | $35+/mo |
| Docker image size | ~200MB | ~1GB | ~1GB |
| Memory at idle | ~30MB | ~500MB | ~500MB |
diff --git a/ministack/app.py b/ministack/app.py
index a105558a..1453a147 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -44,6 +44,7 @@ from ministack.services import (
alb,
apigateway,
apigateway_v1,
+ appsync,
athena,
cloudformation,
cloudwatch,
@@ -122,6 +123,7 @@ SERVICE_HANDLERS = {
"elasticfilesystem": efs.handle_request,
"kms": kms.handle_request,
"cloudfront": cloudfront.handle_request,
+ "appsync": appsync.handle_request,
}
SERVICE_NAME_ALIASES = {
@@ -175,7 +177,8 @@ BANNER = r"""
Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,
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, CloudFormation, KMS, ECR, CloudFront
+ Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2, CloudFormation, KMS, ECR, CloudFront,
+ AppSync
"""
@@ -251,6 +254,24 @@ async def app(scope, receive, send):
await _send_response(send, status, resp_headers, resp_body)
return
+ # Cognito JWKS / OpenID Configuration well-known endpoints
+ # Path: /{poolId}/.well-known/jwks.json or /{poolId}/.well-known/openid-configuration
+ if "/.well-known/" in path and method == "GET":
+ if path.endswith("/.well-known/jwks.json"):
+ _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)
+ 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)
+ await _send_response(send, status, resp_headers, resp_body)
+ return
+
# Admin endpoints — no wildcard CORS headers (return early, before CORS block)
if path == "/_ministack/reset" and method == "POST":
_reset_all_state()
@@ -568,6 +589,7 @@ async def _handle_lifespan(scope, receive, send):
"rds": rds.get_state,
"ecs": ecs.get_state,
"elasticache": elasticache.get_state,
+ "appsync": appsync.get_state,
})
await send({"type": "lifespan.shutdown.complete"})
return
@@ -647,6 +669,7 @@ def _reset_all_state():
(kms, kms.reset),
(cloudfront, cloudfront.reset),
(ecr, ecr.reset),
+ (appsync, appsync.reset),
]:
try:
fn()
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 3e7f4d8f..56839579 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -162,6 +162,11 @@ SERVICE_PATTERNS = {
"host_patterns": [r"cloudfront\."],
"credential_scope": "cloudfront",
},
+ "appsync": {
+ "host_patterns": [r"appsync\."],
+ "path_prefixes": ["/v1/apis", "/v1/tags"],
+ "credential_scope": "appsync",
+ },
}
@@ -213,6 +218,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"cloudformation": "cloudformation",
"kms": "kms",
"cloudfront": "cloudfront",
+ "appsync": "appsync",
}
if svc_name in scope_map:
return scope_map[svc_name]
@@ -412,6 +418,8 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
# 4. Check URL path patterns
path_lower = path.lower()
+ if path_lower.startswith("/v1/apis") or path_lower.startswith("/v1/tags/arn:aws:appsync"):
+ return "appsync"
if path_lower.startswith("/2020-05-31/"):
return "cloudfront"
if path_lower.startswith("/2013-04-01/"):
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
new file mode 100644
index 00000000..b1ce2247
--- /dev/null
+++ b/ministack/services/appsync.py
@@ -0,0 +1,610 @@
+"""
+AWS AppSync Service Emulator.
+
+GraphQL API management service — REST/JSON protocol via /v1/apis/* paths.
+
+Supports:
+ GraphQL APIs: CreateGraphQLApi, GetGraphQLApi, ListGraphQLApis,
+ UpdateGraphQLApi, DeleteGraphQLApi
+ API Keys: CreateApiKey, ListApiKeys, DeleteApiKey
+ Data Sources: CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource
+ Resolvers: CreateResolver, GetResolver, ListResolvers, DeleteResolver
+ Types: CreateType, ListTypes, GetType
+ Tags: TagResource, UntagResource, ListTagsForResource
+
+Wire protocol:
+ REST/JSON — path-based routing under /v1/apis.
+ Credential scope: appsync
+"""
+
+import copy
+import json
+import logging
+import os
+import re
+import time
+
+from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.responses import error_response_json, json_response, new_uuid
+
+logger = logging.getLogger("appsync")
+
+ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+
+# ---------------------------------------------------------------------------
+# In-memory state
+# ---------------------------------------------------------------------------
+
+_apis: dict = {} # apiId -> api record
+_api_keys: dict = {} # apiId -> {keyId -> key record}
+_data_sources: dict = {} # apiId -> {name -> data source record}
+_resolvers: dict = {} # apiId -> {typeName -> {fieldName -> resolver record}}
+_types: dict = {} # apiId -> {typeName -> type record}
+_tags: dict = {} # resource_arn -> {key: value}
+
+# ---------------------------------------------------------------------------
+# Persistence
+# ---------------------------------------------------------------------------
+
+def _load_persisted():
+ if not PERSIST_STATE:
+ return
+ data = load_state("appsync")
+ if data:
+ restore_state(data)
+ logger.info("Loaded persisted state for appsync")
+
+_load_persisted()
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _now():
+ return int(time.time())
+
+
+def _api_arn(api_id):
+ return f"arn:aws:appsync:{REGION}:{ACCOUNT_ID}:apis/{api_id}"
+
+
+def _json(status, body):
+ return json_response(body, status)
+
+
+# ---------------------------------------------------------------------------
+# GraphQL APIs
+# ---------------------------------------------------------------------------
+
+def _create_graphql_api(body):
+ api_id = new_uuid()[:8]
+ name = body.get("name", "")
+ auth_type = body.get("authenticationType", "API_KEY")
+ additional_auth = body.get("additionalAuthenticationProviders", [])
+ log_config = body.get("logConfig")
+ user_pool_config = body.get("userPoolConfig")
+ openid_config = body.get("openIDConnectConfig")
+ xray = body.get("xrayEnabled", False)
+ tags = body.get("tags", {})
+ lambda_auth = body.get("lambdaAuthorizerConfig")
+
+ arn = _api_arn(api_id)
+ now = _now()
+
+ record = {
+ "apiId": api_id,
+ "name": name,
+ "authenticationType": auth_type,
+ "arn": arn,
+ "uris": {
+ "GRAPHQL": f"https://{api_id}.appsync-api.{REGION}.amazonaws.com/graphql",
+ "REALTIME": f"wss://{api_id}.appsync-realtime-api.{REGION}.amazonaws.com/graphql",
+ },
+ "additionalAuthenticationProviders": additional_auth,
+ "xrayEnabled": xray,
+ "wafWebAclArn": body.get("wafWebAclArn"),
+ "createdAt": now,
+ "lastUpdatedAt": now,
+ }
+ if log_config:
+ record["logConfig"] = log_config
+ if user_pool_config:
+ record["userPoolConfig"] = user_pool_config
+ if openid_config:
+ record["openIDConnectConfig"] = openid_config
+ if lambda_auth:
+ record["lambdaAuthorizerConfig"] = lambda_auth
+
+ _apis[api_id] = record
+ _api_keys[api_id] = {}
+ _data_sources[api_id] = {}
+ _resolvers[api_id] = {}
+ _types[api_id] = {}
+
+ if tags:
+ _tags[arn] = tags
+
+ return _json(200, {"graphqlApi": record})
+
+
+def _get_graphql_api(api_id):
+ api = _apis.get(api_id)
+ if not api:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ return _json(200, {"graphqlApi": api})
+
+
+def _list_graphql_apis(query_params):
+ apis = list(_apis.values())
+ return _json(200, {"graphqlApis": apis})
+
+
+def _update_graphql_api(api_id, body):
+ api = _apis.get(api_id)
+ if not api:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ if "name" in body:
+ api["name"] = body["name"]
+ if "authenticationType" in body:
+ api["authenticationType"] = body["authenticationType"]
+ if "additionalAuthenticationProviders" in body:
+ api["additionalAuthenticationProviders"] = body["additionalAuthenticationProviders"]
+ if "logConfig" in body:
+ api["logConfig"] = body["logConfig"]
+ if "userPoolConfig" in body:
+ api["userPoolConfig"] = body["userPoolConfig"]
+ if "openIDConnectConfig" in body:
+ api["openIDConnectConfig"] = body["openIDConnectConfig"]
+ if "xrayEnabled" in body:
+ api["xrayEnabled"] = body["xrayEnabled"]
+ if "lambdaAuthorizerConfig" in body:
+ api["lambdaAuthorizerConfig"] = body["lambdaAuthorizerConfig"]
+
+ api["lastUpdatedAt"] = _now()
+ return _json(200, {"graphqlApi": api})
+
+
+def _delete_graphql_api(api_id):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ arn = _apis[api_id]["arn"]
+ del _apis[api_id]
+ _api_keys.pop(api_id, None)
+ _data_sources.pop(api_id, None)
+ _resolvers.pop(api_id, None)
+ _types.pop(api_id, None)
+ _tags.pop(arn, None)
+
+ return _json(200, {})
+
+
+# ---------------------------------------------------------------------------
+# API Keys
+# ---------------------------------------------------------------------------
+
+def _create_api_key(api_id, body):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ key_id = "da2-" + new_uuid()[:26]
+ now = _now()
+ expires = body.get("expires", now + 604800) # default 7 days
+ description = body.get("description", "")
+
+ record = {
+ "id": key_id,
+ "description": description,
+ "expires": expires,
+ "createdAt": now,
+ "lastUpdatedAt": now,
+ "deletes": expires + 5184000, # 60 days after expiry
+ }
+
+ _api_keys.setdefault(api_id, {})[key_id] = record
+ return _json(200, {"apiKey": record})
+
+
+def _list_api_keys(api_id):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ keys = list(_api_keys.get(api_id, {}).values())
+ return _json(200, {"apiKeys": keys})
+
+
+def _delete_api_key(api_id, key_id):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ keys = _api_keys.get(api_id, {})
+ if key_id not in keys:
+ return error_response_json("NotFoundException", f"API key {key_id} not found", 404)
+
+ del keys[key_id]
+ return _json(200, {})
+
+
+# ---------------------------------------------------------------------------
+# Data Sources
+# ---------------------------------------------------------------------------
+
+def _create_data_source(api_id, body):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ name = body.get("name", "")
+ ds_type = body.get("type", "NONE")
+ description = body.get("description", "")
+ service_role_arn = body.get("serviceRoleArn", "")
+
+ arn = f"{_apis[api_id]['arn']}/datasources/{name}"
+
+ record = {
+ "dataSourceArn": arn,
+ "name": name,
+ "type": ds_type,
+ "description": description,
+ "serviceRoleArn": service_role_arn,
+ "createdAt": _now(),
+ "lastUpdatedAt": _now(),
+ }
+
+ if ds_type == "AMAZON_DYNAMODB":
+ record["dynamodbConfig"] = body.get("dynamodbConfig", {})
+ elif ds_type == "AWS_LAMBDA":
+ record["lambdaConfig"] = body.get("lambdaConfig", {})
+ elif ds_type == "AMAZON_ELASTICSEARCH" or ds_type == "AMAZON_OPENSEARCH_SERVICE":
+ record["elasticsearchConfig"] = body.get("elasticsearchConfig", {})
+ elif ds_type == "HTTP":
+ record["httpConfig"] = body.get("httpConfig", {})
+ elif ds_type == "RELATIONAL_DATABASE":
+ record["relationalDatabaseConfig"] = body.get("relationalDatabaseConfig", {})
+
+ _data_sources.setdefault(api_id, {})[name] = record
+ return _json(200, {"dataSource": record})
+
+
+def _get_data_source(api_id, name):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ ds = _data_sources.get(api_id, {}).get(name)
+ if not ds:
+ return error_response_json("NotFoundException", f"Data source {name} not found", 404)
+
+ return _json(200, {"dataSource": ds})
+
+
+def _list_data_sources(api_id):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ sources = list(_data_sources.get(api_id, {}).values())
+ return _json(200, {"dataSources": sources})
+
+
+def _delete_data_source(api_id, name):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ sources = _data_sources.get(api_id, {})
+ if name not in sources:
+ return error_response_json("NotFoundException", f"Data source {name} not found", 404)
+
+ del sources[name]
+ return _json(200, {})
+
+
+# ---------------------------------------------------------------------------
+# Resolvers
+# ---------------------------------------------------------------------------
+
+def _create_resolver(api_id, type_name, body):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ field_name = body.get("fieldName", "")
+ data_source_name = body.get("dataSourceName")
+ request_template = body.get("requestMappingTemplate", "")
+ response_template = body.get("responseMappingTemplate", "")
+ kind = body.get("kind", "UNIT")
+ pipeline_config = body.get("pipelineConfig")
+ caching_config = body.get("cachingConfig")
+ runtime = body.get("runtime")
+ code = body.get("code")
+
+ arn = f"{_apis[api_id]['arn']}/types/{type_name}/resolvers/{field_name}"
+
+ record = {
+ "typeName": type_name,
+ "fieldName": field_name,
+ "dataSourceName": data_source_name,
+ "resolverArn": arn,
+ "requestMappingTemplate": request_template,
+ "responseMappingTemplate": response_template,
+ "kind": kind,
+ "createdAt": _now(),
+ "lastUpdatedAt": _now(),
+ }
+ if pipeline_config:
+ record["pipelineConfig"] = pipeline_config
+ if caching_config:
+ record["cachingConfig"] = caching_config
+ if runtime:
+ record["runtime"] = runtime
+ if code:
+ record["code"] = code
+
+ _resolvers.setdefault(api_id, {}).setdefault(type_name, {})[field_name] = record
+ return _json(200, {"resolver": record})
+
+
+def _get_resolver(api_id, type_name, field_name):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ resolver = _resolvers.get(api_id, {}).get(type_name, {}).get(field_name)
+ if not resolver:
+ return error_response_json("NotFoundException",
+ f"Resolver {type_name}.{field_name} not found", 404)
+
+ return _json(200, {"resolver": resolver})
+
+
+def _list_resolvers(api_id, type_name):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ resolvers = list(_resolvers.get(api_id, {}).get(type_name, {}).values())
+ return _json(200, {"resolvers": resolvers})
+
+
+def _delete_resolver(api_id, type_name, field_name):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ type_resolvers = _resolvers.get(api_id, {}).get(type_name, {})
+ if field_name not in type_resolvers:
+ return error_response_json("NotFoundException",
+ f"Resolver {type_name}.{field_name} not found", 404)
+
+ del type_resolvers[field_name]
+ return _json(200, {})
+
+
+# ---------------------------------------------------------------------------
+# Types
+# ---------------------------------------------------------------------------
+
+def _create_type(api_id, body):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ definition = body.get("definition", "")
+ fmt = body.get("format", "SDL")
+
+ # Extract type name from SDL definition (e.g. "type Query { ... }" -> "Query")
+ name_match = re.search(r"(?:type|input|enum|interface|union|scalar)\s+(\w+)", definition)
+ type_name = name_match.group(1) if name_match else "Unknown"
+
+ arn = f"{_apis[api_id]['arn']}/types/{type_name}"
+
+ record = {
+ "name": type_name,
+ "description": body.get("description", ""),
+ "arn": arn,
+ "definition": definition,
+ "format": fmt,
+ "createdAt": _now(),
+ "lastUpdatedAt": _now(),
+ }
+
+ _types.setdefault(api_id, {})[type_name] = record
+ return _json(200, {"type": record})
+
+
+def _get_type(api_id, type_name, query_params):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ fmt = "SDL"
+ if query_params.get("format"):
+ fmt_val = query_params["format"]
+ fmt = fmt_val[0] if isinstance(fmt_val, list) else fmt_val
+
+ t = _types.get(api_id, {}).get(type_name)
+ if not t:
+ return error_response_json("NotFoundException", f"Type {type_name} not found", 404)
+
+ return _json(200, {"type": t})
+
+
+def _list_types(api_id, query_params):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ types = list(_types.get(api_id, {}).values())
+ return _json(200, {"types": types})
+
+
+# ---------------------------------------------------------------------------
+# Tags
+# ---------------------------------------------------------------------------
+
+def _tag_resource(body):
+ arn = body.get("resourceArn", "")
+ tags = body.get("tags", {})
+ _tags.setdefault(arn, {}).update(tags)
+ return _json(200, {})
+
+
+def _untag_resource(arn, query_params):
+ tag_keys = query_params.get("tagKeys", [])
+ if isinstance(tag_keys, str):
+ tag_keys = [tag_keys]
+ existing = _tags.get(arn, {})
+ for k in tag_keys:
+ existing.pop(k, None)
+ return _json(200, {})
+
+
+def _list_tags_for_resource(arn):
+ tags = _tags.get(arn, {})
+ return _json(200, {"tags": tags})
+
+
+# ---------------------------------------------------------------------------
+# Request router
+# ---------------------------------------------------------------------------
+
+# Path patterns for routing
+_PATH_RE = re.compile(r"^/v1/apis(?:/([^/]+))?(?:/([^/]+))?(?:/([^/]+))?(?:/([^/]+))?(?:/([^/]+))?")
+# /v1/apis -> groups: (None, None, None, None, None)
+# /v1/apis/{apiId} -> groups: (apiId, None, None, None, None)
+# /v1/apis/{apiId}/apikeys -> groups: (apiId, "apikeys", None, None, None)
+# /v1/apis/{apiId}/apikeys/{id} -> groups: (apiId, "apikeys", id, None, None)
+# /v1/apis/{apiId}/datasources -> groups: (apiId, "datasources", None, None, None)
+# /v1/apis/{apiId}/datasources/{n} -> groups: (apiId, "datasources", name, None, None)
+# /v1/apis/{apiId}/types -> groups: (apiId, "types", None, None, None)
+# /v1/apis/{apiId}/types/{t}/resolvers -> (apiId, "types", t, "resolvers", None)
+# /v1/apis/{apiId}/types/{t}/resolvers/{field} -> (apiId, "types", t, "resolvers", field)
+
+
+async def handle_request(method, path, headers, body, query_params):
+ """Main entry point — route AppSync REST requests."""
+
+ # Tags endpoint: /v1/tags/{resourceArn}
+ if path.startswith("/v1/tags/"):
+ from urllib.parse import unquote
+ arn = unquote(path[len("/v1/tags/"):])
+ if method == "POST":
+ data = json.loads(body) if body else {}
+ data["resourceArn"] = arn
+ return _tag_resource(data)
+ elif method == "DELETE":
+ return _untag_resource(arn, query_params)
+ else: # GET
+ return _list_tags_for_resource(arn)
+
+ m = _PATH_RE.match(path)
+ if not m:
+ return error_response_json("NotFoundException", f"Unknown path: {path}", 404)
+
+ api_id, sub1, sub2, sub3, sub4 = m.groups()
+
+ data = {}
+ if body:
+ try:
+ data = json.loads(body)
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ data = {}
+
+ # POST /v1/apis — CreateGraphQLApi
+ if api_id is None and sub1 is None:
+ if method == "POST":
+ return _create_graphql_api(data)
+ elif method == "GET":
+ return _list_graphql_apis(query_params)
+
+ # /v1/apis/{apiId}
+ if api_id and sub1 is None:
+ if method == "GET":
+ return _get_graphql_api(api_id)
+ elif method == "POST":
+ return _update_graphql_api(api_id, data)
+ elif method == "DELETE":
+ return _delete_graphql_api(api_id)
+
+ # /v1/apis/{apiId}/apikeys
+ if sub1 == "apikeys":
+ if sub2 is None:
+ if method == "POST":
+ return _create_api_key(api_id, data)
+ elif method == "GET":
+ return _list_api_keys(api_id)
+ else:
+ # /v1/apis/{apiId}/apikeys/{keyId}
+ if method == "DELETE":
+ return _delete_api_key(api_id, sub2)
+
+ # /v1/apis/{apiId}/datasources
+ if sub1 == "datasources":
+ if sub2 is None:
+ if method == "POST":
+ return _create_data_source(api_id, data)
+ elif method == "GET":
+ return _list_data_sources(api_id)
+ else:
+ # /v1/apis/{apiId}/datasources/{name}
+ if method == "GET":
+ return _get_data_source(api_id, sub2)
+ elif method == "DELETE":
+ return _delete_data_source(api_id, sub2)
+
+ # /v1/apis/{apiId}/types
+ if sub1 == "types":
+ if sub2 is None:
+ if method == "POST":
+ return _create_type(api_id, data)
+ elif method == "GET":
+ return _list_types(api_id, query_params)
+ elif sub3 == "resolvers":
+ # /v1/apis/{apiId}/types/{typeName}/resolvers
+ type_name = sub2
+ if sub4 is None:
+ if method == "POST":
+ return _create_resolver(api_id, type_name, data)
+ elif method == "GET":
+ return _list_resolvers(api_id, type_name)
+ else:
+ # /v1/apis/{apiId}/types/{typeName}/resolvers/{fieldName}
+ field_name = sub4
+ if method == "GET":
+ return _get_resolver(api_id, type_name, field_name)
+ elif method == "DELETE":
+ return _delete_resolver(api_id, type_name, field_name)
+ else:
+ # /v1/apis/{apiId}/types/{typeName} — GetType
+ if sub3 is None and method == "GET":
+ return _get_type(api_id, sub2, query_params)
+
+ return error_response_json("BadRequestException", f"Unsupported route: {method} {path}")
+
+
+# ---------------------------------------------------------------------------
+# State management
+# ---------------------------------------------------------------------------
+
+def reset():
+ """Clear all in-memory state."""
+ _apis.clear()
+ _api_keys.clear()
+ _data_sources.clear()
+ _resolvers.clear()
+ _types.clear()
+ _tags.clear()
+
+
+def get_state():
+ """Return a deep copy of all state for persistence."""
+ return copy.deepcopy({
+ "apis": _apis,
+ "api_keys": _api_keys,
+ "data_sources": _data_sources,
+ "resolvers": _resolvers,
+ "types": _types,
+ "tags": _tags,
+ })
+
+
+def restore_state(data):
+ """Restore state from persisted data."""
+ _apis.update(data.get("apis", {}))
+ _api_keys.update(data.get("api_keys", {}))
+ _data_sources.update(data.get("data_sources", {}))
+ _resolvers.update(data.get("resolvers", {}))
+ _types.update(data.get("types", {}))
+ _tags.update(data.get("tags", {}))
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 25d80a7c..9d03abe7 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -23,6 +23,7 @@ import ministack.services.ssm as _ssm
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.apigateway_v1 as _apigw_v1
logger = logging.getLogger("cloudformation")
@@ -714,6 +715,263 @@ def _cfn_wait_condition_handle_create(logical_id, props, stack_name):
return pid, {"Ref": url}
+# --- API Gateway REST API ---
+
+def _apigw_rest_api_create(logical_id, props, stack_name):
+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)
+ data = {
+ "name": name,
+ "description": props.get("Description", ""),
+ "endpointConfiguration": props.get("EndpointConfiguration", {"types": ["REGIONAL"]}),
+ "binaryMediaTypes": props.get("BinaryMediaTypes", []),
+ "minimumCompressionSize": props.get("MinimumCompressionSize"),
+ "policy": props.get("Policy"),
+ "tags": {t["Key"]: t["Value"] for t in props.get("Tags", [])},
+ }
+ status, headers, body = _apigw_v1._create_rest_api(data)
+ api = json.loads(body) if isinstance(body, bytes) else json.loads(body)
+ api_id = api.get("id", "")
+ # Find root resource id
+ root_id = ""
+ for rid, res in _apigw_v1._resources.get(api_id, {}).items():
+ if res.get("path") == "/":
+ root_id = rid
+ break
+ return api_id, {
+ "RootResourceId": root_id,
+ "Arn": f"arn:aws:apigateway:{REGION}::/restapis/{api_id}",
+ }
+
+
+def _apigw_rest_api_delete(physical_id, props):
+ _apigw_v1._delete_rest_api(physical_id)
+
+
+# --- API Gateway Resource ---
+
+def _apigw_resource_create(logical_id, props, stack_name):
+ api_id = props.get("RestApiId", "")
+ parent_id = props.get("ParentId", "")
+ path_part = props.get("PathPart", "")
+ data = {"pathPart": path_part}
+ status, headers, body = _apigw_v1._create_resource(api_id, parent_id, data)
+ resource = json.loads(body) if isinstance(body, bytes) else json.loads(body)
+ resource_id = resource.get("id", "")
+ return resource_id, {"ResourceId": resource_id}
+
+
+def _apigw_resource_delete(physical_id, props):
+ api_id = props.get("RestApiId", "")
+ _apigw_v1._delete_resource(api_id, physical_id)
+
+
+# --- API Gateway Method ---
+
+def _apigw_method_create(logical_id, props, stack_name):
+ api_id = props.get("RestApiId", "")
+ resource_id = props.get("ResourceId", "")
+ http_method = props.get("HttpMethod", "ANY")
+ data = {
+ "authorizationType": props.get("AuthorizationType", "NONE"),
+ "authorizerId": props.get("AuthorizerId"),
+ "apiKeyRequired": props.get("ApiKeyRequired", False),
+ "operationName": props.get("OperationName", ""),
+ "requestParameters": props.get("RequestParameters", {}),
+ "requestModels": props.get("RequestModels", {}),
+ }
+ _apigw_v1._put_method(api_id, resource_id, http_method, data)
+
+ # Also set Integration if provided
+ integration = props.get("Integration")
+ if integration:
+ int_data = {
+ "type": integration.get("Type", "AWS_PROXY"),
+ "httpMethod": integration.get("IntegrationHttpMethod", "POST"),
+ "uri": integration.get("Uri", ""),
+ "connectionType": integration.get("ConnectionType", "INTERNET"),
+ "credentials": integration.get("Credentials"),
+ "requestParameters": integration.get("RequestParameters", {}),
+ "requestTemplates": integration.get("RequestTemplates", {}),
+ "passthroughBehavior": integration.get("PassthroughBehavior", "WHEN_NO_MATCH"),
+ "timeoutInMillis": integration.get("TimeoutInMillis", 29000),
+ "cacheKeyParameters": integration.get("CacheKeyParameters", []),
+ }
+ _apigw_v1._put_integration(api_id, resource_id, http_method, int_data)
+
+ pid = f"{api_id}-{resource_id}-{http_method}"
+ return pid, {}
+
+
+def _apigw_method_delete(physical_id, props):
+ api_id = props.get("RestApiId", "")
+ resource_id = props.get("ResourceId", "")
+ http_method = props.get("HttpMethod", "ANY")
+ _apigw_v1._delete_method(api_id, resource_id, http_method)
+
+
+# --- API Gateway Deployment ---
+
+def _apigw_deployment_create(logical_id, props, stack_name):
+ api_id = props.get("RestApiId", "")
+ data = {
+ "description": props.get("Description", ""),
+ "stageName": props.get("StageName"),
+ "stageDescription": props.get("StageDescription", ""),
+ }
+ status, headers, body = _apigw_v1._create_deployment(api_id, data)
+ deployment = json.loads(body) if isinstance(body, bytes) else json.loads(body)
+ deployment_id = deployment.get("id", "")
+ return deployment_id, {"DeploymentId": deployment_id}
+
+
+def _apigw_deployment_delete(physical_id, props):
+ api_id = props.get("RestApiId", "")
+ _apigw_v1._delete_deployment(api_id, physical_id)
+
+
+# --- API Gateway Stage ---
+
+def _apigw_stage_create(logical_id, props, stack_name):
+ api_id = props.get("RestApiId", "")
+ stage_name = props.get("StageName", "")
+ data = {
+ "stageName": stage_name,
+ "deploymentId": props.get("DeploymentId", ""),
+ "description": props.get("Description", ""),
+ "variables": props.get("Variables", {}),
+ "methodSettings": props.get("MethodSettings", {}),
+ "tracingEnabled": props.get("TracingEnabled", False),
+ "tags": {t["Key"]: t["Value"] for t in props.get("Tags", [])},
+ }
+ _apigw_v1._create_stage(api_id, data)
+ pid = f"{api_id}-{stage_name}"
+ return pid, {"StageName": stage_name}
+
+
+def _apigw_stage_delete(physical_id, props):
+ api_id = props.get("RestApiId", "")
+ stage_name = props.get("StageName", "")
+ _apigw_v1._delete_stage(api_id, stage_name)
+
+
+# --- Lambda EventSourceMapping ---
+
+def _lambda_esm_create(logical_id, props, stack_name):
+ func_name = props.get("FunctionName", "")
+ if func_name.startswith("arn:"):
+ func_name = func_name.rsplit(":", 1)[-1]
+ esm_id = new_uuid()
+ func = _lambda_svc._functions.get(func_name)
+ func_arn = func["config"]["FunctionArn"] if func else f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{func_name}"
+
+ esm = {
+ "UUID": esm_id,
+ "EventSourceArn": props.get("EventSourceArn", ""),
+ "FunctionArn": func_arn,
+ "FunctionName": func_name,
+ "State": "Enabled",
+ "StateTransitionReason": "USER_INITIATED",
+ "BatchSize": int(props.get("BatchSize", 10)),
+ "MaximumBatchingWindowInSeconds": int(props.get("MaximumBatchingWindowInSeconds", 0)),
+ "LastModified": time.time(),
+ "LastProcessingResult": "No records processed",
+ "StartingPosition": props.get("StartingPosition", "LATEST"),
+ "Enabled": props.get("Enabled", True),
+ "FunctionResponseTypes": props.get("FunctionResponseTypes", []),
+ }
+ _lambda_svc._esms[esm_id] = esm
+ return esm_id, {"UUID": esm_id}
+
+
+def _lambda_esm_delete(physical_id, props):
+ _lambda_svc._esms.pop(physical_id, None)
+
+
+# --- Lambda Alias ---
+
+def _lambda_alias_create(logical_id, props, stack_name):
+ func_name = props.get("FunctionName", "")
+ if func_name.startswith("arn:"):
+ func_name = func_name.rsplit(":", 1)[-1]
+ alias_name = props.get("Name", "")
+ func_version = props.get("FunctionVersion", "$LATEST")
+
+ func = _lambda_svc._functions.get(func_name)
+ if func:
+ alias = {
+ "AliasArn": f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{func_name}:{alias_name}",
+ "Name": alias_name,
+ "FunctionVersion": func_version,
+ "Description": props.get("Description", ""),
+ "RevisionId": new_uuid(),
+ }
+ rc = props.get("RoutingConfig")
+ if rc:
+ alias["RoutingConfig"] = rc
+ func["aliases"][alias_name] = alias
+ return alias["AliasArn"], {"AliasArn": alias["AliasArn"]}
+
+ alias_arn = f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{func_name}:{alias_name}"
+ return alias_arn, {"AliasArn": alias_arn}
+
+
+def _lambda_alias_delete(physical_id, props):
+ func_name = props.get("FunctionName", "")
+ if func_name.startswith("arn:"):
+ func_name = func_name.rsplit(":", 1)[-1]
+ alias_name = props.get("Name", "")
+ func = _lambda_svc._functions.get(func_name)
+ if func:
+ func["aliases"].pop(alias_name, None)
+
+
+# --- SQS QueuePolicy ---
+
+def _sqs_queue_policy_create(logical_id, props, stack_name):
+ policy_doc = props.get("PolicyDocument", {})
+ if isinstance(policy_doc, dict):
+ policy_doc = json.dumps(policy_doc)
+ queues = props.get("Queues", [])
+ for queue_url in queues:
+ queue = _sqs._queues.get(queue_url)
+ if queue:
+ queue["attributes"]["Policy"] = policy_doc
+ pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ return pid, {}
+
+
+def _sqs_queue_policy_delete(physical_id, props):
+ queues = props.get("Queues", [])
+ for queue_url in queues:
+ queue = _sqs._queues.get(queue_url)
+ if queue:
+ queue["attributes"].pop("Policy", None)
+
+
+# --- SNS TopicPolicy ---
+
+def _sns_topic_policy_create(logical_id, props, stack_name):
+ policy_doc = props.get("PolicyDocument", {})
+ if isinstance(policy_doc, dict):
+ policy_doc = json.dumps(policy_doc)
+ topics = props.get("Topics", [])
+ for topic_arn in topics:
+ topic = _sns._topics.get(topic_arn)
+ if topic:
+ topic["attributes"]["Policy"] = policy_doc
+ pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ return pid, {}
+
+
+def _sns_topic_policy_delete(physical_id, props):
+ topics = props.get("Topics", [])
+ for topic_arn in topics:
+ topic = _sns._topics.get(topic_arn)
+ if topic:
+ # Restore default policy
+ topic["attributes"].pop("Policy", None)
+
+
# ===========================================================================
# Resource Handler Registry
# ===========================================================================
@@ -736,4 +994,13 @@ _RESOURCE_HANDLERS = {
"AWS::Lambda::Version": {"create": _lambda_version_create},
"AWS::CloudFormation::WaitCondition": {"create": _cfn_wait_condition_create},
"AWS::CloudFormation::WaitConditionHandle": {"create": _cfn_wait_condition_handle_create},
+ "AWS::ApiGateway::RestApi": {"create": _apigw_rest_api_create, "delete": _apigw_rest_api_delete},
+ "AWS::ApiGateway::Resource": {"create": _apigw_resource_create, "delete": _apigw_resource_delete},
+ "AWS::ApiGateway::Method": {"create": _apigw_method_create, "delete": _apigw_method_delete},
+ "AWS::ApiGateway::Deployment": {"create": _apigw_deployment_create, "delete": _apigw_deployment_delete},
+ "AWS::ApiGateway::Stage": {"create": _apigw_stage_create, "delete": _apigw_stage_delete},
+ "AWS::Lambda::EventSourceMapping": {"create": _lambda_esm_create, "delete": _lambda_esm_delete},
+ "AWS::Lambda::Alias": {"create": _lambda_alias_create, "delete": _lambda_alias_delete},
+ "AWS::SQS::QueuePolicy": {"create": _sqs_queue_policy_create, "delete": _sqs_queue_policy_delete},
+ "AWS::SNS::TopicPolicy": {"create": _sns_topic_policy_create, "delete": _sns_topic_policy_delete},
}
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 9f625c58..4f1dc9c3 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -59,6 +59,72 @@ from ministack.core.responses import error_response_json, json_response, new_uui
logger = logging.getLogger("cognito")
+# ---------------------------------------------------------------------------
+# RSA key pair for JWKS / token signing
+# ---------------------------------------------------------------------------
+
+_RSA_PRIVATE_KEY = None
+_JWKS_KEY: dict = {}
+
+try:
+ from cryptography.hazmat.primitives.asymmetric import rsa
+ from cryptography.hazmat.primitives import serialization
+
+ _rsa_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ _RSA_PRIVATE_KEY = _rsa_key
+
+ _pub = _rsa_key.public_key()
+ _pub_numbers = _pub.public_numbers()
+
+ def _int_to_base64url(n: int, length: int) -> str:
+ data = n.to_bytes(length, byteorder="big")
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
+
+ _JWKS_KEY = {
+ "kty": "RSA",
+ "alg": "RS256",
+ "use": "sig",
+ "kid": "ministack-key-1",
+ "n": _int_to_base64url(_pub_numbers.n, 256),
+ "e": _int_to_base64url(_pub_numbers.e, 3),
+ }
+except ImportError:
+ # Fallback: static dummy key when cryptography is not installed
+ _JWKS_KEY = {
+ "kty": "RSA",
+ "alg": "RS256",
+ "use": "sig",
+ "kid": "ministack-key-1",
+ "n": (
+ "wJUEhGbAmcKEHp7EaNBYYEmign_bbWUBnfQGTCZ0h4ViqHC_KQQ7A"
+ "3E9X3OJ1P1E5VWZqvMfVN3l_0ljPBiA0XG4D4GBJzFJBmXq48Sk-"
+ "G38q5LHxzH-ajLz7TrEMqSF3XTkmJ_7y3p3BdML2oFGm4F0DUUEU"
+ "P3xmILPH2uo9g-5xRjYMh8i7V0xXyTAQS5Tw"
+ ),
+ "e": "AQAB",
+ }
+
+
+def well_known_jwks(pool_id: str):
+ """Return JWKS JSON for /{poolId}/.well-known/jwks.json."""
+ return 200, {"Content-Type": "application/json"}, json.dumps({"keys": [_JWKS_KEY]}).encode()
+
+
+def well_known_openid_configuration(pool_id: str, region: str | None = None):
+ """Return OpenID Connect discovery document."""
+ r = region or REGION
+ issuer = f"https://cognito-idp.{r}.amazonaws.com/{pool_id}"
+ doc = {
+ "issuer": issuer,
+ "jwks_uri": f"{issuer}/.well-known/jwks.json",
+ "authorization_endpoint": f"{issuer}/oauth2/authorize",
+ "token_endpoint": f"{issuer}/oauth2/token",
+ "response_types_supported": ["code", "token"],
+ "subject_types_supported": ["public"],
+ "id_token_signing_alg_values_supported": ["RS256"],
+ }
+ return 200, {"Content-Type": "application/json"}, json.dumps(doc).encode()
+
ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index d7d4c151..2e092c24 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -722,6 +722,26 @@ def _modify_vpc_attribute(p):
return _xml(200, "ModifyVpcAttributeResponse", "<return>true</return>")
+def _describe_vpc_attribute(p):
+ vpc_id = _p(p, "VpcId")
+ attribute = _p(p, "Attribute")
+ if vpc_id not in _vpcs:
+ return _error("InvalidVpcID.NotFound", f"The vpc ID '{vpc_id}' does not exist", 400)
+ vpc = _vpcs[vpc_id]
+ if attribute == "enableDnsSupport":
+ val = vpc.get("EnableDnsSupport", True)
+ return _xml(200, "DescribeVpcAttributeResponse",
+ f"<vpcId>{vpc_id}</vpcId><enableDnsSupport><value>{'true' if val else 'false'}</value></enableDnsSupport>")
+ elif attribute == "enableDnsHostnames":
+ val = vpc.get("EnableDnsHostnames", False)
+ return _xml(200, "DescribeVpcAttributeResponse",
+ f"<vpcId>{vpc_id}</vpcId><enableDnsHostnames><value>{'true' if val else 'false'}</value></enableDnsHostnames>")
+ elif attribute == "enableNetworkAddressUsageMetrics":
+ return _xml(200, "DescribeVpcAttributeResponse",
+ f"<vpcId>{vpc_id}</vpcId><enableNetworkAddressUsageMetrics><value>false</value></enableNetworkAddressUsageMetrics>")
+ return _xml(200, "DescribeVpcAttributeResponse", f"<vpcId>{vpc_id}</vpcId>")
+
+
def _modify_subnet_attribute(p):
subnet_id = _p(p, "SubnetId")
if subnet_id not in _subnets:
@@ -2537,6 +2557,7 @@ _ACTION_MAP = {
"DeleteTags": _delete_tags,
"DescribeTags": _describe_tags,
"ModifyVpcAttribute": _modify_vpc_attribute,
+ "DescribeVpcAttribute": _describe_vpc_attribute,
"ModifySubnetAttribute": _modify_subnet_attribute,
"CreateRouteTable": _create_route_table,
"DeleteRouteTable": _delete_route_table,
diff --git a/pyproject.toml b/pyproject.toml
index 9a2e9df5..407f5d0f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.31"
+version = "1.1.32"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_services.py b/tests/test_services.py
index 216294ec..77bfdc42 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -18098,3 +18098,109 @@ def test_lambda_provisioned_concurrency_crud(lam):
lam.get_provisioned_concurrency_config(FunctionName="pc-fn", Qualifier=ver)
lam.delete_function(FunctionName="pc-fn")
+
+
+# ========== AppSync ==========
+
+
+def test_appsync_create_and_list_api():
+ """Create a GraphQL API and list it."""
+ from conftest import make_client
+ appsync = make_client("appsync")
+ resp = appsync.create_graphql_api(name="test-api", authenticationType="API_KEY")
+ api = resp["graphqlApi"]
+ assert api["name"] == "test-api"
+ assert api["apiId"]
+ assert api["authenticationType"] == "API_KEY"
+
+ apis = appsync.list_graphql_apis()["graphqlApis"]
+ assert any(a["apiId"] == api["apiId"] for a in apis)
+
+
+def test_appsync_get_and_delete_api():
+ from conftest import make_client
+ appsync = make_client("appsync")
+ resp = appsync.create_graphql_api(name="del-api", authenticationType="API_KEY")
+ api_id = resp["graphqlApi"]["apiId"]
+ got = appsync.get_graphql_api(apiId=api_id)
+ assert got["graphqlApi"]["name"] == "del-api"
+ appsync.delete_graphql_api(apiId=api_id)
+ from botocore.exceptions import ClientError
+ with pytest.raises(ClientError):
+ appsync.get_graphql_api(apiId=api_id)
+
+
+def test_appsync_api_key_crud():
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="key-api", authenticationType="API_KEY")["graphqlApi"]
+ key = appsync.create_api_key(apiId=api["apiId"])["apiKey"]
+ assert key["id"]
+ keys = appsync.list_api_keys(apiId=api["apiId"])["apiKeys"]
+ assert len(keys) >= 1
+ appsync.delete_api_key(apiId=api["apiId"], id=key["id"])
+
+
+def test_appsync_data_source_crud():
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="ds-api", authenticationType="API_KEY")["graphqlApi"]
+ ds = appsync.create_data_source(
+ apiId=api["apiId"], name="myds", type="AMAZON_DYNAMODB",
+ dynamodbConfig={"tableName": "test-table", "awsRegion": "us-east-1"},
+ )["dataSource"]
+ assert ds["name"] == "myds"
+ got = appsync.get_data_source(apiId=api["apiId"], name="myds")
+ assert got["dataSource"]["name"] == "myds"
+ appsync.delete_data_source(apiId=api["apiId"], name="myds")
+
+
+# ========== Cognito JWKS ==========
+
+
+def test_cognito_jwks_endpoint():
+ """/.well-known/jwks.json returns valid JWK set."""
+ import urllib.request, json as _json
+ from conftest import make_client
+ cognito = make_client("cognito-idp")
+ pool = cognito.create_user_pool(PoolName="jwks-pool")["UserPool"]
+ pool_id = pool["Id"]
+ req = urllib.request.Request(
+ f"http://localhost:4566/{pool_id}/.well-known/jwks.json",
+ )
+ with urllib.request.urlopen(req) as r:
+ data = _json.loads(r.read())
+ assert "keys" in data
+ assert len(data["keys"]) >= 1
+ assert data["keys"][0]["kty"] == "RSA"
+ assert data["keys"][0]["alg"] == "RS256"
+
+
+def test_cognito_openid_configuration():
+ """/.well-known/openid-configuration returns valid discovery document."""
+ import urllib.request, json as _json
+ from conftest import make_client
+ cognito = make_client("cognito-idp")
+ pool = cognito.create_user_pool(PoolName="oidc-pool")["UserPool"]
+ pool_id = pool["Id"]
+ req = urllib.request.Request(
+ f"http://localhost:4566/{pool_id}/.well-known/openid-configuration",
+ )
+ with urllib.request.urlopen(req) as r:
+ data = _json.loads(r.read())
+ assert "issuer" in data
+ assert pool_id in data["issuer"]
+ assert "jwks_uri" in data
+ assert "token_endpoint" in data
+
+
+# ========== EC2 DescribeVpcAttribute ==========
+
+
+def test_ec2_describe_vpc_attribute(ec2):
+ vpc = ec2.create_vpc(CidrBlock="10.99.0.0/16")
+ vpc_id = vpc["Vpc"]["VpcId"]
+ resp = ec2.describe_vpc_attribute(VpcId=vpc_id, Attribute="enableDnsSupport")
+ assert resp["EnableDnsSupport"]["Value"] in (True, False)
+ resp2 = ec2.describe_vpc_attribute(VpcId=vpc_id, Attribute="enableDnsHostnames")
+ assert resp2["EnableDnsHostnames"]["Value"] in (True, False)