Skip to content

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

Fix/edge cases v1.2.7 (#276)

Nahuel Nucera5a65ea609046
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f17f0428..03310646 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,39 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.2.7] — 2026-04-12
+
+### Added
+- **EC2 CreateDefaultVpc** — new action creates a default VPC with all associated resources (3 default subnets, internet gateway, route table, network ACL, security group), matching real AWS behavior. Returns `DefaultVpcAlreadyExists` if one already exists. Reported by @staranto
+- **DynamoDB ExecuteStatement (PartiQL)** — supports `SELECT`, `INSERT`, `UPDATE`, `DELETE` PartiQL statements with `?` parameter binding. Enables IntelliJ database integration and other PartiQL-based tooling. Reported by @mspiller
+- **SNS FIFO topic support** — `.fifo` naming validation, `MessageGroupId`/`MessageDeduplicationId` enforcement, 5-minute deduplication window, sequence numbers, content-based deduplication, FIFO SQS subscription validation, `PublishBatch` FIFO support, thread-safe dedup cache. Contributed by @yskarparis (#279)
+
+### Fixed
+- **Lambda UpdateFunctionConfiguration Layers** — attaching layers via `update-function-configuration` no longer throws `'str' object has no attribute 'get'`. Layer ARN strings are now normalized to `{"Arn": ..., "CodeSize": 0}` dicts, matching the `create-function` path. Reported by @Vagator-Prostovich
+- **EC2 default VPC network ACL** — the default VPC's network ACL (`acl-00000001`) was referenced but never initialized, causing `DescribeNetworkAcls` to omit it. Now created at startup with standard allow/deny entries.
+- **S3 GetObject by VersionId** — requesting a specific version now returns the correct object data. Previously always returned the latest version, ignoring the `versionId` parameter.
+- **S3 delete markers in ListObjectVersions** — deleting an object in a versioned bucket now inserts a proper delete marker. `ListObjectVersions` returns `DeleteMarker` elements. Previously delete markers were missing entirely.
+- **S3 reset clears version history** — `/_ministack/reset` now clears `_object_versions` store. Previously versioned objects accumulated across resets.
+- **Lambda Invoke event payload** — handler event no longer contains an internal `_request_id` field. Previously leaked into the event dict, breaking handlers that validate input shape.
+- **Lambda PublishVersion ARN** — `FunctionArn` in the response now includes the version qualifier (e.g. `:1`). Previously returned the unqualified function ARN.
+- **DynamoDB BatchWriteItem on nonexistent table** — returns `ResourceNotFoundException` instead of silently placing items into `UnprocessedItems`.
+- **WAFv2 DeleteWebACL LockToken** — now enforces `LockToken` validation, returning `WAFOptimisticLockException` for stale tokens. `UpdateWebACL` already enforced this; `DeleteWebACL` was missing the check.
+- **Step Functions duplicate execution name** — `StartExecution` with a name already in use returns `ExecutionAlreadyExists`. Previously silently created a second execution.
+- **Step Functions Fail state error/cause** — `DescribeExecution` now includes `error` and `cause` fields when execution fails via a Fail state. Previously returned `null` for both.
+- **API Gateway v2 CreateApi Description** — `Description` field is now stored and returned. Previously silently dropped.
+- **API Gateway v1 CreateResource duplicate** — rejects duplicate `pathPart` under the same parent with `ConflictException`. Previously silently created duplicates.
+- **CloudWatch DeleteDashboards nonexistent** — returns `DashboardNotFoundError` for nonexistent dashboards. Previously silently succeeded.
+- **RDS DescribeDBInstances error code** — returns `DBInstanceNotFoundFault` (with `Fault` suffix) matching real AWS. Previously returned `DBInstanceNotFound`.
+- **SQS CreateQueue attribute mismatch** — creating a queue with the same name but different attributes returns `QueueNameExists`. Previously silently returned the existing queue URL.
+- **EC2 TagSpecifications on create operations** — `CreateVpc`, `CreateSubnet`, `CreateSecurityGroup`, `CreateKeyPair`, `CreateInternetGateway`, `CreateRouteTable`, `CreateNatGateway`, `CreateNetworkAcl` now process `TagSpecifications` and persist tags. Previously silently ignored.
+- **EC2 DeleteVpc dependency check** — returns `DependencyViolation` when subnets, non-default security groups, or internet gateways are still attached. Previously silently deleted the VPC.
+- **EC2 delete default security group blocked** — returns `CannotDelete` when attempting to delete a VPC's default security group. Previously silently deleted it.
+- **EC2 RunInstances MinCount > MaxCount** — returns `InvalidParameterCombination` when `MinCount` exceeds `MaxCount`. Previously silently launched instances.
+- **EC2 Describe tag sets** — `DescribeRouteTables`, `DescribeVolumes`, `DescribeSnapshots`, `DescribeNatGateways` now read tags from the `_tags` store. Previously returned hardcoded empty `<tagSet/>`.
+- **ECS DescribeTaskDefinition tags** — always returns tags in the response. Previously only returned tags when `include=["TAGS"]` was explicitly passed.
+
+---
+
## [1.2.6] — 2026-04-12
### Fixed
diff --git a/README.md b/README.md
index 089161e9..a96b388c 100644
--- a/README.md
+++ b/README.md
@@ -73,14 +73,34 @@ curl http://localhost:4566/_ministack/health
# Reset all state — wipe every service back to empty (useful between test runs)
curl -X POST http://localhost:4566/_ministack/reset
-# Runtime config — change settings without restart
+# Runtime config — change service-level settings without restart
curl -X POST http://localhost:4566/_ministack/config \
-H "Content-Type: application/json" \
- -d '{"MINISTACK_ACCOUNT_ID": "123456789012"}'
+ -d '{"lambda_svc.LAMBDA_EXECUTOR": "docker"}'
```
The reset endpoint is especially useful in CI pipelines and test suites — call it in `setUp`/`beforeEach` to get a clean environment for every test without restarting the container.
+The config endpoint supports these keys:
+
+| Key | Description |
+|-----|-------------|
+| `lambda_svc.LAMBDA_EXECUTOR` | Lambda execution mode (`local` or `docker`) |
+| `athena.ATHENA_ENGINE` | Athena query engine (`duckdb` or `mock`) |
+| `athena.ATHENA_DATA_DIR` | Directory for Athena DuckDB data files |
+| `stepfunctions._sfn_mock_config` | SFN mock config (AWS SFN Local compatible) |
+
+To set region or account ID, use environment variables at startup:
+
+```bash
+docker run -p 4566:4566 \
+ -e MINISTACK_REGION=eu-west-1 \
+ -e MINISTACK_ACCOUNT_ID=123456789012 \
+ ministackorg/ministack
+```
+
+Or use the multi-tenancy feature — a 12-digit access key automatically becomes the account ID (see [Multi-Tenancy](#multi-tenancy) below).
+
Also compatible with LocalStack's health endpoint:
```bash
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index acb33ee0..93996da4 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -65,7 +65,7 @@ def run():
"function_name": init.get("function_name", ""),
"memory_limit_in_mb": init.get("memory", 128),
"invoked_function_arn": init.get("arn", ""),
- "aws_request_id": event.get("_request_id", ""),
+ "aws_request_id": event.pop("_request_id", ""),
})()
try:
result = handler_fn(event, context)
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index cdf8091a..08eee053 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -440,6 +440,7 @@ def _create_api(data):
"disableSchemaValidation": data.get("disableSchemaValidation", False),
"disableExecuteApiEndpoint": data.get("disableExecuteApiEndpoint", False),
"version": data.get("version", ""),
+ "description": data.get("description", ""),
}
if data.get("corsConfiguration"):
api["corsConfiguration"] = data["corsConfiguration"]
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index a3ab1776..8c521be6 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -836,6 +836,11 @@ def _create_resource(api_id, parent_id, data):
if parent_id not in _resources.get(api_id, {}):
return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
path_part = data.get("pathPart", "")
+ # Check for duplicate pathPart under same parent
+ for r in _resources.get(api_id, {}).values():
+ if r.get("parentId") == parent_id and r.get("pathPart") == path_part:
+ return _v1_error("ConflictException",
+ f"Another resource with the same parent already has this name: {path_part}", 409)
resource_id = _new_id()[:8]
resource = {
"id": resource_id,
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 1dca49c0..a80daaf2 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -1291,6 +1291,12 @@ def _delete_dashboards(params, cbor_data, is_cbor, is_json=False):
names.append(_p(params, f"DashboardNames.member.{i}"))
i += 1
+ missing = [n for n in names if n not in _dashboards]
+ if missing:
+ return _error("DashboardNotFoundError",
+ f"Dashboard {', '.join(missing)} does not exist",
+ use_json=is_json, use_cbor=is_cbor)
+
for n in names:
_dashboards.pop(n, None)
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 5cda9746..2193f0a4 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -5,7 +5,8 @@ Supports: CreateTable, DeleteTable, DescribeTable, ListTables, UpdateTable,
BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems,
DescribeTimeToLive, UpdateTimeToLive,
DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints,
- TagResource, UntagResource, ListTagsOfResource.
+ TagResource, UntagResource, ListTagsOfResource,
+ ExecuteStatement (PartiQL: SELECT, INSERT, UPDATE, DELETE).
Uses X-Amz-Target header for action routing (JSON API).
"""
@@ -195,6 +196,7 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que
"TagResource": _tag_resource,
"UntagResource": _untag_resource,
"ListTagsOfResource": _list_tags,
+ "ExecuteStatement": _execute_statement,
}
handler = handlers.get(action)
@@ -653,6 +655,364 @@ def _scan(data):
return json_response(result)
+# ---------------------------------------------------------------------------
+# PartiQL — ExecuteStatement
+# ---------------------------------------------------------------------------
+
+def _execute_statement(data):
+ statement = data.get("Statement", "")
+ parameters = data.get("Parameters", [])
+
+ if not statement or not statement.strip():
+ return error_response_json("ValidationException", "Statement must not be empty", 400)
+
+ try:
+ parsed = _parse_partiql(statement, parameters)
+ except ValueError as e:
+ return error_response_json("ValidationException", str(e), 400)
+
+ op = parsed["op"]
+ table_name = parsed["table"]
+ table = _tables.get(table_name)
+ if not table:
+ return error_response_json("ResourceNotFoundException",
+ f"Requested resource not found: Table: {table_name} not found", 400)
+
+ if op == "SELECT":
+ return _partiql_select(table, parsed)
+ elif op == "INSERT":
+ return _partiql_insert(table, parsed)
+ elif op == "UPDATE":
+ return _partiql_update(table, parsed)
+ elif op == "DELETE":
+ return _partiql_delete(table, parsed)
+ else:
+ return error_response_json("ValidationException", f"Unsupported PartiQL operation: {op}", 400)
+
+
+def _partiql_select(table, parsed):
+ all_items = []
+ for pk in sorted(table["items"].keys()):
+ for sk in sorted(table["items"][pk].keys()):
+ all_items.append(table["items"][pk][sk])
+
+ if parsed.get("where_fn"):
+ filtered = [it for it in all_items if parsed["where_fn"](it)]
+ else:
+ filtered = all_items
+
+ projections = parsed.get("projections")
+ if projections:
+ projected = []
+ for it in filtered:
+ proj = {}
+ for attr in projections:
+ if attr in it:
+ proj[attr] = it[attr]
+ projected.append(proj)
+ filtered = projected
+
+ return json_response({"Items": filtered})
+
+
+def _partiql_insert(table, parsed):
+ item = parsed.get("item", {})
+ if not item:
+ return error_response_json("ValidationException", "INSERT requires a value list", 400)
+ pk_val = _extract_key_val(item.get(table["pk_name"]))
+ sk_val = _extract_key_val(item.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"
+ if not pk_val:
+ return error_response_json("ValidationException",
+ "Missing partition key in INSERT", 400)
+ # DynamoDB PartiQL INSERT fails on duplicate key
+ if pk_val in table["items"] and sk_val in table["items"][pk_val]:
+ return error_response_json("ConditionalCheckFailedException",
+ "Duplicate primary key exists in table", 400)
+ table["items"][pk_val][sk_val] = item
+ return json_response({})
+
+
+def _partiql_update(table, parsed):
+ where_fn = parsed.get("where_fn")
+ set_attrs = parsed.get("set_attrs", {})
+ if not where_fn or not set_attrs:
+ return error_response_json("ValidationException",
+ "UPDATE requires SET and WHERE clauses", 400)
+ updated = False
+ for pk in list(table["items"].keys()):
+ for sk in list(table["items"][pk].keys()):
+ it = table["items"][pk][sk]
+ if where_fn(it):
+ for attr, val in set_attrs.items():
+ it[attr] = val
+ updated = True
+ if updated:
+ return json_response({})
+
+
+def _partiql_delete(table, parsed):
+ where_fn = parsed.get("where_fn")
+ if not where_fn:
+ return error_response_json("ValidationException",
+ "DELETE requires a WHERE clause", 400)
+ to_delete = []
+ for pk in list(table["items"].keys()):
+ for sk in list(table["items"][pk].keys()):
+ it = table["items"][pk][sk]
+ if where_fn(it):
+ to_delete.append((pk, sk))
+ for pk, sk in to_delete:
+ del table["items"][pk][sk]
+ if not table["items"][pk]:
+ del table["items"][pk]
+ if to_delete:
+ return json_response({})
+
+
+def _parse_partiql(statement, parameters):
+ """Minimal PartiQL parser for DynamoDB statements."""
+ s = statement.strip().rstrip(";").strip()
+ upper = s.upper()
+
+ if upper.startswith("SELECT"):
+ return _parse_partiql_select(s, parameters)
+ elif upper.startswith("INSERT"):
+ return _parse_partiql_insert(s, parameters)
+ elif upper.startswith("UPDATE"):
+ return _parse_partiql_update(s, parameters)
+ elif upper.startswith("DELETE"):
+ return _parse_partiql_delete(s, parameters)
+ else:
+ raise ValueError(f"Unsupported PartiQL statement: {s[:20]}")
+
+
+def _parse_partiql_select(s, parameters):
+ import re
+ # SELECT <projections> FROM <table> [WHERE <condition>]
+ m = re.match(
+ r'SELECT\s+(.*?)\s+FROM\s+"?([A-Za-z0-9_.\-]+)"?(?:\s+WHERE\s+(.+))?$',
+ s, re.IGNORECASE | re.DOTALL,
+ )
+ if not m:
+ raise ValueError(f"Could not parse SELECT statement: {s}")
+
+ proj_str = m.group(1).strip()
+ table_name = m.group(2).strip()
+ where_str = m.group(3)
+
+ projections = None
+ if proj_str != "*":
+ projections = [p.strip().strip('"') for p in proj_str.split(",")]
+
+ where_fn = _build_partiql_where(where_str, parameters) if where_str else None
+
+ return {"op": "SELECT", "table": table_name, "projections": projections, "where_fn": where_fn}
+
+
+def _parse_partiql_insert(s, parameters):
+ import re
+ # INSERT INTO <table> VALUE { ... }
+ m = re.match(
+ r"INSERT\s+INTO\s+\"?([A-Za-z0-9_.\-]+)\"?\s+VALUE\s+(.+)$",
+ s, re.IGNORECASE | re.DOTALL,
+ )
+ if not m:
+ raise ValueError(f"Could not parse INSERT statement: {s}")
+
+ table_name = m.group(1).strip()
+ value_str = m.group(2).strip()
+ item = _parse_partiql_value(value_str, parameters)
+ if not isinstance(item, dict) or not all(isinstance(v, dict) for v in item.values()):
+ raise ValueError("INSERT VALUE must be a map of DynamoDB-typed attributes")
+ return {"op": "INSERT", "table": table_name, "item": item}
+
+
+def _parse_partiql_update(s, parameters):
+ import re
+ # UPDATE <table> SET <attr>=<val>[,...] WHERE <condition>
+ m = re.match(
+ r"UPDATE\s+\"?([A-Za-z0-9_.\-]+)\"?\s+SET\s+(.+?)\s+WHERE\s+(.+)$",
+ s, re.IGNORECASE | re.DOTALL,
+ )
+ if not m:
+ raise ValueError(f"Could not parse UPDATE statement: {s}")
+
+ table_name = m.group(1).strip()
+ set_str = m.group(2).strip()
+ where_str = m.group(3).strip()
+
+ # Parse SET assignments
+ set_attrs = {}
+ param_idx = [0]
+ for assignment in _split_top_level(set_str, ','):
+ parts = assignment.split("=", 1)
+ if len(parts) != 2:
+ raise ValueError(f"Invalid SET assignment: {assignment}")
+ attr = parts[0].strip().strip('"')
+ val_str = parts[1].strip()
+ set_attrs[attr] = _parse_partiql_literal(val_str, parameters, param_idx)
+
+ where_fn = _build_partiql_where(where_str, parameters, param_idx)
+ return {"op": "UPDATE", "table": table_name, "set_attrs": set_attrs, "where_fn": where_fn}
+
+
+def _parse_partiql_delete(s, parameters):
+ import re
+ # DELETE FROM <table> WHERE <condition>
+ m = re.match(
+ r"DELETE\s+FROM\s+\"?([A-Za-z0-9_.\-]+)\"?\s+WHERE\s+(.+)$",
+ s, re.IGNORECASE | re.DOTALL,
+ )
+ if not m:
+ raise ValueError(f"Could not parse DELETE statement: {s}")
+
+ table_name = m.group(1).strip()
+ where_str = m.group(2).strip()
+ where_fn = _build_partiql_where(where_str, parameters)
+ return {"op": "DELETE", "table": table_name, "where_fn": where_fn}
+
+
+def _build_partiql_where(where_str, parameters, param_idx=None):
+ """Build a predicate function from a PartiQL WHERE clause."""
+ if not where_str or not where_str.strip():
+ return None
+ if param_idx is None:
+ param_idx = [0]
+
+ # Parse simple conditions: attr op value [AND attr op value ...]
+ conditions = _parse_partiql_conditions(where_str, parameters, param_idx)
+
+ def where_fn(item):
+ for attr, op, val in conditions:
+ item_val = item.get(attr)
+ if not _compare_ddb(item_val, op, val):
+ return False
+ return True
+
+ return where_fn
+
+
+def _parse_partiql_conditions(where_str, parameters, param_idx):
+ """Parse WHERE conditions joined by AND. Returns list of (attr, op, ddb_value)."""
+ import re
+ conditions = []
+ # Split on AND (case-insensitive, word boundary)
+ parts = re.split(r'\s+AND\s+', where_str, flags=re.IGNORECASE)
+ for part in parts:
+ part = part.strip()
+ m = re.match(r'"?([A-Za-z0-9_.\-]+)"?\s*(=|<>|!=|<=|>=|<|>)\s*(.+)$', part)
+ if not m:
+ raise ValueError(f"Could not parse WHERE condition: {part}")
+ attr = m.group(1)
+ op = m.group(2)
+ if op == '!=':
+ op = '<>'
+ val_str = m.group(3).strip()
+ val = _parse_partiql_literal(val_str, parameters, param_idx)
+ conditions.append((attr, op, val))
+ return conditions
+
+
+def _parse_partiql_literal(val_str, parameters, param_idx=None):
+ """Parse a PartiQL literal or ? parameter reference into a DynamoDB typed value."""
+ if param_idx is None:
+ param_idx = [0]
+ val_str = val_str.strip()
+
+ if val_str == "?":
+ if param_idx[0] >= len(parameters):
+ raise ValueError("Not enough parameters for ? placeholders")
+ val = parameters[param_idx[0]]
+ param_idx[0] += 1
+ return val
+
+ # String literal
+ if (val_str.startswith("'") and val_str.endswith("'")) or \
+ (val_str.startswith('"') and val_str.endswith('"')):
+ return {"S": val_str[1:-1]}
+
+ # Boolean
+ if val_str.upper() == "TRUE":
+ return {"BOOL": True}
+ if val_str.upper() == "FALSE":
+ return {"BOOL": False}
+
+ # NULL
+ if val_str.upper() == "NULL":
+ return {"NULL": True}
+
+ # Number
+ try:
+ Decimal(val_str)
+ return {"N": val_str}
+ except (InvalidOperation, ValueError):
+ pass
+
+ raise ValueError(f"Cannot parse PartiQL value: {val_str}")
+
+
+def _parse_partiql_value(val_str, parameters, param_idx=None):
+ """Parse a PartiQL VALUE map like {'attr': val, ...} into a DynamoDB item."""
+ if param_idx is None:
+ param_idx = [0]
+ val_str = val_str.strip()
+
+ if val_str == "?":
+ if param_idx[0] >= len(parameters):
+ raise ValueError("Not enough parameters for ? placeholders")
+ val = parameters[param_idx[0]]
+ param_idx[0] += 1
+ return val
+
+ # Parse DynamoDB JSON-style map: { 'key' : value, ... }
+ if not val_str.startswith("{") or not val_str.endswith("}"):
+ raise ValueError(f"Expected a map value, got: {val_str}")
+
+ inner = val_str[1:-1].strip()
+ result = {}
+ for pair in _split_top_level(inner, ','):
+ pair = pair.strip()
+ if not pair:
+ continue
+ kv = pair.split(":", 1)
+ if len(kv) != 2:
+ raise ValueError(f"Invalid key-value pair: {pair}")
+ key = kv[0].strip().strip("'\"")
+ val = _parse_partiql_literal(kv[1].strip(), parameters, param_idx)
+ result[key] = val
+ return result
+
+
+def _split_top_level(s, delimiter):
+ """Split string by delimiter, respecting nested braces/parens/quotes."""
+ parts = []
+ depth = 0
+ current = []
+ in_str = None
+ for ch in s:
+ if in_str:
+ current.append(ch)
+ if ch == in_str:
+ in_str = None
+ elif ch in ("'", '"'):
+ in_str = ch
+ current.append(ch)
+ elif ch in ('(', '{', '['):
+ depth += 1
+ current.append(ch)
+ elif ch in (')', '}', ']'):
+ depth -= 1
+ current.append(ch)
+ elif ch == delimiter and depth == 0:
+ parts.append("".join(current))
+ current = []
+ else:
+ current.append(ch)
+ if current:
+ parts.append("".join(current))
+ return parts
+
+
# ---------------------------------------------------------------------------
# Batch operations
# ---------------------------------------------------------------------------
@@ -663,8 +1023,11 @@ def _batch_write_item(data):
for table_name, requests in request_items.items():
table = _tables.get(table_name)
if not table:
- unprocessed[table_name] = requests
- continue
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"Requested resource not found",
+ 400,
+ )
for req in requests:
if "PutRequest" in req:
item = req["PutRequest"]["Item"]
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index a156c78f..89115e38 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -11,7 +11,7 @@ Supports:
AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress
Key Pairs: CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair
VPC / Subnets: DescribeVpcs, DescribeSubnets, DescribeAvailabilityZones
- CreateVpc, DeleteVpc, CreateSubnet, DeleteSubnet
+ CreateVpc, CreateDefaultVpc, DeleteVpc, CreateSubnet, DeleteSubnet
CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways,
AttachInternetGateway, DetachInternetGateway
Elastic IPs: AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress,
@@ -217,6 +217,17 @@ def _init_defaults():
"Ipv6Ranges": [], "PrefixListIds": [], "UserIdGroupPairs": []},
],
}
+ if _DEFAULT_ACL_ID not in _network_acls:
+ _network_acls[_DEFAULT_ACL_ID] = {
+ "NetworkAclId": _DEFAULT_ACL_ID, "VpcId": _DEFAULT_VPC_ID, "IsDefault": True,
+ "Entries": [
+ {"RuleNumber": 100, "Protocol": "-1", "RuleAction": "allow", "Egress": False, "CidrBlock": "0.0.0.0/0"},
+ {"RuleNumber": 32767, "Protocol": "-1", "RuleAction": "deny", "Egress": False, "CidrBlock": "0.0.0.0/0"},
+ {"RuleNumber": 100, "Protocol": "-1", "RuleAction": "allow", "Egress": True, "CidrBlock": "0.0.0.0/0"},
+ {"RuleNumber": 32767, "Protocol": "-1", "RuleAction": "deny", "Egress": True, "CidrBlock": "0.0.0.0/0"},
+ ],
+ "Associations": [], "Tags": [], "OwnerId": get_account_id(),
+ }
if _DEFAULT_IGW_ID not in _internet_gateways:
_internet_gateways[_DEFAULT_IGW_ID] = {
"InternetGatewayId": _DEFAULT_IGW_ID,
@@ -271,6 +282,10 @@ def _run_instances(p):
instance_type = _p(p, "InstanceType") or "t2.micro"
min_count = int(_p(p, "MinCount") or "1")
max_count = int(_p(p, "MaxCount") or "1")
+ if min_count > max_count:
+ return _error("InvalidParameterCombination",
+ f"Value ({min_count}) for parameter MinCount is not valid. "
+ f"MinCount must not exceed MaxCount.", 400)
key_name = _p(p, "KeyName") or ""
subnet_id = _p(p, "SubnetId") or _DEFAULT_SUBNET_ID
user_data = _p(p, "UserData") or ""
@@ -530,6 +545,7 @@ def _create_security_group(p):
"Ipv6Ranges": [], "PrefixListIds": [], "UserIdGroupPairs": []},
],
}
+ _parse_tag_specs(p, "security-group", sg_id)
return _xml(200, "CreateSecurityGroupResponse",
f"<return>true</return><groupId>{sg_id}</groupId>")
@@ -537,6 +553,10 @@ def _create_security_group(p):
def _delete_security_group(p):
sg_id = _p(p, "GroupId")
if sg_id and sg_id in _security_groups:
+ # Block deletion of default security group
+ if _security_groups[sg_id]["GroupName"] == "default":
+ return _error("CannotDelete",
+ f"the specified group: \"{sg_id}\" name: \"default\" cannot be deleted by a user", 400)
del _security_groups[sg_id]
elif sg_id:
return _error("InvalidGroup.NotFound",
@@ -637,6 +657,7 @@ def _create_key_pair(p):
"KeyFingerprint": fingerprint,
"KeyPairId": f"key-{new_uuid().replace('-','')[:17]}",
}
+ _parse_tag_specs(p, "key-pair", _key_pairs[name]['KeyPairId'])
return _xml(200, "CreateKeyPairResponse", f"""
<keyName>{name}</keyName>
<keyFingerprint>{fingerprint}</keyFingerprint>
@@ -777,6 +798,7 @@ def _create_vpc(p):
"OwnerId": get_account_id(), "DefaultNetworkAclId": acl_id,
"DefaultSecurityGroupId": sg_id, "MainRouteTableId": rtb_id,
}
+ _parse_tag_specs(p, "vpc", vpc_id)
return _xml(200, "CreateVpcResponse", _vpc_fields_xml(_vpcs[vpc_id], tag="vpc"))
@@ -784,10 +806,102 @@ def _delete_vpc(p):
vpc_id = _p(p, "VpcId")
if vpc_id not in _vpcs:
return _error("InvalidVpcID.NotFound", f"The vpc ID '{vpc_id}' does not exist", 400)
+ # Check for attached subnets
+ for s in _subnets.values():
+ if s["VpcId"] == vpc_id:
+ return _error("DependencyViolation",
+ f"The vpc '{vpc_id}' has dependencies and cannot be deleted.", 400)
+ # Check for non-default security groups
+ for sg in _security_groups.values():
+ if sg["VpcId"] == vpc_id and sg["GroupName"] != "default":
+ return _error("DependencyViolation",
+ f"The vpc '{vpc_id}' has dependencies and cannot be deleted.", 400)
+ # Check for attached internet gateways
+ for igw in _internet_gateways.values():
+ for att in igw.get("Attachments", []):
+ if att.get("VpcId") == vpc_id:
+ return _error("DependencyViolation",
+ f"The vpc '{vpc_id}' has dependencies and cannot be deleted.", 400)
+ # Clean up VPC-associated default resources
+ to_del_sgs = [sid for sid, sg in _security_groups.items() if sg["VpcId"] == vpc_id]
+ for sid in to_del_sgs:
+ del _security_groups[sid]
+ to_del_rtb = [rid for rid, r in _route_tables.items() if r["VpcId"] == vpc_id]
+ for rid in to_del_rtb:
+ del _route_tables[rid]
+ to_del_acl = [aid for aid, a in _network_acls.items() if a["VpcId"] == vpc_id]
+ for aid in to_del_acl:
+ del _network_acls[aid]
del _vpcs[vpc_id]
return _xml(200, "DeleteVpcResponse", "<return>true</return>")
+def _create_default_vpc(p):
+ # AWS returns DefaultVpcAlreadyExists if one already exists
+ for vpc in _vpcs.values():
+ if vpc.get("IsDefault"):
+ return _error("DefaultVpcAlreadyExists",
+ "A Default VPC already exists for this account in this region.", 400)
+ cidr = "172.31.0.0/16"
+ vpc_id = _new_vpc_id()
+ acl_id = "acl-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ _network_acls[acl_id] = {
+ "NetworkAclId": acl_id, "VpcId": vpc_id, "IsDefault": True,
+ "Entries": [
+ {"RuleNumber": 100, "Protocol": "-1", "RuleAction": "allow", "Egress": False, "CidrBlock": "0.0.0.0/0"},
+ {"RuleNumber": 32767, "Protocol": "-1", "RuleAction": "deny", "Egress": False, "CidrBlock": "0.0.0.0/0"},
+ {"RuleNumber": 100, "Protocol": "-1", "RuleAction": "allow", "Egress": True, "CidrBlock": "0.0.0.0/0"},
+ {"RuleNumber": 32767, "Protocol": "-1", "RuleAction": "deny", "Egress": True, "CidrBlock": "0.0.0.0/0"},
+ ],
+ "Associations": [], "Tags": [], "OwnerId": get_account_id(),
+ }
+ rtb_id = "rtb-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ rtb_assoc_id = "rtbassoc-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ _route_tables[rtb_id] = {
+ "RouteTableId": rtb_id, "VpcId": vpc_id, "OwnerId": get_account_id(),
+ "Routes": [
+ {"DestinationCidrBlock": cidr, "GatewayId": "local", "State": "active", "Origin": "CreateRouteTable"},
+ ],
+ "Associations": [
+ {"RouteTableAssociationId": rtb_assoc_id, "RouteTableId": rtb_id, "Main": True,
+ "AssociationState": {"State": "associated"}},
+ ],
+ }
+ sg_id = _new_sg_id()
+ _security_groups[sg_id] = {
+ "GroupId": sg_id, "GroupName": "default", "Description": "default VPC security group",
+ "VpcId": vpc_id, "OwnerId": get_account_id(), "IpPermissions": [],
+ "IpPermissionsEgress": [
+ {"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
+ "Ipv6Ranges": [], "PrefixListIds": [], "UserIdGroupPairs": []},
+ ],
+ }
+ igw_id = _new_igw_id()
+ _internet_gateways[igw_id] = {
+ "InternetGatewayId": igw_id, "OwnerId": get_account_id(),
+ "Attachments": [{"VpcId": vpc_id, "State": "available"}],
+ }
+ _vpcs[vpc_id] = {
+ "VpcId": vpc_id, "CidrBlock": cidr, "State": "available", "IsDefault": True,
+ "DhcpOptionsId": "dopt-00000001", "InstanceTenancy": "default",
+ "OwnerId": get_account_id(), "DefaultNetworkAclId": acl_id,
+ "DefaultSecurityGroupId": sg_id, "MainRouteTableId": rtb_id,
+ }
+ # Create default subnets (one per AZ, matching AWS behavior)
+ for i, (sub_cidr, az_suffix) in enumerate([
+ ("172.31.0.0/20", "a"), ("172.31.16.0/20", "b"), ("172.31.32.0/20", "c"),
+ ]):
+ subnet_id = _new_subnet_id()
+ _subnets[subnet_id] = {
+ "SubnetId": subnet_id, "VpcId": vpc_id, "CidrBlock": sub_cidr,
+ "AvailabilityZone": f"{REGION}{az_suffix}",
+ "AvailableIpAddressCount": 4091, "State": "available",
+ "DefaultForAz": True, "MapPublicIpOnLaunch": True,
+ "OwnerId": get_account_id(),
+ }
+ return _xml(200, "CreateDefaultVpcResponse", _vpc_fields_xml(_vpcs[vpc_id], tag="vpc"))
+
+
# ---------------------------------------------------------------------------
# Subnets
# ---------------------------------------------------------------------------
@@ -834,6 +948,7 @@ def _create_subnet(p):
"MapPublicIpOnLaunch": False,
"OwnerId": get_account_id(),
}
+ _parse_tag_specs(p, "subnet", subnet_id)
return _xml(200, "CreateSubnetResponse", _subnet_fields_xml(_subnets[subnet_id], tag="subnet"))
@@ -857,6 +972,7 @@ def _create_internet_gateway(p):
"OwnerId": get_account_id(),
"Attachments": [],
}
+ _parse_tag_specs(p, "internet-gateway", igw_id)
return _xml(200, "CreateInternetGatewayResponse",
_igw_fields_xml(_internet_gateways[igw_id], tag="internetGateway"))
@@ -978,6 +1094,7 @@ def _create_route_table(p):
],
"Associations": [],
}
+ _parse_tag_specs(p, "route-table", rtb_id)
return _xml(200, "CreateRouteTableResponse",
_rtb_fields_xml(_route_tables[rtb_id], tag="routeTable"))
@@ -1621,7 +1738,7 @@ def _volume_inner_xml(vol):
<encrypted>{'true' if vol['Encrypted'] else 'false'}</encrypted>
<multiAttachEnabled>{'true' if vol['MultiAttachEnabled'] else 'false'}</multiAttachEnabled>
<attachmentSet>{attachments}</attachmentSet>
- <tagSet/>"""
+ {_tag_set_xml(vol['VolumeId'])}"""
# ---------------------------------------------------------------------------
@@ -1747,7 +1864,7 @@ def _snapshot_inner_xml(snap):
<description>{_esc(snap['Description'])}</description>
<encrypted>{'true' if snap['Encrypted'] else 'false'}</encrypted>
<storageTier>{snap['StorageTier']}</storageTier>
- <tagSet/>"""
+ {_tag_set_xml(snap['SnapshotId'])}"""
# ---------------------------------------------------------------------------
@@ -1916,7 +2033,7 @@ def _rtb_fields_xml(rtb, tag="item"):
<routeSet>{routes}</routeSet>
<associationSet>{assocs}</associationSet>
<propagatingVgwSet/>
- <tagSet/>
+ {_tag_set_xml(rtb['RouteTableId'])}
</{tag}>"""
@@ -1986,6 +2103,24 @@ def _p(params, key, default=""):
return val
+def _parse_tag_specs(p, resource_type, resource_id):
+ """Parse TagSpecification.N from params and store tags for the given resource."""
+ i = 1
+ while _p(p, f"TagSpecification.{i}.ResourceType"):
+ if _p(p, f"TagSpecification.{i}.ResourceType") == resource_type:
+ tags = []
+ j = 1
+ while _p(p, f"TagSpecification.{i}.Tag.{j}.Key"):
+ tags.append({
+ "Key": _p(p, f"TagSpecification.{i}.Tag.{j}.Key"),
+ "Value": _p(p, f"TagSpecification.{i}.Tag.{j}.Value", ""),
+ })
+ j += 1
+ if tags:
+ _tags[resource_id] = tags
+ i += 1
+
+
def _parse_member_list(params, prefix):
items = []
i = 1
@@ -2187,6 +2322,7 @@ def _create_nat_gateway(params):
_nat_gateways[nat_id] = record
if tags:
_tags[nat_id] = tags
+ _parse_tag_specs(params, "natgateway", nat_id)
inner = f"""<natGateway>
<natGatewayId>{nat_id}</natGatewayId>
<subnetId>{subnet_id}</subnetId>
@@ -2221,7 +2357,7 @@ def _describe_nat_gateways(params):
<connectivityType>{nat['ConnectivityType']}</connectivityType>
<createTime>{nat['CreateTime']}</createTime>
<natGatewayAddressSet/>
- <tagSet/>
+ {_tag_set_xml(nat['NatGatewayId'])}
</item>"""
return _xml(200, "DescribeNatGatewaysResponse",
f"<natGatewaySet>{items}</natGatewaySet>")
@@ -2258,6 +2394,7 @@ def _create_network_acl(params):
_network_acls[acl_id] = record
if tags:
_tags[acl_id] = tags
+ _parse_tag_specs(params, "network-acl", acl_id)
inner = f"""<networkAcl>
<networkAclId>{acl_id}</networkAclId>
<vpcId>{vpc_id}</vpcId>
@@ -3796,6 +3933,7 @@ _ACTION_MAP = {
"ImportKeyPair": _import_key_pair,
"DescribeVpcs": _describe_vpcs,
"CreateVpc": _create_vpc,
+ "CreateDefaultVpc": _create_default_vpc,
"DeleteVpc": _delete_vpc,
"DescribeSubnets": _describe_subnets,
"CreateSubnet": _create_subnet,
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index 7e27bed8..3d4d5c90 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -441,12 +441,8 @@ def _describe_task_definition(data):
if not td:
return error_response_json("ClientException",
f"Unable to describe task definition: {td_ref}", 400)
- include = set(data.get("include", [])) if isinstance(data, dict) else set()
resp = {"taskDefinition": td}
- if "TAGS" in include:
- resp["tags"] = _tags.get(td["taskDefinitionArn"], [])
- else:
- resp["tags"] = []
+ resp["tags"] = _tags.get(td["taskDefinitionArn"], [])
return json_response(resp)
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 759af554..177dda1d 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -906,7 +906,16 @@ def _update_config(name: str, data: dict):
"FileSystemConfigs",
):
if key in data:
- config[key] = data[key]
+ if key == "Layers":
+ layers_cfg = []
+ for layer in data["Layers"]:
+ if isinstance(layer, str):
+ layers_cfg.append({"Arn": layer, "CodeSize": 0})
+ elif isinstance(layer, dict):
+ layers_cfg.append(layer)
+ config["Layers"] = layers_cfg
+ else:
+ config[key] = data[key]
if "ImageConfig" in data:
config["ImageConfigResponse"] = {"ImageConfig": data["ImageConfig"]}
config["LastModified"] = _now_iso()
@@ -1832,7 +1841,7 @@ def _publish_version(name: str, data: dict):
ver_config = copy.deepcopy(func["config"])
ver_config["Version"] = str(ver_num)
- ver_config["FunctionArn"] = _func_arn(name)
+ ver_config["FunctionArn"] = f"{_func_arn(name)}:{ver_num}"
ver_config["RevisionId"] = new_uuid()
if data.get("Description"):
ver_config["Description"] = data["Description"]
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index bf3847e1..6dc7e9ee 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -319,7 +319,7 @@ def _delete_db_instance(p):
db_id = _p(p, "DBInstanceIdentifier")
instance = _instances.get(db_id)
if not instance:
- return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)
+ return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)
if instance.get("DeletionProtection"):
return _error("InvalidParameterCombination",
@@ -352,7 +352,7 @@ def _describe_db_instances(p):
if db_id:
instance = _instances.get(db_id)
if not instance:
- return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)
+ return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)
instances = [instance]
else:
instances = list(_instances.values())
@@ -369,7 +369,7 @@ def _modify_db_instance(p):
db_id = _p(p, "DBInstanceIdentifier")
instance = _instances.get(db_id)
if not instance:
- return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)
+ return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)
apply_immediately = _p(p, "ApplyImmediately") == "true"
@@ -435,7 +435,7 @@ def _start_db_instance(p):
db_id = _p(p, "DBInstanceIdentifier")
instance = _instances.get(db_id)
if not instance:
- return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)
+ return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)
instance["DBInstanceStatus"] = "available"
return _single_instance_response("StartDBInstanceResponse", "StartDBInstanceResult", instance)
@@ -444,7 +444,7 @@ def _stop_db_instance(p):
db_id = _p(p, "DBInstanceIdentifier")
instance = _instances.get(db_id)
if not instance:
- return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)
+ return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)
instance["DBInstanceStatus"] = "stopped"
return _single_instance_response("StopDBInstanceResponse", "StopDBInstanceResult", instance)
@@ -453,7 +453,7 @@ def _reboot_db_instance(p):
db_id = _p(p, "DBInstanceIdentifier")
instance = _instances.get(db_id)
if not instance:
- return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)
+ return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)
instance["DBInstanceStatus"] = "available"
return _single_instance_response("RebootDBInstanceResponse", "RebootDBInstanceResult", instance)
@@ -468,7 +468,7 @@ def _create_read_replica(p):
source = _instances.get(source_id)
if not source:
- return _error("DBInstanceNotFound", f"DBInstance {source_id} not found.", 404)
+ return _error("DBInstanceNotFoundFault", f"DBInstance {source_id} not found.", 404)
if replica_id in _instances:
return _error("DBInstanceAlreadyExistsFault", f"DBInstance {replica_id} already exists.", 400)
@@ -783,7 +783,7 @@ def _create_db_snapshot(p):
instance = _instances.get(db_id)
if not instance:
- return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)
+ return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)
snap = _create_snapshot_internal(snap_id, instance)
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 15367c73..a070720e 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -390,7 +390,7 @@ def _dispatch(
return _get_object_retention(bucket, key)
if "legal-hold" in query_params:
return _get_object_legal_hold(bucket, key)
- return _get_object(bucket, key, headers)
+ return _get_object(bucket, key, headers, query_params)
if method == "PUT":
if "partNumber" in query_params and "uploadId" in query_params:
@@ -1036,9 +1036,13 @@ def _list_object_versions(bucket_name: str, query_params: dict):
SubElement(root, "VersionIdMarker").text = version_id_marker
SubElement(root, "MaxKeys").text = str(max_keys)
- keys = sorted(
- k for k in bucket["objects"] if k.startswith(prefix) and k > key_marker
- )
+ # Collect all keys: from objects AND from version history (deleted objects)
+ all_keys = set(k for k in bucket["objects"] if k.startswith(prefix) and k > key_marker)
+ for (bn, k) in _object_versions:
+ if bn == bucket_name and k.startswith(prefix) and k > key_marker:
+ all_keys.add(k)
+ keys = sorted(all_keys)
+
is_truncated = False
SubElement(root, "IsTruncated").text = "false"
@@ -1055,21 +1059,33 @@ def _list_object_versions(bucket_name: str, query_params: dict):
if count >= max_keys:
is_truncated = True
break
- ver = SubElement(root, "Version")
- SubElement(ver, "Key").text = k
- SubElement(ver, "VersionId").text = v["version_id"]
- SubElement(ver, "IsLatest").text = "true" if v["is_latest"] else "false"
- SubElement(ver, "LastModified").text = v["last_modified"]
- SubElement(ver, "ETag").text = v["etag"]
- SubElement(ver, "Size").text = str(v["size"])
- SubElement(ver, "StorageClass").text = "STANDARD"
- owner = SubElement(ver, "Owner")
- SubElement(owner, "ID").text = "owner-id"
- SubElement(owner, "DisplayName").text = "ministack"
+ if v.get("is_delete_marker"):
+ dm = SubElement(root, "DeleteMarker")
+ SubElement(dm, "Key").text = k
+ SubElement(dm, "VersionId").text = v["version_id"]
+ SubElement(dm, "IsLatest").text = "true" if v["is_latest"] else "false"
+ SubElement(dm, "LastModified").text = v["last_modified"]
+ owner = SubElement(dm, "Owner")
+ SubElement(owner, "ID").text = "owner-id"
+ SubElement(owner, "DisplayName").text = "ministack"
+ else:
+ ver = SubElement(root, "Version")
+ SubElement(ver, "Key").text = k
+ SubElement(ver, "VersionId").text = v["version_id"]
+ SubElement(ver, "IsLatest").text = "true" if v["is_latest"] else "false"
+ SubElement(ver, "LastModified").text = v["last_modified"]
+ SubElement(ver, "ETag").text = v["etag"]
+ SubElement(ver, "Size").text = str(v["size"])
+ SubElement(ver, "StorageClass").text = "STANDARD"
+ owner = SubElement(ver, "Owner")
+ SubElement(owner, "ID").text = "owner-id"
+ SubElement(owner, "DisplayName").text = "ministack"
count += 1
else:
# No version history — return current object with null version
- obj = bucket["objects"][k]
+ obj = bucket["objects"].get(k)
+ if not obj:
+ continue
ver = SubElement(root, "Version")
SubElement(ver, "Key").text = k
SubElement(ver, "VersionId").text = obj.get("version_id", "null")
@@ -1462,10 +1478,28 @@ def _apply_object_lock_from_headers(bucket_name: str, key: str, headers: dict):
_object_legal_hold[(bucket_name, key)] = lock_legal
-def _get_object(bucket_name: str, key: str, headers: dict):
+def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict = None):
+ query_params = query_params or {}
bucket = _ensure_bucket(bucket_name)
if bucket is None:
return _no_such_bucket(bucket_name)
+
+ version_id = _qp(query_params, "versionId", "")
+ if version_id:
+ vkey = (bucket_name, key)
+ versions = _object_versions.get(vkey, [])
+ for v in versions:
+ if v["version_id"] == version_id:
+ resp_headers = {
+ "Content-Type": "application/octet-stream",
+ "ETag": v["etag"],
+ "Content-Length": str(v["size"]),
+ "Last-Modified": v["last_modified"],
+ "x-amz-version-id": v["version_id"],
+ }
+ return 200, resp_headers, v.get("data", b"")
+ return _error("NoSuchVersion", "The specified version does not exist.", 404, f"/{bucket_name}/{key}")
+
if key not in bucket["objects"]:
return _error(
"NoSuchKey",
@@ -1534,19 +1568,38 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None):
if lock_err:
return lock_err
+ versioning = _bucket_versioning.get(bucket_name, "")
+ if versioning in ("Enabled", "Suspended"):
+ # Add a delete marker instead of removing version history
+ delete_marker_id = new_uuid()
+ vkey = (bucket_name, key)
+ if vkey not in _object_versions:
+ _object_versions[vkey] = []
+ # Mark all previous versions as not latest
+ for v in _object_versions[vkey]:
+ v["is_latest"] = False
+ _object_versions[vkey].append({
+ "version_id": delete_marker_id,
+ "last_modified": now_iso(),
+ "etag": "",
+ "size": 0,
+ "is_latest": True,
+ "is_delete_marker": True,
+ })
+ existed = key in bucket["objects"]
+ bucket["objects"].pop(key, None)
+ if existed:
+ _fire_s3_event_async(bucket_name, key, "s3:ObjectRemoved:Delete")
+ return 204, {"x-amz-delete-marker": "true", "x-amz-version-id": delete_marker_id}, b""
+
existed = key in bucket["objects"]
bucket["objects"].pop(key, None)
_object_tags.pop((bucket_name, key), None)
_object_retention.pop((bucket_name, key), None)
_object_legal_hold.pop((bucket_name, key), None)
- _object_versions.pop((bucket_name, key), None)
if existed:
_fire_s3_event_async(bucket_name, key, "s3:ObjectRemoved:Delete")
-
- versioning = _bucket_versioning.get(bucket_name, "")
- if versioning in ("Enabled", "Suspended"):
- return 204, {"x-amz-delete-marker": "true", "x-amz-version-id": "null"}, b""
return 204, {}, b""
@@ -2904,7 +2957,7 @@ def reset():
global _bucket_versioning, _bucket_encryption, _bucket_lifecycle, _bucket_cors
global _bucket_acl, _bucket_websites, _bucket_logging_config
global _bucket_accelerate_config, _bucket_request_payment_config
- global _object_tags, _multipart_uploads
+ global _object_tags, _multipart_uploads, _object_versions
global \
_bucket_object_lock, \
_bucket_replication, \
@@ -2930,5 +2983,6 @@ def reset():
_bucket_replication,
_object_retention,
_object_legal_hold,
+ _object_versions,
):
d.clear()
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 8da2b49e..257724f4 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -482,6 +482,7 @@ def _set_subscription_attributes(params):
# original MessageId/SequenceNumber without re-delivering to subscribers.
# Reference: https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html
_DEDUP_WINDOW_S = 300
+_fifo_lock = _threading.Lock()
def _is_fifo_topic(topic: dict) -> bool:
@@ -565,24 +566,32 @@ def _publish(params):
return _error("InvalidParameterException", str(exc), 400)
# Prune expired cache entries, then check for duplicate
- _prune_sns_dedup(topic)
- cached = topic.get("dedup_cache", {}).get(dedup_id)
- if cached:
- # Duplicate within the 5-minute window — return cached result
- return _xml(
- 200,
- "PublishResponse",
- f"<PublishResult>"
- f"<MessageId>{cached['message_id']}</MessageId>"
- f"<SequenceNumber>{cached['sequence_number']}</SequenceNumber>"
- f"</PublishResult>",
- )
+ with _fifo_lock:
+ _prune_sns_dedup(topic)
+ cached = topic.get("dedup_cache", {}).get(dedup_id)
+ if cached:
+ # Duplicate within the 5-minute window — return cached result
+ return _xml(
+ 200,
+ "PublishResponse",
+ f"<PublishResult>"
+ f"<MessageId>{cached['message_id']}</MessageId>"
+ f"<SequenceNumber>{cached['sequence_number']}</SequenceNumber>"
+ f"</PublishResult>",
+ )
+
+ # New message: increment sequence counter
+ topic["fifo_seq"] = topic.get("fifo_seq", 0) + 1
+ seq_number = str(topic["fifo_seq"]).zfill(20)
+ msg_id = new_uuid()
- # New message: increment sequence counter
- topic["fifo_seq"] = topic.get("fifo_seq", 0) + 1
- seq_number = str(topic["fifo_seq"]).zfill(20)
+ # Cache the entry for deduplication (300s window)
+ topic.setdefault("dedup_cache", {})[dedup_id] = {
+ "expire": time.time() + _DEDUP_WINDOW_S,
+ "message_id": msg_id,
+ "sequence_number": seq_number,
+ }
- msg_id = new_uuid()
topic["messages"].append({
"id": msg_id,
"message": message,
@@ -595,13 +604,6 @@ def _publish(params):
_fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs,
message_group_id=group_id, message_dedup_id=dedup_id)
- # Cache the entry for deduplication (300s window)
- topic.setdefault("dedup_cache", {})[dedup_id] = {
- "expire": time.time() + _DEDUP_WINDOW_S,
- "message_id": msg_id,
- "sequence_number": seq_number,
- }
-
logger.info("SNS FIFO publish to %s: %s", topic_arn, message[:100])
return _xml(
200,
@@ -701,23 +703,31 @@ def _publish_batch(params):
continue
# Dedup check
- _prune_sns_dedup(topic)
- cached = topic.get("dedup_cache", {}).get(dedup_id)
- if cached:
- successful += (
- "<member>"
- f"<Id>{_xml_escape(eid)}</Id>"
- f"<MessageId>{cached['message_id']}</MessageId>"
- f"<SequenceNumber>{cached['sequence_number']}</SequenceNumber>"
- "</member>"
- )
- continue
+ with _fifo_lock:
+ _prune_sns_dedup(topic)
+ cached = topic.get("dedup_cache", {}).get(dedup_id)
+ if cached:
+ successful += (
+ "<member>"
+ f"<Id>{_xml_escape(eid)}</Id>"
+ f"<MessageId>{cached['message_id']}</MessageId>"
+ f"<SequenceNumber>{cached['sequence_number']}</SequenceNumber>"
+ "</member>"
+ )
+ continue
+
+ # New FIFO message: increment sequence counter
+ topic["fifo_seq"] = topic.get("fifo_seq", 0) + 1
+ seq_number = str(topic["fifo_seq"]).zfill(20)
+ msg_id = new_uuid()
+
+ # Cache for deduplication
+ topic.setdefault("dedup_cache", {})[dedup_id] = {
+ "expire": time.time() + _DEDUP_WINDOW_S,
+ "message_id": msg_id,
+ "sequence_number": seq_number,
+ }
- # New FIFO message: increment sequence counter
- topic["fifo_seq"] = topic.get("fifo_seq", 0) + 1
- seq_number = str(topic["fifo_seq"]).zfill(20)
-
- msg_id = new_uuid()
topic["messages"].append({
"id": msg_id,
"message": message,
@@ -730,13 +740,6 @@ def _publish_batch(params):
_fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs,
message_group_id=group_id, message_dedup_id=dedup_id)
- # Cache for deduplication
- topic.setdefault("dedup_cache", {})[dedup_id] = {
- "expire": time.time() + _DEDUP_WINDOW_S,
- "message_id": msg_id,
- "sequence_number": seq_number,
- }
-
successful += (
"<member>"
f"<Id>{_xml_escape(eid)}</Id>"
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index b4fae2b2..82a82675 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -175,6 +175,13 @@ def _act_create_queue(data: dict, _u: str) -> dict:
url = _queue_url(name)
if url in _queues:
+ # If attrs differ from existing queue, return error
+ if attrs:
+ existing = _queues[url]["attributes"]
+ for k, v in attrs.items():
+ if k in existing and existing[k] != v:
+ raise _Err("QueueNameExists",
+ "A queue already exists with the same name and a different value for attribute " + k)
return {"QueueUrl": url}
ts = str(int(time.time()))
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index a71e8f73..8ba40221 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -351,6 +351,12 @@ def _start_execution(data):
exec_arn = (f"arn:aws:states:{REGION}:{get_account_id()}"
f":execution:{sm['name']}:{name}")
+ # Reject duplicate execution names
+ if exec_arn in _executions:
+ return error_response_json(
+ "ExecutionAlreadyExists",
+ f"Execution already exists: '{exec_arn}'", 400)
+
start_date = now_iso()
input_str = data.get("input", "{}")
@@ -423,6 +429,10 @@ def _describe_execution(data):
"output": execution["output"],
"outputDetails": execution.get("outputDetails", {"included": True}),
}
+ if execution.get("error"):
+ result["error"] = execution["error"]
+ if execution.get("cause"):
+ result["cause"] = execution["cause"]
return json_response(result)
@@ -1082,6 +1092,8 @@ def _run_execution(exec_arn):
def _fail_execution(execution, error, cause):
execution["status"] = "FAILED"
+ execution["error"] = error
+ execution["cause"] = cause
execution["output"] = json.dumps({"Error": error, "Cause": cause})
execution["stopDate"] = now_iso()
_add_event(execution, "ExecutionFailed", {
diff --git a/ministack/services/waf.py b/ministack/services/waf.py
index 99bbde6f..44194fc4 100644
--- a/ministack/services/waf.py
+++ b/ministack/services/waf.py
@@ -171,6 +171,10 @@ def _delete_web_acl(data):
uid = data.get("Id", "")
if uid not in _web_acls:
return _waf_err("WAFNonexistentItemException", f"WebACL {uid} not found")
+ lock_token = data.get("LockToken", "")
+ if lock_token != _web_acls[uid]["LockToken"]:
+ return _waf_err("WAFOptimisticLockException",
+ "The resource you are trying to update has changed. Please retry.")
arn = _web_acls[uid]["ARN"]
del _web_acls[uid]
_waf_tags.pop(arn, None)
diff --git a/pyproject.toml b/pyproject.toml
index ed172e54..e0351af0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.2.6"
+version = "1.2.7"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/conftest.py b/tests/conftest.py
index 897c5e62..50ed2e19 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -35,6 +35,7 @@ _SERIAL_TESTS = {
"tests/test_ministack.py::test_ministack_config_invalid_key_ignored",
"tests/test_sfn.py::test_sfn_mock_config_return",
"tests/test_sfn.py::test_sfn_mock_config_throw",
+ "tests/test_ec2.py::test_ec2_create_default_vpc",
}
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index 05ee9a34..4263876f 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -1278,3 +1278,198 @@ def test_dynamodb_update_to_pay_per_request_zeroes_throughput(ddb):
finally:
ddb.delete_table(TableName=tname)
+
+# ---------------------------------------------------------------------------
+# ExecuteStatement (PartiQL)
+# ---------------------------------------------------------------------------
+
+def test_partiql_select_all(ddb):
+ """SELECT * FROM table — the IntelliJ use case."""
+ tname = "partiql-select-all"
+ try:
+ ddb.delete_table(TableName=tname)
+ except ClientError:
+ pass
+ ddb.create_table(
+ TableName=tname,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "a"}, "val": {"S": "1"}})
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "b"}, "val": {"S": "2"}})
+
+ resp = ddb.execute_statement(Statement=f'SELECT * FROM "{tname}"')
+ assert len(resp["Items"]) == 2
+ pks = sorted(it["pk"]["S"] for it in resp["Items"])
+ assert pks == ["a", "b"]
+
+
+def test_partiql_select_with_where(ddb):
+ """SELECT with WHERE clause and ? parameter binding."""
+ tname = "partiql-select-where"
+ try:
+ ddb.delete_table(TableName=tname)
+ except ClientError:
+ pass
+ ddb.create_table(
+ TableName=tname,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "x"}, "status": {"S": "active"}})
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "y"}, "status": {"S": "inactive"}})
+
+ resp = ddb.execute_statement(
+ Statement=f'SELECT * FROM "{tname}" WHERE pk = ?',
+ Parameters=[{"S": "x"}],
+ )
+ assert len(resp["Items"]) == 1
+ assert resp["Items"][0]["pk"]["S"] == "x"
+
+
+def test_partiql_select_projection(ddb):
+ """SELECT specific columns."""
+ tname = "partiql-select-proj"
+ try:
+ ddb.delete_table(TableName=tname)
+ except ClientError:
+ pass
+ ddb.create_table(
+ TableName=tname,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "k1"}, "a": {"S": "1"}, "b": {"S": "2"}})
+
+ resp = ddb.execute_statement(Statement=f'SELECT pk, a FROM "{tname}"')
+ assert len(resp["Items"]) == 1
+ item = resp["Items"][0]
+ assert "pk" in item
+ assert "a" in item
+ assert "b" not in item
+
+
+def test_partiql_insert(ddb):
+ """INSERT INTO table VALUE {...}."""
+ tname = "partiql-insert"
+ try:
+ ddb.delete_table(TableName=tname)
+ except ClientError:
+ pass
+ ddb.create_table(
+ TableName=tname,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ ddb.execute_statement(
+ Statement=f"INSERT INTO \"{tname}\" VALUE {{'pk': ?, 'data': ?}}",
+ Parameters=[{"S": "ins1"}, {"S": "hello"}],
+ )
+ resp = ddb.get_item(TableName=tname, Key={"pk": {"S": "ins1"}})
+ assert resp["Item"]["data"]["S"] == "hello"
+
+
+def test_partiql_insert_duplicate_rejected(ddb):
+ """INSERT with duplicate key should fail."""
+ tname = "partiql-ins-dup"
+ try:
+ ddb.delete_table(TableName=tname)
+ except ClientError:
+ pass
+ ddb.create_table(
+ TableName=tname,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "dup"}})
+
+ with pytest.raises(ClientError) as exc:
+ ddb.execute_statement(
+ Statement=f"INSERT INTO \"{tname}\" VALUE {{'pk': ?}}",
+ Parameters=[{"S": "dup"}],
+ )
+ assert "ConditionalCheckFailed" in exc.value.response["Error"]["Code"]
+
+
+def test_partiql_update(ddb):
+ """UPDATE table SET attr = val WHERE pk = val."""
+ tname = "partiql-update"
+ try:
+ ddb.delete_table(TableName=tname)
+ except ClientError:
+ pass
+ ddb.create_table(
+ TableName=tname,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "u1"}, "status": {"S": "old"}})
+
+ ddb.execute_statement(
+ Statement=f"UPDATE \"{tname}\" SET status = ? WHERE pk = ?",
+ Parameters=[{"S": "new"}, {"S": "u1"}],
+ )
+ resp = ddb.get_item(TableName=tname, Key={"pk": {"S": "u1"}})
+ assert resp["Item"]["status"]["S"] == "new"
+
+
+def test_partiql_delete(ddb):
+ """DELETE FROM table WHERE pk = val."""
+ tname = "partiql-delete"
+ try:
+ ddb.delete_table(TableName=tname)
+ except ClientError:
+ pass
+ ddb.create_table(
+ TableName=tname,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "d1"}, "val": {"S": "x"}})
+
+ ddb.execute_statement(
+ Statement=f'DELETE FROM "{tname}" WHERE pk = ?',
+ Parameters=[{"S": "d1"}],
+ )
+ resp = ddb.get_item(TableName=tname, Key={"pk": {"S": "d1"}})
+ assert "Item" not in resp
+
+
+def test_partiql_nonexistent_table(ddb):
+ """ExecuteStatement on a nonexistent table should return ResourceNotFoundException."""
+ with pytest.raises(ClientError) as exc:
+ ddb.execute_statement(Statement='SELECT * FROM "no-such-table-partiql"')
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_partiql_select_where_number(ddb):
+ """WHERE clause with numeric comparison."""
+ tname = "partiql-num-where"
+ try:
+ ddb.delete_table(TableName=tname)
+ except ClientError:
+ pass
+ ddb.create_table(
+ TableName=tname,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "n1"}, "age": {"N": "25"}})
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "n2"}, "age": {"N": "30"}})
+
+ resp = ddb.execute_statement(
+ Statement=f'SELECT * FROM "{tname}" WHERE age > ?',
+ Parameters=[{"N": "27"}],
+ )
+ assert len(resp["Items"]) == 1
+ assert resp["Items"][0]["pk"]["S"] == "n2"
+
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index f390de86..ee820819 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -1199,3 +1199,76 @@ def test_describe_tags_filters(ec2):
# All tags have correct resource type
resp = ec2.describe_tags(Filters=[{"Name": "resource-id", "Values": [id1, id2]}])
assert all(t["ResourceType"] == "instance" for t in resp["Tags"])
+
+
+def test_ec2_default_vpc_network_acl(ec2):
+ """Default VPC's network ACL should exist and be queryable."""
+ resp = ec2.describe_network_acls(
+ Filters=[{"Name": "default", "Values": ["true"]}]
+ )
+ acls = resp["NetworkAcls"]
+ assert len(acls) >= 1
+ default_acl = acls[0]
+ assert default_acl["IsDefault"] is True
+ # Should have both allow and deny entries
+ assert len(default_acl["Entries"]) >= 4
+
+
+def test_ec2_create_default_vpc_already_exists(ec2):
+ """CreateDefaultVpc should fail when a default VPC already exists."""
+ with pytest.raises(ClientError) as exc:
+ ec2.create_default_vpc()
+ assert exc.value.response["Error"]["Code"] == "DefaultVpcAlreadyExists"
+
+
+def test_ec2_create_default_vpc(ec2):
+ """CreateDefaultVpc should create a VPC with subnets, IGW, SG, route table, ACL."""
+ # First, find and delete the existing default VPC and its dependencies
+ vpcs = ec2.describe_vpcs(Filters=[{"Name": "is-default", "Values": ["true"]}])["Vpcs"]
+ if vpcs:
+ default_vpc_id = vpcs[0]["VpcId"]
+ # Delete subnets
+ for s in ec2.describe_subnets(Filters=[{"Name": "vpc-id", "Values": [default_vpc_id]}])["Subnets"]:
+ ec2.delete_subnet(SubnetId=s["SubnetId"])
+ # Delete non-default security groups (other tests may have created them)
+ for sg in ec2.describe_security_groups(
+ Filters=[{"Name": "vpc-id", "Values": [default_vpc_id]}]
+ )["SecurityGroups"]:
+ if sg["GroupName"] != "default":
+ ec2.delete_security_group(GroupId=sg["GroupId"])
+ # Detach and delete IGWs
+ for igw in ec2.describe_internet_gateways(
+ Filters=[{"Name": "attachment.vpc-id", "Values": [default_vpc_id]}]
+ )["InternetGateways"]:
+ ec2.detach_internet_gateway(InternetGatewayId=igw["InternetGatewayId"], VpcId=default_vpc_id)
+ ec2.delete_internet_gateway(InternetGatewayId=igw["InternetGatewayId"])
+ ec2.delete_vpc(VpcId=default_vpc_id)
+
+ # Now create a new default VPC
+ resp = ec2.create_default_vpc()
+ vpc = resp["Vpc"]
+ assert vpc["IsDefault"] is True
+ assert vpc["CidrBlock"] == "172.31.0.0/16"
+ assert vpc["State"] == "available"
+
+ vpc_id = vpc["VpcId"]
+
+ # Verify 3 default subnets were created
+ subnets = ec2.describe_subnets(
+ Filters=[{"Name": "vpc-id", "Values": [vpc_id]}]
+ )["Subnets"]
+ assert len(subnets) == 3
+ for s in subnets:
+ assert s["DefaultForAz"] is True
+ assert s["MapPublicIpOnLaunch"] is True
+
+ # Verify IGW attached
+ igws = ec2.describe_internet_gateways(
+ Filters=[{"Name": "attachment.vpc-id", "Values": [vpc_id]}]
+ )["InternetGateways"]
+ assert len(igws) == 1
+
+ # Verify calling again fails
+ with pytest.raises(ClientError) as exc:
+ ec2.create_default_vpc()
+ assert exc.value.response["Error"]["Code"] == "DefaultVpcAlreadyExists"
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 45c68af7..e3b024de 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -1896,3 +1896,39 @@ def test_esm_response_no_function_name_field(lam, sqs):
lam.delete_event_source_mapping(UUID=esm_uuid)
lam.delete_function(FunctionName=fname)
sqs.delete_queue(QueueUrl=q_url)
+
+
+def test_lambda_update_function_configuration_layers(lam):
+ """Attaching a layer via update-function-configuration should normalize ARN strings
+ to {Arn, CodeSize} dicts — regression test for 'str' object has no attribute 'get'."""
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as z:
+ z.writestr("util.py", "# layer code")
+ layer_resp = lam.publish_layer_version(
+ LayerName="update-cfg-layer", Content={"ZipFile": buf.getvalue()},
+ )
+ layer_arn = layer_resp["LayerVersionArn"]
+
+ fn_zip = io.BytesIO()
+ with zipfile.ZipFile(fn_zip, "w") as z:
+ z.writestr("index.py", "def handler(e, c): return {}")
+ lam.create_function(
+ FunctionName="fn-update-layer-test",
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test",
+ Handler="index.handler",
+ Code={"ZipFile": fn_zip.getvalue()},
+ )
+
+ resp = lam.update_function_configuration(
+ FunctionName="fn-update-layer-test",
+ Layers=[layer_arn],
+ )
+ # Response Layers must be dicts with Arn key, not raw strings
+ assert len(resp["Layers"]) == 1
+ assert isinstance(resp["Layers"][0], dict)
+ assert resp["Layers"][0]["Arn"] == layer_arn
+
+ # GetFunction must also return normalized layer dicts
+ fn = lam.get_function(FunctionName="fn-update-layer-test")
+ assert fn["Configuration"]["Layers"][0]["Arn"] == layer_arn
diff --git a/tests/test_rds.py b/tests/test_rds.py
index 010685dd..a569a303 100644
--- a/tests/test_rds.py
+++ b/tests/test_rds.py
@@ -94,7 +94,7 @@ def test_rds_delete_instance_v2(rds):
rds.delete_db_instance(DBInstanceIdentifier="rds-del-v2", SkipFinalSnapshot=True)
with pytest.raises(ClientError) as exc:
rds.describe_db_instances(DBInstanceIdentifier="rds-del-v2")
- assert exc.value.response["Error"]["Code"] == "DBInstanceNotFound"
+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFoundFault"
def test_rds_modify_instance_v2(rds):
rds.create_db_instance(