Skip to content

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

prerelease (#2078)

Nahuel Nucerada421e695812
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d84facdf..0b9ff207 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
-- **IoT — domain configurations** — `CreateDomainConfiguration`, `DescribeDomainConfiguration`, `ListDomainConfigurations`, `UpdateDomainConfiguration` and `DeleteDomainConfiguration`, and the CloudFormation type `AWS::IoT::DomainConfiguration`, were missing. The list now shows the `iot:Data-ATS` and `iot:CredentialProvider` configurations IoT owns (their `domainName` is the `DescribeEndpoint` address). A configuration without a server certificate is AWS-managed with a generated `-ats` host, one with an ACM certificate is customer-managed, and requests are validated with AWS's messages (TLS security policy, authentication type and protocol combinations, certificates, the IoT-owned entries). As on AWS, only a DISABLED configuration can be deleted (AWS's seven-day hold on an AWS-managed one is not enforced), and CloudFormation leaves a configuration DISABLED unless the template enables it, and disables it before deleting it. The broker does not serve a configured domain. Contributed by @iot-rocket.
+- **IoT — domain configurations** — `CreateDomainConfiguration`, `DescribeDomainConfiguration`, `ListDomainConfigurations`, `UpdateDomainConfiguration` and `DeleteDomainConfiguration`, and the CloudFormation type `AWS::IoT::DomainConfiguration`, were missing. The list now shows the `iot:Data-ATS` and `iot:CredentialProvider` configurations IoT owns (their `domainName` is the `DescribeEndpoint` address). A configuration without a server certificate is AWS-managed with a generated `-ats` host, one with an ACM certificate is customer-managed, and requests are validated with AWS's messages (TLS security policy, authentication type and protocol combinations, certificates, the IoT-owned entries). As on AWS, only a DISABLED configuration can be deleted, and an AWS-managed one only seven days after it was disabled; CloudFormation leaves a configuration DISABLED unless the template enables it, and disables it before deleting it, so the stack delete of an AWS-managed one fails with `DELETE_FAILED`. The broker does not serve a configured domain. Contributed by @iot-rocket.
- **CloudFormation — enum properties are validated before provisioning** — a template value outside an enum of the resource schema was only refused by the resource's own create, after the resources before it existed. Such a value, literal or from a parameter, now fails the create before anything is provisioned, as AWS does: one stack `CREATE_FAILED` event "Validation failed with N error(s). ..." with `DetailedStatus` `VALIDATION_FAILED`, then `ROLLBACK_IN_PROGRESS` and `ROLLBACK_COMPLETE`, with no resource event. `DescribeStackEvents` returns `DetailedStatus`. `AWS::Signer::SigningProfile` `PlatformId` is the first property checked. Contributed by @iot-rocket.
- **Signer — CloudFormation `AWS::Signer::SigningProfile` and `AWS::Signer::ProfilePermission`, profile permissions and `CancelSigningProfile`** — a template with either type was refused as an unrecognized resource type, and the profile permission API and `CancelSigningProfile` had no route. Both types now provision as AWS does: the profile's `Ref` is its ARN with `Arn`, `ProfileName`, `ProfileVersion` and `ProfileVersionArn` attributes, a generated name is `<LogicalId>_` plus 12 letters and digits, `Tags` (with the stack and `aws:cloudformation:` tags) update in place, a `PlatformId` or `SignatureValidityPeriod` change replaces the profile, a delete cancels it, and a `PlatformId` outside the schema's two values fails the resource with AWS's enum message; the permission's `Ref` is `<StatementId>|<ProfileName>`. `AddProfilePermission`, `ListProfilePermissions` and `RemoveProfilePermission` follow the revision id rules, error codes, 2000-byte policy limit and `policySizeBytes` measured on AWS, a canceled profile keeps its name and its permissions, `PutSigningProfile` refuses a name that is already taken, and `GetSigningProfile` reports the 135-month default validity period. Contributed by @iot-rocket.
- **CloudFormation — `AWS::IoT::Thing`, `AWS::IoT::Certificate`, `AWS::IoT::ThingPrincipalAttachment` and `AWS::IoT::PolicyPrincipalAttachment`** — a template using any of them failed with `Unrecognized resource types`. They now provision onto the IoT registry as AWS does: `Ref` and `Fn::GetAtt` return AWS's values (`{name}|{principal}` for the attachments), `AttributePayload` and `Status` update in place, the create-only properties replace the resource, a certificate is deactivated before its delete, a thing or certificate that still has an attachment made outside the stack fails its delete with the service's message, and a `ThingName` that already exists fails the create instead of adopting the thing. A certificate comes from `CertificateSigningRequest`, from `CertificatePem` with `CACertificatePem`, or from `CertificatePem` alone in `SNI_ONLY` mode. Thing and certificate can be imported. Contributed by @iot-rocket.
@@ -17,9 +17,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **Lambda — preserve invocation aliases in runtime context** — `Invoke` retains the requested alias or version in `invoked_function_arn`, while `function_version` remains the resolved published version. Warm workers receive invocation identity per request. Contributed by @jayjanssen.
- **IoT — `DescribeCertificate` reports `certificateMode`** — the field was missing from the description. It is now `SNI_ONLY` for a certificate registered with `RegisterCertificateWithoutCA` and `DEFAULT` for the others, as AWS reports it. Contributed by @iot-rocket.
### Fixed
-- **Lambda — preserve invocation aliases in runtime context** — `Invoke` retains the requested alias or version in `invoked_function_arn`, while `function_version` remains the resolved published version. Warm workers receive invocation identity per request.
- **RDS Data API — MySQL `generatedFields`** — `ExecuteStatement` and `BatchExecuteStatement` always answered `generatedFields: []`, so an `INSERT` into an `AUTO_INCREMENT` table gave no way to read the new id. On the MySQL engines it now holds the id the server assigned (`[{"longValue": <id>}]`), or `[]` when none was assigned; `BatchExecuteStatement` reports it in each parameter set's update result. Aurora PostgreSQL still returns `[]`: the API reference says it does not support `generatedFields` and points to `RETURNING`.
- **SSM — `PutParameter` validates `Type`, reserved names and `Tags` with `Overwrite`** — three requests that AWS refuses were accepted. Creating a parameter without `Type` now fails with `ValidationException` ("A parameter type is required when you create a parameter."), and an overwrite without `Type` keeps the stored type instead of resetting it to `String`, so a `SecureString` no longer turns into plaintext. Names whose first characters (after an optional leading `/`) are `aws` or `ssm`, in any case, are refused: `/aws...` with `AccessDeniedException`, everything else with `ValidationException`, all HTTP 400. `Tags` together with `Overwrite=true` fails with `ValidationException` whether or not the parameter exists; an empty `Tags` list is accepted. Matches AWS observed in us-east-1 on 2026-10-06. Reported by @jin-gizmo.
@@ -30,7 +30,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **IoT — job templates and `AWS::IoT::JobTemplate`** — `CreateJobTemplate`, `DescribeJobTemplate`, `ListJobTemplates` and `DeleteJobTemplate` were missing, so a `jobTemplateArn` could not be created or used. Templates now store a document or a `documentSource` (not fetched, like `CreateJob`'s), every job configuration member, maintenance windows and tags, can be copied from a job through `jobArn`, list newest first with `maxResults` / `nextToken` paging, and answer AWS's errors and messages. `CreateJob` with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a member the request names replaces the template's. CloudFormation creates and deletes `AWS::IoT::JobTemplate` (Ref is the id, `Fn::GetAtt` `Arn`); every property is create-only, so an update under the same `JobTemplateId` fails with AWS's custom-name sentence and a new id replaces the template. Contributed by @iot-rocket.
### Fixed
-- **DynamoDB — transactions are authorized per item under `AUTH=true`** — `TransactWriteItems` and `TransactGetItems` were checked as `dynamodb:TransactWriteItems` / `dynamodb:TransactGetItems` on the first item's table, which are not IAM actions, so a policy granting the item actions was refused and one granting the transaction name was accepted. Each item is now checked as the action it performs (`dynamodb:PutItem`, `UpdateItem`, `DeleteItem`, `ConditionCheckItem`, `GetItem`) on its own table. Fixes #2063.
+- **DynamoDB — transactions are authorized per item under `AUTH=true`** — `TransactWriteItems` and `TransactGetItems` were checked as `dynamodb:TransactWriteItems` / `dynamodb:TransactGetItems` on the first item's table, which are not IAM actions, so a policy granting the item actions was refused and one granting the transaction name was accepted. Each item is now checked as the action it performs (`dynamodb:PutItem`, `UpdateItem`, `DeleteItem`, `ConditionCheckItem`, `GetItem`) on its own table. Each item check carries `dynamodb:EnclosingOperation`, so policies that allow or deny only transactional calls evaluate as on AWS. Contributed by @drakeo338.
- **Kinesis — active subscriptions survive retention pruning** — `SubscribeToShard` tracks its selected sequence boundary instead of a record-list offset, so removing expired records cannot skip newly appended records. The starting boundary and checkpoint are captured before streaming begins and progress remains stable through idle polls and repeated pruning. Contributed by @AdrianAcala.
## [1.5.22] — 2026-10-05
diff --git a/ministack/app.py b/ministack/app.py
index 07e8307f..f1b76ec6 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2519,10 +2519,12 @@ async def _dispatch_service_request(
)
if transaction_checks:
denied = None
+ item_context = {**(service_context or {}),
+ "dynamodb:EnclosingOperation": [iam_action.split(":", 1)[1]]}
for item_action, item_arn in transaction_checks:
denied = enforce(
access_key, item_action, service, region,
- resource_arn=item_arn, service_context=service_context,
+ resource_arn=item_arn, service_context=item_context,
)
if denied:
iam_action = item_action # named in the AccessDenied message
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index d2cef75c..81dd1e2c 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -755,10 +755,7 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "TopicName",
"exists": "Topic creation failed because the topic already exists",
},
- # Measured on an account: a SignatureValidityPeriod change under a kept
- # ProfileName, and an Action change under a kept StatementId and
- # ProfileName (the permission's identity), both fail with the refusal
- # sentence naming the physical id.
+ # A permission's identity is StatementId + ProfileName.
"AWS::Signer::SigningProfile": {"name": "ProfileName"},
"AWS::Signer::ProfilePermission": {"name": ("StatementId", "ProfileName")},
# "If you specify a name, you cannot perform updates that require
@@ -861,8 +858,7 @@ def _custom_named_replacement_error(resource_type, old_props, new_props,
def _kept_custom_name(resource_type, old_props, new_props):
- """The explicit name an update keeps unchanged, else None. A ``name``
- tuple is a name made of several properties, kept only when all are."""
+ """The explicit name (or tuple of names) an update keeps unchanged, else None."""
spec = _CUSTOM_NAME_REPLACEMENT.get(resource_type)
if not spec:
return None
@@ -10504,22 +10500,17 @@ def _ses_configuration_set_event_destination_delete(physical_id, props):
# Signer SigningProfile and ProfilePermission
# ---------------------------------------------------------------------------
-# The PlatformId enum of the resource schema (describe-type, 2026-10-05).
-# There is no SigningMaterial property, so no template reaches the IoT
-# platform, whose profiles need a certificate.
+# PlatformId's allowed values in the CloudFormation template reference.
_SIGNER_CFN_PLATFORMS = ("AWSLambda-SHA384-ECDSA", "Notation-OCI-SHA384-ECDSA")
-# Property enums of the resource schemas. AWS checks them before it
-# provisions anything (pre-deployment PROPERTY_VALIDATION): the stack fails
-# with no resource created, also when the value comes from a parameter.
+# Property enums checked before a stack create provisions anything.
_PROPERTY_ENUMS = {
"AWS::Signer::SigningProfile": {"PlatformId": _SIGNER_CFN_PLATFORMS},
}
def _property_enum_errors(resource_type, props):
- """``(property, reason)`` for each value outside its schema enum, with
- AWS's ValidationStatusReason."""
+ """(property, reason) for each value outside its schema enum."""
return [
(prop, f"{props[prop]} is not a valid enum value. Supported values: "
f"[{', '.join(allowed)}]")
@@ -10551,14 +10542,7 @@ def _signer_profile_name_from_arn(physical_id):
def _signer_signing_profile_create(logical_id, props, stack_name):
- """Ref is the profile ARN. Without a ProfileName the name is
- ``<LogicalId>_<12 random letters and digits>`` (measured: Prof_s3JMHz2XvtHK).
- The suffix is random, not hashed from the stack: a canceled profile keeps
- its name for good, so recreating a deleted stack must not reuse one. The
- tags, stack tags and ``aws:cloudformation:`` tags included, are stored as
- given: the ``aws:`` prefix PutSigningProfile refuses is CloudFormation's own.
- The profile is created through PutSigningProfile's own path, so jobs treat
- it like any other profile."""
+ """Ref is the profile ARN; a generated name is <LogicalId>_ + 12 random letters and digits."""
import ministack.services.signer as _signer
# The stack checks the enum before provisioning; a value that came from
# another resource is only known here.
@@ -10585,9 +10569,7 @@ def _signer_signing_profile_create(logical_id, props, stack_name):
def _signer_signing_profile_update(physical_id, old_props, new_props, stack_name):
- """Only Tags can reach this: the other properties are create-only and
- replace the profile first. Tags change in place and the profile keeps
- its version, as measured."""
+ """Only Tags update in place; the profile keeps its version."""
import ministack.services.signer as _signer
profile = _signer._profiles.get(_signer_profile_name_from_arn(physical_id))
if profile is None:
@@ -10599,8 +10581,7 @@ def _signer_signing_profile_update(physical_id, old_props, new_props, stack_name
def _signer_signing_profile_delete(physical_id, props):
- """A signing profile cannot be deleted: CloudFormation cancels it, and
- the canceled profile keeps its name."""
+ """A profile cannot be deleted: CloudFormation cancels it."""
import ministack.services.signer as _signer
_signer._cancel_signing_profile(_signer_profile_name_from_arn(physical_id))
@@ -10612,9 +10593,7 @@ def _signer_current_revision(profile_name):
def _signer_profile_permission_create(logical_id, props, stack_name):
- """Ref is ``<StatementId>|<ProfileName>``, as measured. The handler reads
- the policy's current revision first, so permissions on one profile do
- not conflict with each other."""
+ """Ref is <StatementId>|<ProfileName>; adds at the policy's current revision."""
import ministack.services.signer as _signer
name = props.get("ProfileName", "")
sid = props.get("StatementId", "")
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index acfa1d19..3bdac75a 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -600,12 +600,7 @@ _VALIDATION_ROLLBACK = "Validation failure detected. See the operation's FAILED
def _fail_property_validation(stack, stack_id, stack_name, resources_defs, ordered,
param_values, conditions, mappings, disable_rollback):
- """Fail a create whose template sets a property outside its schema enum,
- before anything is provisioned, with the events AWS records (measured
- 2026-10-05: one count for all errors, a parameter's value is checked,
- the valid resources are not created either). A value that depends on
- another resource is left to the provisioner. AWS lists the errors
- through DescribeEvents, which is not served; they are logged."""
+ """Fail a create with a property outside its schema enum before provisioning anything."""
errors = []
for logical_id in ordered:
res_def = resources_defs[logical_id]
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 4e8e6532..631ac79b 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -1081,7 +1081,7 @@ def _list_domain_configurations(qp: dict) -> tuple:
try:
page_size = int(raw_size) if raw_size not in (None, "") else None
except (TypeError, ValueError):
- return _domain_config_invalid("pageSize must be an integer")
+ return _domain_config_invalid("The request is not valid.")
if page_size is not None and page_size > _DOMAIN_CONFIG_LIST_LIMIT:
return _domain_config_constraint(
"pageSize", f"have value less than or equal to {_DOMAIN_CONFIG_LIST_LIMIT}")
@@ -1184,11 +1184,7 @@ def _update_domain_configuration(name: str, payload: dict) -> tuple:
def _delete_domain_configuration(name: str) -> tuple:
- """``DELETE /domainConfigurations/{name}``: only a DISABLED configuration
- goes, and an unknown name answers 200, as on AWS. AWS also keeps an
- AWS_MANAGED configuration until it has been DISABLED for seven days; that
- wall-clock hold is not enforced, so a test or stack can clean up after
- itself."""
+ """Only a DISABLED configuration goes (an AWS-managed one after seven days); an unknown name is 200."""
err = _domain_config_name_error(name, _DOMAIN_CONFIG_NAME_RE)
if err:
return err
@@ -1198,6 +1194,11 @@ def _delete_domain_configuration(name: str) -> tuple:
if record["domainConfigurationStatus"] != "DISABLED":
return _domain_config_invalid(
"Cannot delete a domain configuration that is not disabled")
+ if (record.get("domainType") == "AWS_MANAGED"
+ and _now_epoch() - float(record.get("lastStatusChangeDate") or 0) < 7 * 86400):
+ return _domain_config_invalid(
+ "AWS Managed Domain Configuration must be disabled for at least 7 days "
+ "before it can be deleted")
del _domain_configurations[name]
return json_response({})
diff --git a/ministack/services/signer.py b/ministack/services/signer.py
index 2c2258c2..bcb24200 100644
--- a/ministack/services/signer.py
+++ b/ministack/services/signer.py
@@ -733,8 +733,7 @@ def _put_signing_profile(name, body):
if problem is not None:
return problem
if name in _profiles:
- # A profile name is taken for good: AWS refuses a second put on an
- # Active profile and on a Canceled one alike (measured 2026-10-05).
+ # A profile name is taken for good, Active or Canceled.
return _coded_error(400, "ValidationException", "ProfileAlreadyExists",
f"Profile with name {name} already exists")
profile = _register_profile(name, body)
@@ -759,10 +758,7 @@ def _get_signing_profile(name):
return json_response(shown)
-# Profile permissions. The statements live on the profile record under
-# "policy" ({"revisionId", "statements"}), so persistence, reset and the
-# account/region scoping follow the profile. Wording, codes and ordering below
-# were measured on AWS 2026-10-05 (eu-central-1, AWSLambda-SHA384-ECDSA).
+# Profile permissions live on the profile record under "policy".
_PERMISSION_ACTIONS = ("signer:StartSigningJob", "signer:GetSigningProfile",
"signer:RevokeSignature")
@@ -772,8 +768,7 @@ _MAX_POLICY_BYTES = 2000
def _coded_error(status, error_type, code, message):
- """A signer error whose body carries the `code` member AWS fills in for
- these operations (for example `PolicyRevisionIdMismatch`)."""
+ """A signer error carrying the `code` member."""
return error_response_json(error_type, message, status, extra={"code": code},
content_type=REST_JSON_CONTENT_TYPE)
@@ -792,17 +787,13 @@ def _policy_statement(profile, permission, expand_principal):
def _policy_size(profile, permissions, expand_principal=True):
- """The length of the compact JSON statement list. With the account id
- principals written as `arn:aws:iam::<id>:root` this is policySizeBytes;
- with the principals as given it is what the 2000-byte limit counts (2000
- was accepted and 2001 refused). Both reproduced every size measured on
- AWS, for account and role principals, with and without profileVersion."""
+ """Compact JSON length of the statements (policySizeBytes, or the 2000-byte limit with principals as given)."""
statements = [_policy_statement(profile, p, expand_principal) for p in permissions]
return len(json.dumps(statements, separators=(",", ":")))
def _active_profile_for_permissions(name, verb):
- """`(profile, None)` for an Active profile, else `(None, error)`."""
+ """(profile, None) for an Active profile, else (None, error)."""
name_err = _validate_profile_name(name)
if name_err:
return None, name_err
@@ -893,10 +884,7 @@ def _no_policy(name):
def _list_profile_permissions(name):
- """The whole policy in one page. AWS caps a policy at 2000 bytes, which
- is a handful of statements, and answered every listing measured in one
- page, ignoring a nextToken it did not issue; nextToken is ignored here
- and never returned."""
+ """The whole policy in one page; nextToken is ignored and never returned."""
profile, err = _active_profile_for_permissions(name, None)
if err:
return err
@@ -935,10 +923,7 @@ def _remove_profile_permission(name, sid, revision):
def _cancel_signing_profile(name):
- """Status becomes Canceled; the name stays taken and the permissions stay
- listable, but they can no longer be added or removed. Canceling twice
- succeeds. On the first cancel AWS issued a new revisionId for the
- policy, which is mirrored here."""
+ """Cancel a profile; its name stays taken and its permissions stay listable."""
name_err = _validate_profile_name(name)
if name_err:
return name_err
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index e19b0324..9047e08a 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -1942,8 +1942,8 @@ def test_cfn_iot_domain_configuration_lifecycle(cfn, iot_client):
"""Ref is the name (``{LogicalId}-{suffix}`` when generated); a create that
does not declare DomainConfigurationStatus leaves the configuration
DISABLED; an update applies the declared members in place and keeps the
- dropped ones; the delete disables an ENABLED configuration and then
- deletes it (AWS's seven-day hold on an AWS-managed one is not enforced)."""
+ dropped ones; the delete disables an ENABLED configuration, then fails on
+ AWS's seven-day hold for an AWS-managed one (DELETE_FAILED)."""
stack_name = f"cfn-iot-dc-{_uuid_mod.uuid4().hex[:8]}"
named = f"cfn-dc-{_uuid_mod.uuid4().hex[:8]}"
cfn.create_stack(StackName=stack_name, TemplateBody=_iot_domain_configuration_template({
@@ -1993,16 +1993,20 @@ def test_cfn_iot_domain_configuration_lifecycle(cfn, iot_client):
cfn.delete_stack(StackName=stack_name)
stack = _wait_stack(cfn, stack_name)
- assert stack["StackStatus"] == "DELETE_COMPLETE", _stack_event_reasons(cfn, stack_name)
- listed = [d["domainConfigurationName"]
- for d in iot_client.list_domain_configurations()["domainConfigurations"]]
- assert named not in listed and unnamed not in listed
+ assert stack["StackStatus"] == "DELETE_FAILED"
+ assert "must be disabled for at least 7 days" in _stack_event_reasons(cfn, stack_name)
+ for name in (named, unnamed):
+ assert iot_client.describe_domain_configuration(
+ domainConfigurationName=name)["domainConfigurationStatus"] == "DISABLED"
+ cfn.delete_stack(StackName=stack_name, RetainResources=["Named", "Unnamed"])
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
def test_cfn_iot_domain_configuration_create_only_properties(cfn, iot_client):
"""ServiceType and the other create-only properties replace the
configuration: refused under a custom name, a new generated name
- otherwise, with the predecessor deleted in the cleanup."""
+ otherwise, with the predecessor kept by AWS's seven-day hold on deleting
+ an AWS-managed configuration."""
stack_name = f"cfn-iot-dc-replace-{_uuid_mod.uuid4().hex[:8]}"
named = f"cfn-dc-{_uuid_mod.uuid4().hex[:8]}"
cfn.create_stack(StackName=stack_name, TemplateBody=_iot_domain_configuration_template({
@@ -2028,9 +2032,13 @@ def test_cfn_iot_domain_configuration_create_only_properties(cfn, iot_client):
assert second != first and second.startswith("Unnamed-")
listed = [d["domainConfigurationName"]
for d in iot_client.list_domain_configurations()["domainConfigurations"]]
- assert second in listed and first not in listed
+ assert second in listed and first in listed
+ assert iot_client.describe_domain_configuration(
+ domainConfigurationName=first)["domainConfigurationStatus"] == "DISABLED"
cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_FAILED"
+ cfn.delete_stack(StackName=stack_name, RetainResources=["Named", "Unnamed"])
assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 92c03e07..5e85fcb7 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -2609,13 +2609,13 @@ class TestDynamoDBTransactionAuthorization:
_TABLE = "arn:aws:dynamodb:us-east-1:000000000000:table/repro"
@staticmethod
- def _transact(monkeypatch, target, items_key, items, actions, resource="*"):
+ def _transact(monkeypatch, target, items_key, items, actions, resource="*", policy=None):
import asyncio
import ministack.app as app_mod
from ministack.core import iam_evaluator
- statements = parse_policy_document({"Statement": [{
+ statements = parse_policy_document(policy or {"Statement": [{
"Effect": "Allow", "Action": actions, "Resource": resource,
}]})
seen = []
@@ -2624,7 +2624,9 @@ class TestDynamoDBTransactionAuthorization:
def enforce_stub(access_key_id, iam_action, service, region, resource_arn="*",
service_context=None):
seen.append((iam_action, resource_arn))
- result = evaluate(_ctx(action=iam_action, resource=resource_arn), [statements])
+ ctx = _ctx(action=iam_action, resource=resource_arn)
+ ctx.service_context = {k.lower(): v for k, v in (service_context or {}).items()}
+ result = evaluate(ctx, [statements])
if result.decision == "Allow":
return None
result.principal_arn = "arn:aws:iam::000000000000:user/testuser"
@@ -2735,6 +2737,30 @@ class TestDynamoDBTransactionAuthorization:
("dynamodb:GetItem", self._TABLE.replace("repro", "other")),
]
+ _ITEM_ACTIONS = ["dynamodb:ConditionCheckItem", "dynamodb:PutItem", "dynamodb:UpdateItem",
+ "dynamodb:DeleteItem", "dynamodb:GetItem"]
+ _ENCLOSING = {"ForAnyValue:StringEquals": {
+ "dynamodb:EnclosingOperation": ["TransactWriteItems", "TransactGetItems"]}}
+
+ def test_allow_only_transactional_operations(self, monkeypatch):
+ """Example 2 of the DynamoDB transactions IAM guide."""
+ policy = {"Statement": [{"Effect": "Allow", "Action": self._ITEM_ACTIONS,
+ "Resource": "*", "Condition": self._ENCLOSING}]}
+ response, _, handled = self._transact(
+ monkeypatch, "TransactWriteItems", "TransactItems", self._WRITE, [], policy=policy)
+ assert response[0] == 200 and handled
+
+ def test_deny_transactional_operations(self, monkeypatch):
+ """Example 3 of the DynamoDB transactions IAM guide."""
+ policy = {"Statement": [
+ {"Effect": "Deny", "Action": self._ITEM_ACTIONS, "Resource": "*",
+ "Condition": self._ENCLOSING},
+ {"Effect": "Allow", "Action": self._ITEM_ACTIONS, "Resource": "*"},
+ ]}
+ response, _, handled = self._transact(
+ monkeypatch, "TransactWriteItems", "TransactItems", self._WRITE, [], policy=policy)
+ assert response[0] == 403 and not handled
+
def test_get_with_only_the_whole_operation_action_is_denied(self, monkeypatch):
items = [{"Get": {"TableName": "repro", "Key": {"pk": {"S": "a"}}}}]
response, _, handled = self._transact(
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 79fab159..aa973ade 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -363,8 +363,8 @@ def test_iot_domain_configuration_update_iot_owned(iot_client):
def test_iot_domain_configuration_delete(iot_client):
- """Only a DISABLED configuration is deleted. AWS also holds an AWS-managed
- one for seven days after it was disabled; MiniStack deletes it at once."""
+ """Only a DISABLED configuration is deleted, and an AWS-managed one only
+ seven days after it was disabled."""
name = _unique("dc-del")
iot_client.create_domain_configuration(domainConfigurationName=name)
delete = iot_client.delete_domain_configuration
@@ -372,11 +372,12 @@ def test_iot_domain_configuration_delete(iot_client):
"InvalidRequestException", "Cannot delete a domain configuration that is not disabled")
iot_client.update_domain_configuration(
domainConfigurationName=name, domainConfigurationStatus="DISABLED")
- delete(domainConfigurationName=name)
- assert _dc_error(iot_client.describe_domain_configuration,
- domainConfigurationName=name)[0] == "ResourceNotFoundException"
- assert name not in [d["domainConfigurationName"]
- for d in iot_client.list_domain_configurations()["domainConfigurations"]]
+ assert _dc_error(delete, domainConfigurationName=name) == (
+ "InvalidRequestException",
+ "AWS Managed Domain Configuration must be disabled for at least 7 days "
+ "before it can be deleted")
+ assert iot_client.describe_domain_configuration(
+ domainConfigurationName=name)["domainConfigurationStatus"] == "DISABLED"
# An unknown name is a no-op; the IoT-owned names fail the Delete pattern.
delete(domainConfigurationName=_unique("dc-never"))
assert _dc_error(delete, domainConfigurationName="iot:Data-ATS")[1].endswith(
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index d0048f4e..c7f2773a 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -4892,7 +4892,7 @@ def test_lambda_cross_account_layer_under_auth_names_the_calling_user(monkeypatc
from ministack.services import iam as iam_svc
monkeypatch.setattr(app_mod, "AUTH", True)
- key, user = "test-layer-consumer-key", "layer-consumer"
+ key, user = "AKIALAYERCONSUMER001", "layer-consumer"
user_arn = f"arn:aws:iam::{_CALLER_ACCOUNT}:user/{user}"
seeded = [
(iam_svc._users, user, {"UserName": user, "Arn": user_arn, "UserId": "AIDALAYER", "AttachedPolicies": []}),
@@ -13575,13 +13575,16 @@ def test_idle_reaper_and_reset_release_provided_environments(isolated_runtime):
def test_invoke_signature_keeps_trace_out_of_the_positional_contract(isolated_runtime):
- """``trace_id`` is keyword-only, so no caller can pass it as the event."""
+ """``trace_id`` and ``invoked_function_arn`` are keyword-only, so no caller
+ can pass either as the event."""
import inspect
sig = inspect.signature(lambda_runtime.ProvidedWorker.invoke)
- assert list(sig.parameters) == ["self", "event", "request_id", "trace_id"]
- assert sig.parameters["trace_id"].kind is inspect.Parameter.KEYWORD_ONLY
- assert sig.parameters["trace_id"].default is None
+ assert list(sig.parameters) == [
+ "self", "event", "request_id", "trace_id", "invoked_function_arn"]
+ for name in ("trace_id", "invoked_function_arn"):
+ assert sig.parameters[name].kind is inspect.Parameter.KEYWORD_ONLY
+ assert sig.parameters[name].default is None
def test_json_only_bootstrap_output_is_not_parsed_as_protocol(worker_factory):
@@ -14279,3 +14282,46 @@ while True:
result = worker.invoke({}, "request-" + qualifier, invoked_function_arn=arn)
assert result["status"] == "ok", result
assert result["result"] == arn
+
+
[email protected]("runtime", ["python3.12", "nodejs20.x"])
[email protected]("asynchronous", [False, True])
+def test_invocation_retains_alias_without_mutating_version(monkeypatch, asynchronous, runtime):
+ """Invoke identity follows the caller's qualifier, not alias resolution."""
+ from copy import deepcopy
+
+ from ministack.core.lambda_runtime import invalidate_worker
+ from ministack.services import lambda_svc as svc
+
+ name = "identity-" + _uuid_mod.uuid4().hex
+ arn = svc._func_arn(name)
+ config = {"FunctionName": name, "FunctionArn": arn, "Runtime": runtime,
+ "Handler": "index.handler", "Timeout": 10, "Version": "$LATEST"}
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as archive:
+ archive.writestr("index.py", "def handler(event, context):\n"
+ " return [context.invoked_function_arn, context.function_version, event]\n")
+ archive.writestr("index.js", "exports.handler = async (event, context) => [context.invokedFunctionArn, context.functionVersion, event];")
+ version = {"config": {**config, "FunctionArn": arn + ":1", "Version": "1"},
+ "code_zip": buf.getvalue()}
+ function = {"config": config, "code_zip": buf.getvalue(), "versions": {"1": version},
+ "aliases": {"worker": {"FunctionVersion": "1"}, "other": {"FunctionVersion": "1"}}}
+ original = deepcopy(function)
+ monkeypatch.setitem(svc._functions, name, function)
+ monkeypatch.setattr(svc, "_emit_lambda_metrics", lambda *args, **kwargs: None)
+ monkeypatch.setattr(svc, "_execute_function_with_config_scope", svc._execute_function_warm)
+ captured = []
+ monkeypatch.setattr(svc, "invoke_async_with_retry", lambda f, e: captured.append(svc._execute_function_warm(f, e)))
+ try:
+ # Alternate aliases sharing one published version, including warm reuse.
+ for qualifier in ["worker", "other", "1", "worker", None, "$LATEST"]:
+ headers = {"x-amz-invocation-type": "Event"} if asynchronous else {}
+ status, response_headers, body = asyncio.run(svc._invoke(name, {"value": 1}, headers, qualifier))
+ expected_version = "1" if qualifier in ("worker", "other", "1") else "$LATEST"
+ assert response_headers["X-Amz-Executed-Version"] == expected_version
+ assert status == (202 if asynchronous else 200)
+ result = captured[-1]["body"] if asynchronous else json.loads(body)
+ assert result == [arn + (":" + qualifier if qualifier else ""), expected_version, {"value": 1}]
+ assert function == original
+ finally:
+ invalidate_worker(name)
diff --git a/tests/test_lambda_invocation_identity.py b/tests/test_lambda_invocation_identity.py
deleted file mode 100644
index b8b06761..00000000
--- a/tests/test_lambda_invocation_identity.py
+++ /dev/null
@@ -1,52 +0,0 @@
-"""Invoke identity follows the caller's qualifier, not alias resolution.
-
-AWS contract: https://docs.aws.amazon.com/lambda/latest/dg/python-context.html
-"""
-import asyncio
-import io
-import json
-import uuid
-import zipfile
-from copy import deepcopy
-
-import pytest
-
-from ministack.core.lambda_runtime import invalidate_worker
-from ministack.services import lambda_svc as svc
-
-
[email protected]("runtime", ["python3.12", "nodejs20.x"])
[email protected]("asynchronous", [False, True])
-def test_invocation_retains_alias_without_mutating_version(monkeypatch, asynchronous, runtime):
- name = "identity-" + uuid.uuid4().hex
- arn = svc._func_arn(name)
- config = {"FunctionName": name, "FunctionArn": arn, "Runtime": runtime,
- "Handler": "index.handler", "Timeout": 10, "Version": "$LATEST"}
- buf = io.BytesIO()
- with zipfile.ZipFile(buf, "w") as archive:
- archive.writestr("index.py", "def handler(event, context):\n"
- " return [context.invoked_function_arn, context.function_version, event]\n")
- archive.writestr("index.js", "exports.handler = async (event, context) => [context.invokedFunctionArn, context.functionVersion, event];")
- version = {"config": {**config, "FunctionArn": arn + ":1", "Version": "1"},
- "code_zip": buf.getvalue()}
- function = {"config": config, "code_zip": buf.getvalue(), "versions": {"1": version},
- "aliases": {"worker": {"FunctionVersion": "1"}, "other": {"FunctionVersion": "1"}}}
- original = deepcopy(function)
- monkeypatch.setitem(svc._functions, name, function)
- monkeypatch.setattr(svc, "_emit_lambda_metrics", lambda *args, **kwargs: None)
- monkeypatch.setattr(svc, "_execute_function_with_config_scope", svc._execute_function_warm)
- captured = []
- monkeypatch.setattr(svc, "invoke_async_with_retry", lambda f, e: captured.append(svc._execute_function_warm(f, e)))
- try:
- # Alternate aliases sharing one published version, including warm reuse.
- for qualifier in ["worker", "other", "1", "worker", None, "$LATEST"]:
- headers = {"x-amz-invocation-type": "Event"} if asynchronous else {}
- status, response_headers, body = asyncio.run(svc._invoke(name, {"value": 1}, headers, qualifier))
- expected_version = "1" if qualifier in ("worker", "other", "1") else "$LATEST"
- assert response_headers["X-Amz-Executed-Version"] == expected_version
- assert status == (202 if asynchronous else 200)
- result = captured[-1]["body"] if asynchronous else json.loads(body)
- assert result == [arn + (":" + qualifier if qualifier else ""), expected_version, {"value": 1}]
- assert function == original
- finally:
- invalidate_worker(name)