Skip to content

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

feat: AppSync GraphQL data plane, EC2 Terraform VPC fixes, CFN Cognito/SecretsManager, S3 UploadPartCopy, 971 tests (v1.1.33) (#109)

Nahuel Nucerae96defdf0ec5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 07a24a85..7911bbe2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,30 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.33] — 2026-04-04
+
+### Added
+- **DynamoDB `ScanFilter` / `QueryFilter`** — legacy filter conditions (EQ, NE, NOT_NULL, NULL, CONTAINS, BEGINS_WITH) now supported alongside FilterExpression
+- **CFN `AWS::AppSync::*`** — GraphQLApi, DataSource, Resolver, GraphQLSchema, ApiKey provisioners for CDK/Amplify stacks
+- **CFN `AWS::SecretsManager::Secret`** — with `GenerateSecretString` support (PasswordLength, ExcludeCharacters, SecretStringTemplate, GenerateStringKey)
+- **S3 `UploadPartCopy`** — copy a range from an existing object as a multipart upload part; supports `x-amz-copy-source-range`
+- **SNS FIFO dedup passthrough** — `MessageGroupId` and `MessageDeduplicationId` from SNS Publish now forwarded to SQS FIFO queues via fanout
+- **AppSync GraphQL data plane** — `POST /v1/apis/{apiId}/graphql` executes queries and mutations against DynamoDB resolvers; supports create/get/list/update/delete operations, nested input objects, field selection, Lambda resolvers; enables Amplify Data runtime
+- **CFN Cognito resource types** — `AWS::Cognito::UserPool`, `AWS::Cognito::UserPoolClient`, `AWS::Cognito::IdentityPool`, `AWS::Cognito::UserPoolDomain` for Amplify/CDK auth stacks
+
+### Fixed
+- **DynamoDB persistence crash** — `defaultdict(dict)` deserialized as plain `dict` after restart, causing `KeyError` on new partition keys. Now converts back to `defaultdict` on restore
+- **DynamoDB `_pitr_settings` not persisted** — `DescribeContinuousBackups` now survives restarts
+- **Cognito JWT `kid` mismatch** — tokens now use `kid: ministack-key-1` matching the JWKS endpoint; fixes client-side JWT validation
+- **KMS RSA private keys persisted** — private keys now PEM-encoded in state; Sign/Verify work after restart (requires `cryptography` package)
+- **4 duplicate test function names** — `test_lambda_publish_version`, `test_kinesis_stream_encryption`, `test_apigw_delete_route` renamed to unique names; previously only last definition ran
+- **EC2 Terraform VPC module fixes** — `DescribeAddressesAttribute`, `DescribeSecurityGroupRules`, route table association state (`associated`), VPC `defaultNetworkAclId`/`defaultSecurityGroupId`/`mainRouteTableId` in CreateVpc/DescribeVpcs responses. Reported by @betorvs
+
+### Tests
+- 971 tests total, all passing
+
+---
+
## [1.1.32] — 2026-04-04
### Added
diff --git a/README.md b/README.md
index 8bb5b923..1414a69e 100644
--- a/README.md
+++ b/README.md
@@ -278,7 +278,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if
| **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 |
+| **AppSync** | CreateGraphQLApi, GetGraphQLApi, ListGraphQLApis, UpdateGraphQLApi, DeleteGraphQLApi, CreateApiKey, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, DeleteResolver, CreateType, ListTypes, GetType, TagResource, UntagResource, ListTagsForResource | Control plane + data plane; GraphQL queries/mutations execute against DynamoDB resolvers (create/get/list/update/delete); Lambda resolvers supported; designed for Amplify/CDK CRUD patterns — not a full GraphQL spec engine |
---
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
index b1ce2247..7478613e 100644
--- a/ministack/services/appsync.py
+++ b/ministack/services/appsync.py
@@ -489,6 +489,22 @@ async def handle_request(method, path, headers, body, query_params):
else: # GET
return _list_tags_for_resource(arn)
+ # GraphQL data plane: POST /graphql or POST /v1/apis/{apiId}/graphql
+ if path == "/graphql" and method == "POST":
+ api_key = headers.get("x-api-key", "")
+ api_id = _resolve_api_by_key(api_key)
+ if not api_id:
+ return error_response_json("UnauthorizedException", "Valid API key required", 401)
+ data = json.loads(body) if body else {}
+ return _execute_graphql(api_id, data)
+
+ if path.startswith("/v1/apis/") and path.endswith("/graphql") and method == "POST":
+ parts = path.split("/")
+ if len(parts) >= 5:
+ api_id = parts[3]
+ data = json.loads(body) if body else {}
+ return _execute_graphql(api_id, data)
+
m = _PATH_RE.match(path)
if not m:
return error_response_json("NotFoundException", f"Unknown path: {path}", 404)
@@ -608,3 +624,372 @@ def restore_state(data):
_resolvers.update(data.get("resolvers", {}))
_types.update(data.get("types", {}))
_tags.update(data.get("tags", {}))
+
+
+# ---------------------------------------------------------------------------
+# GraphQL Data Plane — parse and execute queries against DynamoDB
+# ---------------------------------------------------------------------------
+
+import re as _re
+
+# Simple GraphQL parser — handles queries/mutations that Amplify generates
+_GQL_OP_RE = _re.compile(
+ r'(?:query|mutation|subscription)\s+(\w+)?\s*(?:\(([^)]*)\))?\s*\{(.*)\}',
+ _re.DOTALL,
+)
+_GQL_FIELD_RE = _re.compile(r'(\w+)\s*(?:\(([^)]*)\))?\s*(?:\{([^}]*)\})?')
+
+
+def _resolve_api_by_key(api_key_value):
+ """Find the API ID that owns this API key."""
+ for api_id, keys in _api_keys.items():
+ for kid, key in keys.items():
+ if kid == api_key_value or key.get("id") == api_key_value:
+ return api_id
+ # Fallback: if only one API exists, use it
+ if len(_apis) == 1:
+ return next(iter(_apis))
+ return None
+
+
+def _execute_graphql(api_id, data):
+ """Execute a GraphQL query/mutation against the configured resolvers."""
+ query = data.get("query", "")
+ variables = data.get("variables", {})
+ operation_name = data.get("operationName")
+
+ if not query.strip():
+ return _json(400, {"errors": [{"message": "Query is required"}]})
+
+ if api_id not in _apis:
+ return _json(404, {"errors": [{"message": f"API {api_id} not found"}]})
+
+ # Parse the top-level operation
+ # Strip __typename fields — Amplify adds these everywhere
+ query_clean = _re.sub(r'__typename\s*', '', query)
+
+ m = _GQL_OP_RE.search(query_clean)
+ if not m:
+ # Try bare field query: { getUser(id: "1") { name } }
+ inner = query_clean.strip().strip("{}")
+ fields = _parse_fields(inner, variables)
+ else:
+ op_name, op_args, body = m.groups()
+ fields = _parse_fields(body, variables)
+
+ # Determine operation type
+ is_mutation = query_clean.strip().startswith("mutation")
+
+ results = {}
+ errors = []
+ for field_name, args, sub_fields in fields:
+ resolver = _find_resolver(api_id, "Mutation" if is_mutation else "Query", field_name)
+ if resolver:
+ try:
+ result = _resolve_field(api_id, resolver, args, sub_fields, variables)
+ results[field_name] = result
+ except Exception as e:
+ errors.append({"message": str(e), "path": [field_name]})
+ results[field_name] = None
+ else:
+ # No resolver — return mock empty result
+ results[field_name] = None
+
+ response = {"data": results}
+ if errors:
+ response["errors"] = errors
+ return _json(200, response)
+
+
+def _parse_fields(body, variables):
+ """Parse GraphQL field selections into (name, args_dict, sub_fields) tuples."""
+ fields = []
+ for m in _GQL_FIELD_RE.finditer(body.strip()):
+ name = m.group(1)
+ args_str = m.group(2) or ""
+ sub = m.group(3) or ""
+ args = _parse_args(args_str, variables)
+ sub_fields = [s.strip() for s in sub.split() if s.strip() and s.strip() != "__typename"]
+ fields.append((name, args, sub_fields))
+ return fields
+
+
+def _parse_args(args_str, variables):
+ """Parse GraphQL arguments like (id: "1") or (id: $id) into a dict."""
+ args = {}
+ if not args_str.strip():
+ return args
+ # Match key: value pairs
+ for pair in _re.finditer(r'(\w+)\s*:\s*("(?:[^"\\]|\\.)*"|\$\w+|\d+(?:\.\d+)?|true|false|null|\{[^}]*\}|\[[^\]]*\])', args_str):
+ key = pair.group(1)
+ val = pair.group(2)
+ if val.startswith("$"):
+ val = variables.get(val[1:], val)
+ elif val.startswith('"') and val.endswith('"'):
+ val = val[1:-1]
+ elif val == "true":
+ val = True
+ elif val == "false":
+ val = False
+ elif val == "null":
+ val = None
+ elif val.startswith("{") and val.endswith("}"):
+ val = _parse_args(val[1:-1], variables)
+ elif val.startswith("[") and val.endswith("]"):
+ val = val # Keep as string for now
+ elif val.replace(".", "").isdigit():
+ val = float(val) if "." in val else int(val)
+ args[key] = val
+ return args
+
+
+def _find_resolver(api_id, type_name, field_name):
+ """Find a resolver for Query.fieldName or Mutation.fieldName."""
+ resolvers = _resolvers.get(api_id, {})
+ # Try exact match
+ if type_name in resolvers and field_name in resolvers[type_name]:
+ return resolvers[type_name][field_name]
+ # Try generic match (some setups use "Query" or "Mutation" type)
+ for tn in resolvers:
+ if field_name in resolvers[tn]:
+ return resolvers[tn][field_name]
+ return None
+
+
+def _resolve_field(api_id, resolver, args, sub_fields, variables):
+ """Execute a resolver against its data source (DynamoDB)."""
+ ds_name = resolver.get("dataSourceName", "")
+ data_source = _data_sources.get(api_id, {}).get(ds_name)
+
+ if not data_source:
+ # No data source — return args as mock
+ return args or {}
+
+ ds_type = data_source.get("type", "NONE")
+
+ if ds_type == "AMAZON_DYNAMODB":
+ return _resolve_dynamodb(data_source, resolver, args, sub_fields)
+ elif ds_type == "AWS_LAMBDA":
+ return _resolve_lambda(data_source, args)
+ else:
+ return args or {}
+
+
+def _resolve_dynamodb(data_source, resolver, args, sub_fields):
+ """Execute a DynamoDB resolver — auto-detect operation from field name and args."""
+ import ministack.services.dynamodb as _ddb
+
+ config = data_source.get("dynamodbConfig", {})
+ table_name = config.get("tableName", "")
+ if not table_name:
+ return None
+
+ table = _ddb._tables.get(table_name)
+ if not table:
+ return None
+
+ field_name = resolver.get("fieldName", "")
+
+ # Auto-detect: get* → GetItem, list* → Scan, create*/update*/put* → PutItem, delete* ��� DeleteItem
+ if field_name.startswith("get") or "id" in args:
+ return _ddb_get_item(table, table_name, args, sub_fields)
+ elif field_name.startswith("list"):
+ return _ddb_scan(table, table_name, args, sub_fields)
+ elif field_name.startswith("create") or field_name.startswith("put"):
+ return _ddb_put_item(table, table_name, args)
+ elif field_name.startswith("update"):
+ return _ddb_update_item(table, table_name, args)
+ elif field_name.startswith("delete"):
+ return _ddb_delete_item(table, table_name, args)
+ else:
+ # Default: try scan
+ return _ddb_scan(table, table_name, args, sub_fields)
+
+
+def _ddb_get_item(table, table_name, args, sub_fields):
+ """Get a single item by primary key."""
+ pk_name = table["pk_name"]
+ sk_name = table.get("sk_name")
+
+ pk_val = args.get("id") or args.get(pk_name) or next(iter(args.values()), None)
+ if pk_val is None:
+ return None
+
+ items = table["items"]
+ pk_bucket = items.get(str(pk_val), {})
+
+ if sk_name:
+ sk_val = args.get(sk_name, "")
+ item = pk_bucket.get(str(sk_val))
+ else:
+ # No sort key — get the single item
+ item = next(iter(pk_bucket.values()), None) if pk_bucket else None
+
+ if not item:
+ return None
+
+ return _strip_ddb_types(item, sub_fields)
+
+
+def _ddb_scan(table, table_name, args, sub_fields):
+ """Scan/list items, optionally with filters and pagination."""
+ items = []
+ limit = args.get("limit", 100)
+ next_token = args.get("nextToken")
+
+ count = 0
+ for pk in sorted(table["items"].keys()):
+ for sk in sorted(table["items"][pk].keys()):
+ if count >= limit:
+ break
+ items.append(_strip_ddb_types(table["items"][pk][sk], sub_fields))
+ count += 1
+
+ # Filter if filter arg provided
+ filter_arg = args.get("filter", {})
+ if filter_arg and isinstance(filter_arg, dict):
+ filtered = []
+ for item in items:
+ match = True
+ for fk, fv in filter_arg.items():
+ if isinstance(fv, dict) and "eq" in fv:
+ if item.get(fk) != fv["eq"]:
+ match = False
+ elif item.get(fk) != fv:
+ match = False
+ if match:
+ filtered.append(item)
+ items = filtered
+
+ return {"items": items, "nextToken": None}
+
+
+def _ddb_put_item(table, table_name, args):
+ """Create/put an item."""
+ import ministack.services.dynamodb as _ddb
+ from collections import defaultdict
+
+ input_data = args.get("input", args)
+ pk_name = table["pk_name"]
+ sk_name = table.get("sk_name")
+
+ # Build DynamoDB-typed item
+ ddb_item = {}
+ for k, v in input_data.items():
+ if isinstance(v, str):
+ ddb_item[k] = {"S": v}
+ elif isinstance(v, (int, float)):
+ ddb_item[k] = {"N": str(v)}
+ elif isinstance(v, bool):
+ ddb_item[k] = {"BOOL": v}
+ elif isinstance(v, list):
+ ddb_item[k] = {"L": [{"S": str(i)} for i in v]}
+ elif v is None:
+ ddb_item[k] = {"NULL": True}
+ else:
+ ddb_item[k] = {"S": str(v)}
+
+ # Auto-generate ID if not provided
+ if pk_name not in ddb_item and "id" not in ddb_item:
+ ddb_item["id" if pk_name == "id" else pk_name] = {"S": new_uuid()}
+
+ pk_val = _ddb._extract_key_val(ddb_item.get(pk_name, {}))
+ sk_val = _ddb._extract_key_val(ddb_item.get(sk_name, {})) if sk_name else ""
+
+ if not isinstance(table["items"], defaultdict):
+ table["items"] = defaultdict(dict, table["items"])
+
+ table["items"][pk_val][sk_val] = ddb_item
+ table["ItemCount"] = sum(len(v) for v in table["items"].values())
+
+ return _strip_ddb_types(ddb_item, [])
+
+
+def _ddb_update_item(table, table_name, args):
+ """Update an existing item — merge input fields."""
+ input_data = args.get("input", args)
+ pk_name = table["pk_name"]
+ pk_val = str(input_data.get("id") or input_data.get(pk_name, ""))
+
+ if pk_val in table["items"]:
+ sk = next(iter(table["items"][pk_val]), "")
+ existing = table["items"][pk_val].get(sk, {})
+ for k, v in input_data.items():
+ if isinstance(v, str):
+ existing[k] = {"S": v}
+ elif isinstance(v, (int, float)):
+ existing[k] = {"N": str(v)}
+ elif isinstance(v, bool):
+ existing[k] = {"BOOL": v}
+ return _strip_ddb_types(existing, [])
+ return None
+
+
+def _ddb_delete_item(table, table_name, args):
+ """Delete an item and return it."""
+ input_data = args.get("input", args)
+ pk_name = table["pk_name"]
+ pk_val = str(input_data.get("id") or input_data.get(pk_name, ""))
+
+ if pk_val in table["items"]:
+ sk = next(iter(table["items"][pk_val]), "")
+ item = table["items"][pk_val].pop(sk, None)
+ if not table["items"][pk_val]:
+ table["items"].pop(pk_val, None)
+ if item:
+ return _strip_ddb_types(item, [])
+ return None
+
+
+def _strip_ddb_types(item, sub_fields):
+ """Convert DynamoDB typed attributes to plain values for GraphQL response."""
+ if not item:
+ return None
+ result = {}
+ for k, v in item.items():
+ if isinstance(v, dict):
+ if "S" in v:
+ result[k] = v["S"]
+ elif "N" in v:
+ val = v["N"]
+ result[k] = int(val) if "." not in val else float(val)
+ elif "BOOL" in v:
+ result[k] = v["BOOL"]
+ elif "NULL" in v:
+ result[k] = None
+ elif "L" in v:
+ result[k] = [_strip_ddb_types(i, []) if isinstance(i, dict) and not any(t in i for t in ("S", "N", "BOOL")) else (i.get("S") or i.get("N") or i.get("BOOL")) for i in v["L"]]
+ elif "M" in v:
+ result[k] = _strip_ddb_types(v["M"], [])
+ else:
+ result[k] = v
+ else:
+ result[k] = v
+ if sub_fields:
+ result = {k: v for k, v in result.items() if k in sub_fields or k == "id" or k == "__typename"}
+ return result
+
+
+def _resolve_lambda(data_source, args):
+ """Execute a Lambda resolver."""
+ config = data_source.get("lambdaConfig", {})
+ func_arn = config.get("lambdaFunctionArn", "")
+ if not func_arn:
+ return args
+
+ import ministack.services.lambda_svc as _lambda_svc
+ func_name = func_arn.rsplit(":", 1)[-1]
+ func = _lambda_svc._functions.get(func_name)
+ if not func:
+ return args
+
+ result = _lambda_svc._execute_function(func, args)
+ body = result.get("body")
+ if isinstance(body, dict):
+ return body
+ if isinstance(body, (str, bytes)):
+ try:
+ return json.loads(body)
+ except Exception:
+ return {"result": body}
+ return args
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 9d03abe7..6f206e03 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -24,6 +24,9 @@ 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
+import ministack.services.appsync as _appsync
+import ministack.services.secretsmanager as _sm
+import ministack.services.cognito as _cognito
logger = logging.getLogger("cloudformation")
@@ -972,6 +975,301 @@ def _sns_topic_policy_delete(physical_id, props):
topic["attributes"].pop("Policy", None)
+# --- AppSync resource provisioners ---
+
+def _appsync_api_create(logical_id, props, stack_name):
+ import time as _time
+ name = props.get("Name") or _physical_name(stack_name, logical_id)
+ auth_type = props.get("AuthenticationType", "API_KEY")
+ api_id = new_uuid()[:8]
+ arn = f"arn:aws:appsync:{REGION}:{ACCOUNT_ID}:apis/{api_id}"
+ now = _time.time()
+ _appsync._apis[api_id] = {
+ "apiId": api_id, "name": name, "authenticationType": auth_type,
+ "arn": arn,
+ "uris": {"GRAPHQL": f"https://{api_id}.appsync-api.{REGION}.amazonaws.com/graphql"},
+ "createdAt": now, "lastUpdatedAt": now,
+ "additionalAuthenticationProviders": props.get("AdditionalAuthenticationProviders", []),
+ "xrayEnabled": False,
+ }
+ _appsync._api_keys[api_id] = {}
+ _appsync._data_sources[api_id] = {}
+ _appsync._resolvers[api_id] = {}
+ _appsync._types[api_id] = {}
+ return api_id, {"ApiId": api_id, "Arn": arn, "GraphQLUrl": f"https://{api_id}.appsync-api.{REGION}.amazonaws.com/graphql"}
+
+
+def _appsync_api_delete(physical_id, props):
+ _appsync._apis.pop(physical_id, None)
+ _appsync._api_keys.pop(physical_id, None)
+ _appsync._data_sources.pop(physical_id, None)
+ _appsync._resolvers.pop(physical_id, None)
+ _appsync._types.pop(physical_id, None)
+
+
+def _appsync_ds_create(logical_id, props, stack_name):
+ api_id = props.get("ApiId", "")
+ name = props.get("Name") or logical_id
+ ds_type = props.get("Type", "NONE")
+ body = {"name": name, "type": ds_type}
+ if props.get("DynamoDBConfig"):
+ body["dynamodbConfig"] = props["DynamoDBConfig"]
+ if props.get("LambdaConfig"):
+ body["lambdaConfig"] = props["LambdaConfig"]
+ if props.get("ServiceRoleArn"):
+ body["serviceRoleArn"] = props["ServiceRoleArn"]
+ _appsync._data_sources.setdefault(api_id, {})[name] = {
+ "name": name, "type": ds_type, **body,
+ "dataSourceArn": f"arn:aws:appsync:{REGION}:{ACCOUNT_ID}:apis/{api_id}/datasources/{name}",
+ }
+ return f"{api_id}/{name}", {"Name": name, "DataSourceArn": f"arn:aws:appsync:{REGION}:{ACCOUNT_ID}:apis/{api_id}/datasources/{name}"}
+
+
+def _appsync_ds_delete(physical_id, props):
+ parts = physical_id.split("/", 1)
+ if len(parts) == 2:
+ _appsync._data_sources.get(parts[0], {}).pop(parts[1], None)
+
+
+def _appsync_resolver_create(logical_id, props, stack_name):
+ api_id = props.get("ApiId", "")
+ type_name = props.get("TypeName", "Query")
+ field_name = props.get("FieldName", logical_id)
+ ds_name = props.get("DataSourceName", "")
+ resolver = {
+ "typeName": type_name, "fieldName": field_name,
+ "dataSourceName": ds_name,
+ "resolverArn": f"arn:aws:appsync:{REGION}:{ACCOUNT_ID}:apis/{api_id}/types/{type_name}/resolvers/{field_name}",
+ }
+ if props.get("RequestMappingTemplate"):
+ resolver["requestMappingTemplate"] = props["RequestMappingTemplate"]
+ if props.get("ResponseMappingTemplate"):
+ resolver["responseMappingTemplate"] = props["ResponseMappingTemplate"]
+ _appsync._resolvers.setdefault(api_id, {}).setdefault(type_name, {})[field_name] = resolver
+ return f"{api_id}/{type_name}/{field_name}", {"ResolverArn": resolver["resolverArn"]}
+
+
+def _appsync_resolver_delete(physical_id, props):
+ parts = physical_id.split("/", 2)
+ if len(parts) == 3:
+ _appsync._resolvers.get(parts[0], {}).get(parts[1], {}).pop(parts[2], None)
+
+
+def _appsync_schema_create(logical_id, props, stack_name):
+ api_id = props.get("ApiId", "")
+ definition = props.get("Definition", "")
+ _appsync._types.setdefault(api_id, {})["__schema__"] = {
+ "typeName": "__schema__", "definition": definition, "format": "SDL",
+ }
+ return f"{api_id}/schema", {}
+
+
+def _appsync_apikey_create(logical_id, props, stack_name):
+ api_id = props.get("ApiId", "")
+ key_id = new_uuid()[:8]
+ import time
+ key = {
+ "id": key_id, "apiKeyId": key_id,
+ "expires": props.get("Expires", int(time.time()) + 604800),
+ }
+ _appsync._api_keys.setdefault(api_id, {})[key_id] = key
+ return key_id, {"ApiKey": key_id, "Arn": f"arn:aws:appsync:{REGION}:{ACCOUNT_ID}:apis/{api_id}/apikeys/{key_id}"}
+
+
+def _appsync_apikey_delete(physical_id, props):
+ api_id = props.get("ApiId", "")
+ _appsync._api_keys.get(api_id, {}).pop(physical_id, None)
+
+
+# --- SecretsManager resource provisioners ---
+
+def _sm_secret_create(logical_id, props, stack_name):
+ import string as _string
+ name = props.get("Name") or _physical_name(stack_name, logical_id)
+ secret_string = props.get("SecretString", "")
+ gen = props.get("GenerateSecretString")
+ if gen and not secret_string:
+ length = gen.get("PasswordLength", 32)
+ exclude = gen.get("ExcludeCharacters", "")
+ chars = _string.ascii_letters + _string.digits + _string.punctuation
+ chars = "".join(c for c in chars if c not in exclude)
+ import random
+ generated = "".join(random.choices(chars, k=length))
+ template = gen.get("SecretStringTemplate")
+ gen_key = gen.get("GenerateStringKey", "password")
+ if template:
+ import json
+ try:
+ obj = json.loads(template)
+ obj[gen_key] = generated
+ secret_string = json.dumps(obj)
+ except Exception:
+ secret_string = generated
+ else:
+ secret_string = generated
+
+ arn = f"arn:aws:secretsmanager:{REGION}:{ACCOUNT_ID}:secret:{name}-{new_uuid()[:6]}"
+ import time as _time
+ _sm._secrets[name] = {
+ "ARN": arn, "Name": name, "Description": props.get("Description", ""),
+ "Tags": props.get("Tags", []),
+ "CreatedDate": _time.time(), "LastChangedDate": _time.time(),
+ "LastAccessedDate": None, "DeletedDate": None,
+ "RotationEnabled": False, "RotationLambdaARN": None,
+ "RotationRules": None, "ReplicationStatus": [],
+ "KmsKeyId": props.get("KmsKeyId"),
+ "Versions": {
+ new_uuid(): {
+ "SecretString": secret_string,
+ "SecretBinary": None,
+ "CreatedDate": _time.time(),
+ "Stages": ["AWSCURRENT"],
+ }
+ },
+ }
+ return name, {"Arn": arn}
+
+
+def _sm_secret_delete(physical_id, props):
+ _sm._secrets.pop(physical_id, None)
+
+
+# --- Cognito UserPool ---
+
+def _cognito_user_pool_create(logical_id, props, stack_name):
+ name = props.get("PoolName") or _physical_name(stack_name, logical_id, max_len=128)
+ pid = _cognito._pool_id()
+ now = _cognito._now_epoch()
+ pool = {
+ "Id": pid,
+ "Name": name,
+ "Arn": _cognito._pool_arn(pid),
+ "CreationDate": now,
+ "LastModifiedDate": now,
+ "Policies": props.get("Policies", {
+ "PasswordPolicy": {
+ "MinimumLength": 8,
+ "RequireUppercase": True,
+ "RequireLowercase": True,
+ "RequireNumbers": True,
+ "RequireSymbols": True,
+ "TemporaryPasswordValidityDays": 7,
+ }
+ }),
+ "Schema": props.get("Schema", []),
+ "AutoVerifiedAttributes": props.get("AutoVerifiedAttributes", []),
+ "AliasAttributes": props.get("AliasAttributes", []),
+ "UsernameAttributes": props.get("UsernameAttributes", []),
+ "MfaConfiguration": props.get("MfaConfiguration", "OFF"),
+ "EstimatedNumberOfUsers": 0,
+ "UserPoolTags": props.get("UserPoolTags", {}),
+ "AdminCreateUserConfig": props.get("AdminCreateUserConfig", {
+ "AllowAdminCreateUserOnly": False,
+ "UnusedAccountValidityDays": 7,
+ }),
+ "Domain": None,
+ "_clients": {},
+ "_users": {},
+ "_groups": {},
+ }
+ _cognito._user_pools[pid] = pool
+ arn = _cognito._pool_arn(pid)
+ provider_name = f"cognito-idp.{REGION}.amazonaws.com/{pid}"
+ return pid, {"Arn": arn, "ProviderName": provider_name}
+
+
+def _cognito_user_pool_delete(physical_id, props):
+ pool = _cognito._user_pools.pop(physical_id, None)
+ if pool and pool.get("Domain"):
+ _cognito._pool_domain_map.pop(pool["Domain"], None)
+
+
+# --- Cognito UserPoolClient ---
+
+def _cognito_user_pool_client_create(logical_id, props, stack_name):
+ pid = props.get("UserPoolId", "")
+ pool = _cognito._user_pools.get(pid)
+ if not pool:
+ raise ValueError(f"UserPool {pid} not found for UserPoolClient")
+
+ cid = _cognito._client_id()
+ now = _cognito._now_epoch()
+ client = {
+ "UserPoolId": pid,
+ "ClientName": props.get("ClientName", ""),
+ "ClientId": cid,
+ "ClientSecret": None,
+ "CreationDate": now,
+ "LastModifiedDate": now,
+ "ExplicitAuthFlows": props.get("ExplicitAuthFlows", []),
+ "AllowedOAuthFlows": props.get("AllowedOAuthFlows", []),
+ "AllowedOAuthScopes": props.get("AllowedOAuthScopes", []),
+ "CallbackURLs": props.get("CallbackURLs", []),
+ "LogoutURLs": props.get("LogoutURLs", []),
+ "SupportedIdentityProviders": props.get("SupportedIdentityProviders", []),
+ }
+ pool["_clients"][cid] = client
+ return cid, {}
+
+
+def _cognito_user_pool_client_delete(physical_id, props):
+ pid = props.get("UserPoolId", "")
+ pool = _cognito._user_pools.get(pid)
+ if pool:
+ pool["_clients"].pop(physical_id, None)
+
+
+# --- Cognito IdentityPool ---
+
+def _cognito_identity_pool_create(logical_id, props, stack_name):
+ name = props.get("IdentityPoolName") or _physical_name(stack_name, logical_id, max_len=128)
+ iid = _cognito._identity_pool_id()
+ pool = {
+ "IdentityPoolId": iid,
+ "IdentityPoolName": name,
+ "AllowUnauthenticatedIdentities": props.get("AllowUnauthenticatedIdentities", False),
+ "AllowClassicFlow": props.get("AllowClassicFlow", False),
+ "SupportedLoginProviders": props.get("SupportedLoginProviders", {}),
+ "DeveloperProviderName": props.get("DeveloperProviderName", ""),
+ "OpenIdConnectProviderARNs": props.get("OpenIdConnectProviderARNs", []),
+ "CognitoIdentityProviders": props.get("CognitoIdentityProviders", []),
+ "SamlProviderARNs": props.get("SamlProviderARNs", []),
+ "IdentityPoolTags": props.get("IdentityPoolTags", {}),
+ "_roles": {},
+ "_identities": {},
+ }
+ _cognito._identity_pools[iid] = pool
+ return iid, {}
+
+
+def _cognito_identity_pool_delete(physical_id, props):
+ _cognito._identity_pools.pop(physical_id, None)
+ _cognito._identity_tags.pop(physical_id, None)
+
+
+# --- Cognito UserPoolDomain ---
+
+def _cognito_user_pool_domain_create(logical_id, props, stack_name):
+ pid = props.get("UserPoolId", "")
+ domain = props.get("Domain", "")
+ pool = _cognito._user_pools.get(pid)
+ if not pool:
+ raise ValueError(f"UserPool {pid} not found for UserPoolDomain")
+ pool["Domain"] = domain
+ _cognito._pool_domain_map[domain] = pid
+ phys_id = f"{pid}-domain-{domain}"
+ return phys_id, {}
+
+
+def _cognito_user_pool_domain_delete(physical_id, props):
+ domain = props.get("Domain", "")
+ pid = _cognito._pool_domain_map.pop(domain, None)
+ if pid:
+ pool = _cognito._user_pools.get(pid)
+ if pool:
+ pool["Domain"] = None
+
+
# ===========================================================================
# Resource Handler Registry
# ===========================================================================
@@ -1003,4 +1301,14 @@ _RESOURCE_HANDLERS = {
"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},
+ "AWS::AppSync::GraphQLApi": {"create": _appsync_api_create, "delete": _appsync_api_delete},
+ "AWS::AppSync::DataSource": {"create": _appsync_ds_create, "delete": _appsync_ds_delete},
+ "AWS::AppSync::Resolver": {"create": _appsync_resolver_create, "delete": _appsync_resolver_delete},
+ "AWS::AppSync::GraphQLSchema": {"create": _appsync_schema_create},
+ "AWS::AppSync::ApiKey": {"create": _appsync_apikey_create, "delete": _appsync_apikey_delete},
+ "AWS::SecretsManager::Secret": {"create": _sm_secret_create, "delete": _sm_secret_delete},
+ "AWS::Cognito::UserPool": {"create": _cognito_user_pool_create, "delete": _cognito_user_pool_delete},
+ "AWS::Cognito::UserPoolClient": {"create": _cognito_user_pool_client_create, "delete": _cognito_user_pool_client_delete},
+ "AWS::Cognito::IdentityPool": {"create": _cognito_identity_pool_create, "delete": _cognito_identity_pool_delete},
+ "AWS::Cognito::UserPoolDomain": {"create": _cognito_user_pool_domain_create, "delete": _cognito_user_pool_domain_delete},
}
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 4f1dc9c3..e1290579 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -223,7 +223,7 @@ def _identity_id(pool_id: str) -> str:
def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "access") -> str:
"""Return a plausible-looking but non-cryptographic JWT stub."""
header = base64.urlsafe_b64encode(
- json.dumps({"alg": "RS256", "kid": "ministack"}).encode()
+ json.dumps({"alg": "RS256", "kid": "ministack-key-1"}).encode()
).rstrip(b"=").decode()
now = int(time.time())
payload = base64.urlsafe_b64encode(
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index a95e7b85..224732ce 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -43,14 +43,19 @@ _lock = threading.Lock()
# ── Persistence ────────────────────────────────────────────
def get_state():
- return {"tables": copy.deepcopy(_tables), "tags": copy.deepcopy(_tags), "ttl_settings": copy.deepcopy(_ttl_settings)}
+ return {"tables": copy.deepcopy(_tables), "tags": copy.deepcopy(_tags), "ttl_settings": copy.deepcopy(_ttl_settings), "pitr_settings": copy.deepcopy(_pitr_settings)}
def restore_state(data):
if data:
_tables.update(data.get("tables", {}))
+ # Restore items as defaultdict(dict) — JSON deserializes as plain dict
+ for tbl in _tables.values():
+ if isinstance(tbl.get("items"), dict) and not isinstance(tbl["items"], defaultdict):
+ tbl["items"] = defaultdict(dict, tbl["items"])
_tags.update(data.get("tags", {}))
_ttl_settings.update(data.get("ttl_settings", {}))
+ _pitr_settings.update(data.get("pitr_settings", {}))
_restored = load_state("dynamodb")
@@ -536,7 +541,10 @@ def _query(data):
candidates = candidates[:limit]
scanned_count = len(candidates)
- if filter_expr:
+ query_filter = data.get("QueryFilter")
+ if query_filter and not filter_expr:
+ filtered = [it for it in candidates if _evaluate_legacy_filter(it, query_filter)]
+ elif filter_expr:
filtered = [it for it in candidates if _evaluate_condition(filter_expr, it, eav, ean)]
else:
filtered = candidates
@@ -595,7 +603,12 @@ def _scan(data):
all_items = all_items[:limit]
scanned_count = len(all_items)
- if filter_expr:
+
+ # Legacy ScanFilter / QueryFilter support
+ scan_filter = data.get("ScanFilter") or data.get("QueryFilter")
+ if scan_filter and not filter_expr:
+ filtered = [it for it in all_items if _evaluate_legacy_filter(it, scan_filter)]
+ elif filter_expr:
filtered = [it for it in all_items if _evaluate_condition(filter_expr, it, eav, ean)]
else:
filtered = all_items
@@ -1782,6 +1795,37 @@ def _update_counts(table):
table["TableSizeBytes"] = count * 200
+def _evaluate_legacy_filter(item, scan_filter):
+ """Evaluate legacy ScanFilter/QueryFilter conditions."""
+ for attr_name, condition in scan_filter.items():
+ op = condition.get("ComparisonOperator", "")
+ attr_vals = condition.get("AttributeValueList", [])
+ item_val = item.get(attr_name)
+ if op == "EQ":
+ if item_val is None or item_val != attr_vals[0]:
+ return False
+ elif op == "NE":
+ if item_val is not None and item_val == attr_vals[0]:
+ return False
+ elif op == "NOT_NULL":
+ if item_val is None:
+ return False
+ elif op == "NULL":
+ if item_val is not None:
+ return False
+ elif op == "CONTAINS":
+ val = _extract_key_val(item_val) if item_val else ""
+ target = _extract_key_val(attr_vals[0]) if attr_vals else ""
+ if target not in str(val):
+ return False
+ elif op == "BEGINS_WITH":
+ val = _extract_key_val(item_val) if item_val else ""
+ target = _extract_key_val(attr_vals[0]) if attr_vals else ""
+ if not str(val).startswith(str(target)):
+ return False
+ return True
+
+
def _add_consumed_capacity(result, data, table_name, write=False):
rc = data.get("ReturnConsumedCapacity", "NONE")
if rc == "NONE":
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 2e092c24..e7d41a2a 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -142,6 +142,8 @@ if _restored:
_DEFAULT_VPC_ID = "vpc-00000001"
_DEFAULT_SUBNET_ID = "subnet-00000001"
_DEFAULT_SG_ID = "sg-00000001"
+_DEFAULT_RTB_ID = "rtb-00000001"
+_DEFAULT_ACL_ID = "acl-00000001"
_DEFAULT_IGW_ID = "igw-00000001"
@@ -155,6 +157,9 @@ def _init_defaults():
"DhcpOptionsId": "dopt-00000001",
"InstanceTenancy": "default",
"OwnerId": ACCOUNT_ID,
+ "DefaultNetworkAclId": _DEFAULT_ACL_ID,
+ "DefaultSecurityGroupId": _DEFAULT_SG_ID,
+ "MainRouteTableId": _DEFAULT_RTB_ID,
}
if _DEFAULT_SUBNET_ID not in _subnets:
_subnets[_DEFAULT_SUBNET_ID] = {
@@ -590,6 +595,7 @@ def _describe_vpcs(p):
def _create_vpc(p):
cidr = _p(p, "CidrBlock") or "10.0.0.0/16"
vpc_id = _new_vpc_id()
+ acl_id = "acl-" + "".join(random.choices(string.hexdigits[:16], k=17))
_vpcs[vpc_id] = {
"VpcId": vpc_id,
"CidrBlock": cidr,
@@ -598,6 +604,9 @@ def _create_vpc(p):
"DhcpOptionsId": "dopt-00000001",
"InstanceTenancy": _p(p, "InstanceTenancy") or "default",
"OwnerId": ACCOUNT_ID,
+ "DefaultNetworkAclId": acl_id,
+ "DefaultSecurityGroupId": _DEFAULT_SG_ID,
+ "MainRouteTableId": _DEFAULT_RTB_ID,
}
return _xml(200, "CreateVpcResponse", _vpc_fields_xml(_vpcs[vpc_id], tag="vpc"))
@@ -1506,6 +1515,9 @@ def _vpc_fields_xml(vpc, tag="item"):
<instanceTenancy>{vpc['InstanceTenancy']}</instanceTenancy>
<isDefault>{'true' if vpc['IsDefault'] else 'false'}</isDefault>
<ownerId>{vpc['OwnerId']}</ownerId>
+ {'<defaultNetworkAclId>' + vpc.get('DefaultNetworkAclId', '') + '</defaultNetworkAclId>' if vpc.get('DefaultNetworkAclId') else ''}
+ {'<defaultSecurityGroupId>' + vpc.get('DefaultSecurityGroupId', '') + '</defaultSecurityGroupId>' if vpc.get('DefaultSecurityGroupId') else ''}
+ {'<mainRouteTableId>' + vpc.get('MainRouteTableId', '') + '</mainRouteTableId>' if vpc.get('MainRouteTableId') else ''}
<tagSet/>
</{tag}>"""
@@ -1563,6 +1575,7 @@ def _rtb_fields_xml(rtb, tag="item"):
<routeTableId>{a['RouteTableId']}</routeTableId>
<main>{'true' if a.get('Main') else 'false'}</main>
{'<subnetId>' + a['SubnetId'] + '</subnetId>' if a.get('SubnetId') else ''}
+ <associationState><state>associated</state></associationState>
</item>""" for a in rtb.get("Associations", []))
return f"""<{tag}>
<routeTableId>{rtb['RouteTableId']}</routeTableId>
@@ -2508,6 +2521,58 @@ def _describe_capacity_reservations(p):
return _xml(200, "DescribeCapacityReservationsResponse", "<capacityReservationSet/>")
+def _describe_addresses_attribute(p):
+ alloc_id = _p(p, "AllocationId") or _parse_member_list(p, "AllocationId")
+ items = ""
+ if isinstance(alloc_id, list):
+ for aid in alloc_id:
+ items += f"<item><allocationId>{aid}</allocationId><ptrRecord></ptrRecord></item>"
+ elif alloc_id:
+ items = f"<item><allocationId>{alloc_id}</allocationId><ptrRecord></ptrRecord></item>"
+ return _xml(200, "DescribeAddressesAttributeResponse", f"<addressSet>{items}</addressSet>")
+
+
+def _describe_security_group_rules(p):
+ sg_ids = _parse_member_list(p, "SecurityGroupId") or []
+ filters = _parse_filters(p)
+ sg_id_filter = filters.get("group-id", [])
+ if sg_id_filter:
+ sg_ids = sg_id_filter
+
+ items = ""
+ for sg_id in sg_ids:
+ sg = _security_groups.get(sg_id)
+ if not sg:
+ continue
+ for i, rule in enumerate(sg.get("IpPermissions", [])):
+ rule_id = f"sgr-{sg_id[3:]}-ingress-{i}"
+ for cidr in rule.get("IpRanges", []):
+ items += f"""<item>
+ <securityGroupRuleId>{rule_id}</securityGroupRuleId>
+ <groupId>{sg_id}</groupId>
+ <groupOwnerId>{ACCOUNT_ID}</groupOwnerId>
+ <isEgress>false</isEgress>
+ <ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>
+ <fromPort>{rule.get('FromPort', -1)}</fromPort>
+ <toPort>{rule.get('ToPort', -1)}</toPort>
+ <cidrIpv4>{cidr.get('CidrIp', '')}</cidrIpv4>
+ </item>"""
+ for i, rule in enumerate(sg.get("IpPermissionsEgress", [])):
+ rule_id = f"sgr-{sg_id[3:]}-egress-{i}"
+ for cidr in rule.get("IpRanges", []):
+ items += f"""<item>
+ <securityGroupRuleId>{rule_id}</securityGroupRuleId>
+ <groupId>{sg_id}</groupId>
+ <groupOwnerId>{ACCOUNT_ID}</groupOwnerId>
+ <isEgress>true</isEgress>
+ <ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>
+ <fromPort>{rule.get('FromPort', -1)}</fromPort>
+ <toPort>{rule.get('ToPort', -1)}</toPort>
+ <cidrIpv4>{cidr.get('CidrIp', '')}</cidrIpv4>
+ </item>"""
+ return _xml(200, "DescribeSecurityGroupRulesResponse", f"<securityGroupRuleSet>{items}</securityGroupRuleSet>")
+
+
_ACTION_MAP = {
"RunInstances": _run_instances,
"DescribeInstances": _describe_instances,
@@ -2558,6 +2623,8 @@ _ACTION_MAP = {
"DescribeTags": _describe_tags,
"ModifyVpcAttribute": _modify_vpc_attribute,
"DescribeVpcAttribute": _describe_vpc_attribute,
+ "DescribeAddressesAttribute": _describe_addresses_attribute,
+ "DescribeSecurityGroupRules": _describe_security_group_rules,
"ModifySubnetAttribute": _modify_subnet_attribute,
"CreateRouteTable": _create_route_table,
"DeleteRouteTable": _delete_route_table,
diff --git a/ministack/services/kms.py b/ministack/services/kms.py
index a6bc0713..bd274994 100644
--- a/ministack/services/kms.py
+++ b/ministack/services/kms.py
@@ -51,7 +51,7 @@ _aliases: dict = {} # alias_name -> key_id (e.g. "alias/my-key" -> "uuid")
def get_state():
"""Return JSON-serializable state. Symmetric keys are base64-encoded;
- RSA private keys are stripped (not serializable)."""
+ RSA private keys are PEM-encoded if cryptography is available."""
serializable_keys = {}
for kid, rec in _keys.items():
entry = {k: v for k, v in rec.items()
@@ -60,7 +60,16 @@ def get_state():
entry["_symmetric_key_b64"] = base64.b64encode(rec["_symmetric_key"]).decode()
if "_public_key_der" in rec:
entry["_public_key_der_b64"] = base64.b64encode(rec["_public_key_der"]).decode()
- # RSA private keys are skipped — not JSON-serializable
+ if "_private_key" in rec and HAS_CRYPTO:
+ try:
+ pem = rec["_private_key"].private_bytes(
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ )
+ entry["_private_key_pem"] = base64.b64encode(pem).decode()
+ except Exception:
+ pass
serializable_keys[kid] = entry
return {"keys": serializable_keys, "aliases": _aliases}
@@ -72,6 +81,12 @@ def restore_state(data):
entry["_symmetric_key"] = base64.b64decode(entry.pop("_symmetric_key_b64"))
if "_public_key_der_b64" in entry:
entry["_public_key_der"] = base64.b64decode(entry.pop("_public_key_der_b64"))
+ if "_private_key_pem" in entry and HAS_CRYPTO:
+ try:
+ pem_bytes = base64.b64decode(entry.pop("_private_key_pem"))
+ entry["_private_key"] = serialization.load_pem_private_key(pem_bytes, password=None)
+ except Exception:
+ pass
_keys[kid] = entry
_aliases.update(data.get("aliases", {}))
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index cd5a4e7f..3fb7fbde 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -383,6 +383,8 @@ def _dispatch(
if method == "PUT":
if "partNumber" in query_params and "uploadId" in query_params:
+ if "x-amz-copy-source" in headers:
+ return _upload_part_copy(bucket, key, query_params, headers)
return _upload_part(bucket, key, body, query_params, headers)
if "tagging" in query_params:
return _put_object_tagging(bucket, key, body)
@@ -2436,6 +2438,50 @@ def _upload_part(
return 200, {"ETag": etag}, b""
+def _upload_part_copy(bucket_name: str, dest_key: str, query_params: dict, headers: dict):
+ """UploadPartCopy — copy a range from an existing object as a multipart part."""
+ upload_id = _qp(query_params, "uploadId")
+ part_number = int(_qp(query_params, "partNumber", "1"))
+
+ if upload_id not in _multipart_uploads:
+ return _error("NoSuchUpload", "The specified multipart upload does not exist.", 404)
+
+ source = url_unquote(headers.get("x-amz-copy-source", "").lstrip("/"))
+ src_parts = source.split("?", 1)[0].split("/", 1)
+ if len(src_parts) < 2:
+ return _error("InvalidArgument", "Copy Source must mention the source bucket and key", 400)
+
+ src_bucket_name, src_key = src_parts
+ src_bucket = _ensure_bucket(src_bucket_name)
+ if src_bucket is None:
+ return _no_such_bucket(src_bucket_name)
+ if src_key not in src_bucket["objects"]:
+ return _error("NoSuchKey", "The specified key does not exist.", 404)
+
+ src_obj = src_bucket["objects"][src_key]
+ src_body = src_obj["body"]
+
+ # Handle x-amz-copy-source-range
+ copy_range = headers.get("x-amz-copy-source-range", "")
+ if copy_range and copy_range.startswith("bytes="):
+ rng = copy_range[6:]
+ start, end = rng.split("-")
+ src_body = src_body[int(start):int(end) + 1]
+
+ etag = f'"{md5_hash(src_body)}"'
+ _multipart_uploads[upload_id]["parts"][part_number] = {
+ "body": src_body,
+ "etag": etag,
+ "size": len(src_body),
+ "last_modified": now_iso(),
+ }
+
+ root = Element("CopyPartResult", xmlns=S3_NS)
+ SubElement(root, "ETag").text = etag
+ SubElement(root, "LastModified").text = now_iso()
+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)
+
+
def _complete_multipart_upload(
bucket_name: str, key: str, body: bytes, query_params: dict
):
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 45cf3d8c..66c702c5 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -443,7 +443,10 @@ def _publish(params):
"timestamp": time.time(),
})
- _fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs)
+ group_id = _p(params, "MessageGroupId") or ""
+ dedup_id = _p(params, "MessageDeduplicationId") or ""
+ _fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs,
+ message_group_id=group_id, message_dedup_id=dedup_id)
logger.info("SNS publish to %s: %s", topic_arn, message[:100])
return _xml(200, "PublishResponse",
@@ -512,7 +515,8 @@ def _publish_batch(params):
# ---------------------------------------------------------------------------
def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,
- message_structure: str = "", message_attributes: dict | None = None):
+ message_structure: str = "", message_attributes: dict | None = None,
+ message_group_id: str = "", message_dedup_id: str = ""):
topic = _topics.get(topic_arn)
if not topic:
return
@@ -538,7 +542,8 @@ def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,
)
if protocol == "sqs":
- _deliver_to_sqs(endpoint, envelope, raw, effective_message)
+ _deliver_to_sqs(endpoint, envelope, raw, effective_message,
+ message_group_id=message_group_id, message_dedup_id=message_dedup_id)
elif protocol in ("http", "https"):
_threading.Thread(
target=asyncio.run,
@@ -555,7 +560,8 @@ def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,
logger.info("SNS fanout → application %s (stub)", endpoint)
-def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str):
+def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str,
+ message_group_id: str = "", message_dedup_id: str = ""):
queue_name = endpoint.split(":")[-1]
queue_url = _sqs._queue_url(queue_name)
queue = _sqs._queues.get(queue_url)
@@ -574,6 +580,10 @@ def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str):
"visible_at": now,
"receive_count": 0,
}
+ if message_group_id:
+ msg["group_id"] = message_group_id
+ if message_dedup_id:
+ msg["dedup_id"] = message_dedup_id
_sqs._ensure_msg_fields(msg)
queue["messages"].append(msg)
logger.info("SNS fanout → SQS %s", queue_name)
diff --git a/pyproject.toml b/pyproject.toml
index 407f5d0f..ba71ca90 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.32"
+version = "1.1.33"
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 77bfdc42..0077743c 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -6258,19 +6258,21 @@ def test_lambda_update_code_s3_missing_returns_error(lam):
# ========== Lambda — versioning ==========
-def test_lambda_publish_version(lam):
+def test_lambda_publish_version_with_create(lam):
code = "def handler(event, context): return {'ver': 1}"
- lam.create_function(
- FunctionName="lam-versioned",
- Runtime="python3.11",
- Role=_LAMBDA_ROLE,
- Handler="index.handler",
- Code={"ZipFile": _make_zip(code)},
- Publish=True,
- )
- resp = lam.list_versions_by_function(FunctionName="lam-versioned")
+ try:
+ lam.get_function(FunctionName="lam-versioned-pub")
+ except Exception:
+ lam.create_function(
+ FunctionName="lam-versioned-pub",
+ Runtime="python3.11",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ Publish=True,
+ )
+ resp = lam.list_versions_by_function(FunctionName="lam-versioned-pub")
versions = [v["Version"] for v in resp["Versions"]]
- assert "$LATEST" in versions
assert any(v != "$LATEST" for v in versions)
@@ -11561,7 +11563,7 @@ def test_lambda_alias_crud(lam):
assert not any(a["Name"] == "prod" for a in aliases2)
-def test_lambda_publish_version(lam):
+def test_lambda_publish_version_snapshot(lam):
"""PublishVersion creates a numbered version snapshot."""
code = _zip_lambda("def handler(e,c): return 'v1'")
lam.create_function(
@@ -12054,7 +12056,7 @@ def test_kinesis_retention_period(kin):
assert desc2["RetentionPeriodHours"] == 24
-def test_kinesis_stream_encryption(kin):
+def test_kinesis_stream_encryption_toggle(kin):
"""StartStreamEncryption / StopStreamEncryption."""
kin.create_stream(StreamName="qa-kin-enc", ShardCount=1)
kin.start_stream_encryption(
@@ -12549,7 +12551,7 @@ def test_apigw_update_integration(apigw):
assert "new-fn" in integ["IntegrationUri"]
-def test_apigw_delete_route(apigw):
+def test_apigw_delete_route_v2(apigw):
"""DeleteRoute removes the route from GetRoutes."""
api_id = apigw.create_api(Name="qa-apigw-del-route", ProtocolType="HTTP")["ApiId"]
route_id = apigw.create_route(ApiId=api_id, RouteKey="GET /qa")["RouteId"]
@@ -18204,3 +18206,436 @@ def test_ec2_describe_vpc_attribute(ec2):
assert resp["EnableDnsSupport"]["Value"] in (True, False)
resp2 = ec2.describe_vpc_attribute(VpcId=vpc_id, Attribute="enableDnsHostnames")
assert resp2["EnableDnsHostnames"]["Value"] in (True, False)
+
+
+# ========== S3 UploadPartCopy ==========
+
+
+def test_s3_upload_part_copy(s3):
+ """Multipart upload with UploadPartCopy (x-amz-copy-source) produces correct final object."""
+ bkt = "intg-s3-partcopy"
+ s3.create_bucket(Bucket=bkt)
+ src_key = "source-obj.txt"
+ dst_key = "dest-obj.txt"
+ src_data = b"COPIED-DATA-FROM-SOURCE"
+ s3.put_object(Bucket=bkt, Key=src_key, Body=src_data)
+
+ mpu = s3.create_multipart_upload(Bucket=bkt, Key=dst_key)
+ upload_id = mpu["UploadId"]
+
+ copy_resp = s3.upload_part_copy(
+ Bucket=bkt,
+ Key=dst_key,
+ UploadId=upload_id,
+ PartNumber=1,
+ CopySource={"Bucket": bkt, "Key": src_key},
+ )
+ etag = copy_resp["CopyPartResult"]["ETag"]
+
+ s3.complete_multipart_upload(
+ Bucket=bkt,
+ Key=dst_key,
+ UploadId=upload_id,
+ MultipartUpload={
+ "Parts": [{"PartNumber": 1, "ETag": etag}]
+ },
+ )
+
+ resp = s3.get_object(Bucket=bkt, Key=dst_key)
+ assert resp["Body"].read() == src_data
+
+
+# ========== SNS FIFO Dedup Passthrough ==========
+
+
+def test_sns_fifo_dedup_passthrough(sns, sqs):
+ """SNS FIFO topic passes MessageGroupId through to the SQS FIFO subscriber."""
+ topic_arn = sns.create_topic(
+ Name="intg-sns-fifo-dedup.fifo",
+ Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "false"},
+ )["TopicArn"]
+
+ q_url = sqs.create_queue(
+ QueueName="intg-sns-fifo-dedup-q.fifo",
+ Attributes={"FifoQueue": "true"},
+ )["QueueUrl"]
+ q_arn = sqs.get_queue_attributes(
+ QueueUrl=q_url, AttributeNames=["QueueArn"],
+ )["Attributes"]["QueueArn"]
+
+ sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
+
+ sns.publish(
+ TopicArn=topic_arn,
+ Message="fifo-dedup-test",
+ MessageGroupId="grp-1",
+ MessageDeduplicationId="dedup-001",
+ )
+
+ msgs = sqs.receive_message(
+ QueueUrl=q_url,
+ MaxNumberOfMessages=1,
+ WaitTimeSeconds=2,
+ AttributeNames=["All"],
+ )
+ assert len(msgs.get("Messages", [])) == 1
+ msg = msgs["Messages"][0]
+ body = json.loads(msg["Body"])
+ assert body["Message"] == "fifo-dedup-test"
+ attrs = msg.get("Attributes", {})
+ assert attrs.get("MessageGroupId") == "grp-1"
+
+
+# ========== CFN SecretsManager with GenerateSecretString ==========
+
+
+def test_cfn_secretsmanager_generate_secret_string(cfn, sm):
+ """CFN stack with SecretsManager::Secret + GenerateSecretString produces valid JSON secret."""
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "MySecret": {
+ "Type": "AWS::SecretsManager::Secret",
+ "Properties": {
+ "Name": "intg-cfn-gensecret",
+ "GenerateSecretString": {
+ "PasswordLength": 20,
+ "SecretStringTemplate": '{"username":"admin"}',
+ "GenerateStringKey": "password",
+ },
+ },
+ }
+ },
+ }
+ cfn.create_stack(
+ StackName="intg-cfn-gensecret-stack",
+ TemplateBody=json.dumps(template),
+ )
+ stack = _wait_stack(cfn, "intg-cfn-gensecret-stack")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ resp = sm.get_secret_value(SecretId="intg-cfn-gensecret")
+ secret = json.loads(resp["SecretString"])
+ assert secret["username"] == "admin"
+ assert "password" in secret
+ assert len(secret["password"]) >= 20
+
+
+# ========== DynamoDB ScanFilter (legacy) ==========
+
+
+def test_ddb_scan_filter_legacy(ddb):
+ """Scan with legacy ScanFilter (ComparisonOperator style) returns matching items."""
+ table = "intg-ddb-scanfilter"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ for i in range(5):
+ ddb.put_item(TableName=table, Item={
+ "pk": {"S": f"sf_{i}"},
+ "color": {"S": "red" if i % 2 == 0 else "blue"},
+ })
+
+ resp = ddb.scan(
+ TableName=table,
+ ScanFilter={
+ "color": {
+ "AttributeValueList": [{"S": "red"}],
+ "ComparisonOperator": "EQ",
+ }
+ },
+ )
+ assert resp["Count"] == 3
+ for item in resp["Items"]:
+ assert item["color"]["S"] == "red"
+
+
+# ========== DynamoDB QueryFilter (legacy) ==========
+
+
+def test_ddb_query_filter_legacy(ddb):
+ """Query with legacy QueryFilter (ComparisonOperator style) returns matching items."""
+ table = "intg-ddb-queryfilter"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[
+ {"AttributeName": "pk", "KeyType": "HASH"},
+ {"AttributeName": "sk", "KeyType": "RANGE"},
+ ],
+ AttributeDefinitions=[
+ {"AttributeName": "pk", "AttributeType": "S"},
+ {"AttributeName": "sk", "AttributeType": "S"},
+ ],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ for i in range(5):
+ ddb.put_item(TableName=table, Item={
+ "pk": {"S": "qf_pk"},
+ "sk": {"S": f"sk_{i}"},
+ "status": {"S": "active" if i < 3 else "inactive"},
+ })
+
+ resp = ddb.query(
+ TableName=table,
+ KeyConditionExpression="pk = :pk",
+ ExpressionAttributeValues={":pk": {"S": "qf_pk"}},
+ QueryFilter={
+ "status": {
+ "AttributeValueList": [{"S": "active"}],
+ "ComparisonOperator": "EQ",
+ }
+ },
+ )
+ assert resp["Count"] == 3
+ assert resp["ScannedCount"] == 5
+ for item in resp["Items"]:
+ assert item["status"]["S"] == "active"
+
+
+# ========== AppSync GraphQL Data Plane ==========
+
+
+def test_appsync_graphql_create_and_query(ddb):
+ """Full AppSync flow: create API + data source + resolver, then execute GraphQL."""
+ from conftest import make_client
+ appsync = make_client("appsync")
+
+ # Create DynamoDB table
+ ddb.create_table(
+ TableName="gql-users",
+ KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ # Create API
+ api = appsync.create_graphql_api(name="gql-test", authenticationType="API_KEY")["graphqlApi"]
+ api_id = api["apiId"]
+
+ # Create API key
+ key = appsync.create_api_key(apiId=api_id)["apiKey"]
+
+ # Create data source
+ appsync.create_data_source(
+ apiId=api_id, name="usersDS", type="AMAZON_DYNAMODB",
+ dynamodbConfig={"tableName": "gql-users", "awsRegion": "us-east-1"},
+ )
+
+ # Create resolvers
+ appsync.create_resolver(
+ apiId=api_id, typeName="Mutation", fieldName="createUser",
+ dataSourceName="usersDS",
+ )
+ appsync.create_resolver(
+ apiId=api_id, typeName="Query", fieldName="getUser",
+ dataSourceName="usersDS",
+ )
+ appsync.create_resolver(
+ apiId=api_id, typeName="Query", fieldName="listUsers",
+ dataSourceName="usersDS",
+ )
+
+ # Execute mutation via HTTP
+ import urllib.request, json as _json
+ mutation = _json.dumps({
+ "query": 'mutation CreateUser { createUser(input: {id: "u1", name: "Alice", email: "[email protected]"}) { id name email } }',
+ }).encode()
+ req = urllib.request.Request(
+ f"http://localhost:4566/v1/apis/{api_id}/graphql",
+ data=mutation,
+ headers={"Content-Type": "application/json", "x-api-key": key["id"]},
+ )
+ with urllib.request.urlopen(req) as r:
+ resp = _json.loads(r.read())
+ assert "data" in resp
+ assert resp["data"]["createUser"]["name"] == "Alice"
+
+ # Query
+ query = _json.dumps({
+ "query": 'query GetUser { getUser(id: "u1") { id name email } }',
+ }).encode()
+ req = urllib.request.Request(
+ f"http://localhost:4566/v1/apis/{api_id}/graphql",
+ data=query,
+ headers={"Content-Type": "application/json", "x-api-key": key["id"]},
+ )
+ with urllib.request.urlopen(req) as r:
+ resp = _json.loads(r.read())
+ assert resp["data"]["getUser"]["name"] == "Alice"
+ assert resp["data"]["getUser"]["id"] == "u1"
+
+ # List
+ list_q = _json.dumps({
+ "query": "query ListUsers { listUsers { items { id name } } }",
+ }).encode()
+ req = urllib.request.Request(
+ f"http://localhost:4566/v1/apis/{api_id}/graphql",
+ data=list_q,
+ headers={"Content-Type": "application/json", "x-api-key": key["id"]},
+ )
+ with urllib.request.urlopen(req) as r:
+ resp = _json.loads(r.read())
+ items = resp["data"]["listUsers"]["items"]
+ assert len(items) >= 1
+ assert any(u["name"] == "Alice" for u in items)
+
+
+def test_appsync_graphql_update_mutation(ddb):
+ """Update an existing item via GraphQL mutation."""
+ import urllib.request, json as _json
+ from conftest import make_client
+ appsync = make_client("appsync")
+
+ try:
+ ddb.create_table(TableName="gql-update", KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}], BillingMode="PAY_PER_REQUEST")
+ except Exception:
+ pass
+
+ api = appsync.create_graphql_api(name="gql-upd", authenticationType="API_KEY")["graphqlApi"]
+ key = appsync.create_api_key(apiId=api["apiId"])["apiKey"]
+ appsync.create_data_source(apiId=api["apiId"], name="ds", type="AMAZON_DYNAMODB",
+ dynamodbConfig={"tableName": "gql-update", "awsRegion": "us-east-1"})
+ appsync.create_resolver(apiId=api["apiId"], typeName="Mutation", fieldName="createItem", dataSourceName="ds")
+ appsync.create_resolver(apiId=api["apiId"], typeName="Mutation", fieldName="updateItem", dataSourceName="ds")
+ appsync.create_resolver(apiId=api["apiId"], typeName="Query", fieldName="getItem", dataSourceName="ds")
+
+ def gql(query):
+ req = urllib.request.Request(f"http://localhost:4566/v1/apis/{api['apiId']}/graphql",
+ data=_json.dumps({"query": query}).encode(), headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req) as r:
+ return _json.loads(r.read())
+
+ # Create
+ gql('mutation { createItem(input: {id: "i1", title: "Original"}) { id title } }')
+ # Update
+ resp = gql('mutation { updateItem(input: {id: "i1", title: "Updated"}) { id title } }')
+ assert resp["data"]["updateItem"]["title"] == "Updated"
+ # Verify via get
+ resp = gql('query { getItem(id: "i1") { id title } }')
+ assert resp["data"]["getItem"]["title"] == "Updated"
+
+
+def test_appsync_graphql_delete_mutation(ddb):
+ """Delete an item via GraphQL mutation."""
+ import urllib.request, json as _json
+ from conftest import make_client
+ appsync = make_client("appsync")
+
+ try:
+ ddb.create_table(TableName="gql-del", KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}], BillingMode="PAY_PER_REQUEST")
+ except Exception:
+ pass
+
+ api = appsync.create_graphql_api(name="gql-del", authenticationType="API_KEY")["graphqlApi"]
+ appsync.create_data_source(apiId=api["apiId"], name="ds", type="AMAZON_DYNAMODB",
+ dynamodbConfig={"tableName": "gql-del", "awsRegion": "us-east-1"})
+ appsync.create_resolver(apiId=api["apiId"], typeName="Mutation", fieldName="createItem", dataSourceName="ds")
+ appsync.create_resolver(apiId=api["apiId"], typeName="Mutation", fieldName="deleteItem", dataSourceName="ds")
+ appsync.create_resolver(apiId=api["apiId"], typeName="Query", fieldName="getItem", dataSourceName="ds")
+
+ def gql(query):
+ req = urllib.request.Request(f"http://localhost:4566/v1/apis/{api['apiId']}/graphql",
+ data=_json.dumps({"query": query}).encode(), headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req) as r:
+ return _json.loads(r.read())
+
+ gql('mutation { createItem(input: {id: "d1", title: "Doomed"}) { id } }')
+ resp = gql('mutation { deleteItem(input: {id: "d1"}) { id title } }')
+ assert resp["data"]["deleteItem"]["id"] == "d1"
+ # Verify deleted
+ resp = gql('query { getItem(id: "d1") { id } }')
+ assert resp["data"]["getItem"] is None
+
+
+def test_appsync_graphql_with_variables():
+ """GraphQL query using $variables."""
+ import urllib.request, json as _json
+ from conftest import make_client
+ appsync = make_client("appsync")
+ ddb_client = make_client("dynamodb")
+
+ try:
+ ddb_client.create_table(TableName="gql-vars", KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}], BillingMode="PAY_PER_REQUEST")
+ except Exception:
+ pass
+
+ api = appsync.create_graphql_api(name="gql-vars", authenticationType="API_KEY")["graphqlApi"]
+ appsync.create_data_source(apiId=api["apiId"], name="ds", type="AMAZON_DYNAMODB",
+ dynamodbConfig={"tableName": "gql-vars", "awsRegion": "us-east-1"})
+ appsync.create_resolver(apiId=api["apiId"], typeName="Mutation", fieldName="createItem", dataSourceName="ds")
+ appsync.create_resolver(apiId=api["apiId"], typeName="Query", fieldName="getItem", dataSourceName="ds")
+
+ def gql(query, variables=None):
+ body = {"query": query}
+ if variables:
+ body["variables"] = variables
+ req = urllib.request.Request(f"http://localhost:4566/v1/apis/{api['apiId']}/graphql",
+ data=_json.dumps(body).encode(), headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req) as r:
+ return _json.loads(r.read())
+
+ gql('mutation { createItem(input: {id: "v1", name: "Var Test"}) { id } }')
+ resp = gql('query GetItem($id: ID!) { getItem(id: $id) { id name } }', {"id": "v1"})
+ assert resp["data"]["getItem"]["name"] == "Var Test"
+
+
+def test_appsync_graphql_nonexistent_item():
+ """Query for a non-existent item returns null."""
+ import urllib.request, json as _json
+ from conftest import make_client
+ appsync = make_client("appsync")
+ ddb_client = make_client("dynamodb")
+
+ try:
+ ddb_client.create_table(TableName="gql-404", KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}], BillingMode="PAY_PER_REQUEST")
+ except Exception:
+ pass
+
+ api = appsync.create_graphql_api(name="gql-404", authenticationType="API_KEY")["graphqlApi"]
+ appsync.create_data_source(apiId=api["apiId"], name="ds", type="AMAZON_DYNAMODB",
+ dynamodbConfig={"tableName": "gql-404", "awsRegion": "us-east-1"})
+ appsync.create_resolver(apiId=api["apiId"], typeName="Query", fieldName="getItem", dataSourceName="ds")
+
+ req = urllib.request.Request(f"http://localhost:4566/v1/apis/{api['apiId']}/graphql",
+ data=_json.dumps({"query": 'query { getItem(id: "ghost") { id } }'}).encode(),
+ headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req) as r:
+ resp = _json.loads(r.read())
+ assert resp["data"]["getItem"] is None
+
+
+def test_appsync_graphql_nonexistent_api():
+ """Query against a non-existent API returns 404."""
+ import urllib.request, json as _json
+ req = urllib.request.Request("http://localhost:4566/v1/apis/fake-api-id/graphql",
+ data=_json.dumps({"query": "{ getItem(id: \"1\") { id } }"}).encode(),
+ headers={"Content-Type": "application/json"})
+ try:
+ urllib.request.urlopen(req)
+ assert False, "Should have failed"
+ except urllib.error.HTTPError as e:
+ assert e.code == 404
+
+
+def test_appsync_graphql_empty_query():
+ """Empty query returns 400."""
+ import urllib.request, json as _json
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="gql-empty", authenticationType="API_KEY")["graphqlApi"]
+
+ req = urllib.request.Request(f"http://localhost:4566/v1/apis/{api['apiId']}/graphql",
+ data=_json.dumps({"query": ""}).encode(),
+ headers={"Content-Type": "application/json"})
+ try:
+ urllib.request.urlopen(req)
+ assert False, "Should have failed"
+ except urllib.error.HTTPError as e:
+ assert e.code == 400