Skip to content

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

fix(iam): authorize DynamoDB transactions per item (#2064)

Younes Beriane67128f2320b4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f8388ace..335f9531 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,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.
- **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 826b32ca..07e8307f 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2493,6 +2493,7 @@ async def _dispatch_service_request(
agentcore_endpoint_arn,
dynamodb_resource_arns,
dynamodb_service_context,
+ dynamodb_transaction_checks,
eventbridge_resource_arns,
extract_iam_action,
extract_resource_arn,
@@ -2510,10 +2511,27 @@ async def _dispatch_service_request(
service_context = (
dynamodb_service_context(body) if service == "dynamodb" else None
)
- denied = enforce(
- access_key, iam_action, service, region,
- resource_arn=resource_arn, service_context=service_context,
+ # A DynamoDB transaction is not itself an IAM action: each item is
+ # authorized as the single-item action it performs, on its table.
+ transaction_checks = (
+ dynamodb_transaction_checks(iam_action, body, region, get_account_id())
+ if service == "dynamodb" else []
)
+ if transaction_checks:
+ denied = None
+ for item_action, item_arn in transaction_checks:
+ denied = enforce(
+ access_key, item_action, service, region,
+ resource_arn=item_arn, service_context=service_context,
+ )
+ if denied:
+ iam_action = item_action # named in the AccessDenied message
+ break
+ else:
+ denied = enforce(
+ access_key, iam_action, service, region,
+ resource_arn=resource_arn, service_context=service_context,
+ )
# A copy also reads its source, a batch delete is one check per
# key, an attributes call is a pair, a governance bypass its own action.
if service == "s3" and not denied:
@@ -2524,7 +2542,7 @@ async def _dispatch_service_request(
if denied:
iam_action = extra_action
break
- if service == "dynamodb" and not denied:
+ if service == "dynamodb" and not denied and not transaction_checks:
resources = dynamodb_resource_arns(body, region, get_account_id())
for extra_arn in resources[1:]:
denied = enforce(
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index a15d18ac..2f14c11b 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -1696,6 +1696,45 @@ def dynamodb_resource_arns(body: bytes, region: str, account_id: str) -> list[st
]
+_DYNAMODB_TRANSACT_ITEM_ACTIONS = {
+ "ConditionCheck": "dynamodb:ConditionCheckItem",
+ "Put": "dynamodb:PutItem",
+ "Update": "dynamodb:UpdateItem",
+ "Delete": "dynamodb:DeleteItem",
+ "Get": "dynamodb:GetItem",
+}
+
+
+def dynamodb_transaction_checks(
+ iam_action: str, body: bytes, region: str, account_id: str
+) -> list[tuple[str, str]]:
+ """Per-item ``(action, table ARN)`` checks of a DynamoDB transaction.
+
+ ``TransactWriteItems`` and ``TransactGetItems`` are not IAM actions: each
+ item is authorized as the single-item action it performs, on its own table.
+ An item naming more than one member (AWS rejects it, the handler does not)
+ is checked for every member, so none can ride along unchecked.
+ Returns an empty list for any other action or a body with no usable item.
+ """
+ if iam_action not in ("dynamodb:TransactWriteItems", "dynamodb:TransactGetItems"):
+ return []
+ try:
+ data = json.loads(body or b"{}")
+ except (json.JSONDecodeError, TypeError, UnicodeDecodeError):
+ return []
+ items = data.get("TransactItems") if isinstance(data, dict) else None
+ checks = []
+ for item in items if isinstance(items, list) else []:
+ if not isinstance(item, dict):
+ continue
+ for member, action in _DYNAMODB_TRANSACT_ITEM_ACTIONS.items():
+ detail = item.get(member)
+ table = detail.get("TableName") if isinstance(detail, dict) else None
+ if isinstance(table, str) and table:
+ checks.append((action, f"arn:aws:dynamodb:{region}:{account_id}:table/{table}"))
+ return checks
+
+
def dynamodb_service_context(body: bytes) -> dict:
"""The DynamoDB condition keys a request carries.
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 3ae65642..92c03e07 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -2603,6 +2603,150 @@ class TestBedrockAgentCoreAuthorization:
assert evaluate(ctx, [stmts]).decision == decision
+class TestDynamoDBTransactionAuthorization:
+ """TransactWriteItems / TransactGetItems are authorised per item."""
+
+ _TABLE = "arn:aws:dynamodb:us-east-1:000000000000:table/repro"
+
+ @staticmethod
+ def _transact(monkeypatch, target, items_key, items, actions, resource="*"):
+ import asyncio
+
+ import ministack.app as app_mod
+ from ministack.core import iam_evaluator
+
+ statements = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": actions, "Resource": resource,
+ }]})
+ seen = []
+ handled = []
+
+ 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])
+ if result.decision == "Allow":
+ return None
+ result.principal_arn = "arn:aws:iam::000000000000:user/testuser"
+ return result
+
+ async def handler(method, request_path, headers, body, query):
+ handled.append(True)
+ return 200, {"Content-Type": "application/x-amz-json-1.0"}, b"{}"
+
+ monkeypatch.setattr(app_mod, "AUTH", True, raising=False)
+ monkeypatch.setattr(iam_evaluator, "enforce", enforce_stub)
+ monkeypatch.setitem(app_mod.SERVICE_HANDLERS, "dynamodb", handler)
+ headers = {
+ **_sigv4_headers("dynamodb", "dynamodb.us-east-1.amazonaws.com"),
+ "host": "dynamodb.us-east-1.amazonaws.com",
+ "x-amz-target": f"DynamoDB_20120810.{target}",
+ "content-type": "application/x-amz-json-1.0",
+ }
+ headers["authorization"] = headers["authorization"].replace(
+ "20260101/eu-central-1/", "20260101/us-east-1/"
+ )
+ body = json.dumps({items_key: items}).encode()
+ response = asyncio.run(
+ app_mod._dispatch_service_request("POST", "/", headers, body, {}, "req-ddb-tx")
+ )
+ return response, seen, handled
+
+ _WRITE = [
+ {"ConditionCheck": {"TableName": "repro", "Key": {"pk": {"S": "guard"}},
+ "ConditionExpression": "attribute_exists(pk)"}},
+ {"Put": {"TableName": "repro", "Item": {"pk": {"S": "written"}}}},
+ ]
+
+ def test_write_is_allowed_by_the_per_item_actions(self, monkeypatch):
+ response, seen, handled = self._transact(
+ monkeypatch, "TransactWriteItems", "TransactItems", self._WRITE,
+ ["dynamodb:ConditionCheckItem", "dynamodb:PutItem"],
+ )
+ assert response[0] == 200
+ assert handled
+ assert seen == [
+ ("dynamodb:ConditionCheckItem", self._TABLE),
+ ("dynamodb:PutItem", self._TABLE),
+ ]
+
+ def test_write_without_condition_check_permission_is_denied(self, monkeypatch):
+ response, _, handled = self._transact(
+ monkeypatch, "TransactWriteItems", "TransactItems", self._WRITE,
+ ["dynamodb:TransactWriteItems", "dynamodb:PutItem"],
+ )
+ assert response[0] == 403
+ assert b"AccessDenied" in response[2]
+ assert b"dynamodb:ConditionCheckItem" in response[2]
+ assert not handled
+
+ def test_update_and_delete_map_to_their_own_actions(self, monkeypatch):
+ items = [
+ {"Update": {"TableName": "repro", "Key": {"pk": {"S": "a"}}, "UpdateExpression": "SET x = :x"}},
+ {"Delete": {"TableName": "repro", "Key": {"pk": {"S": "b"}}}},
+ ]
+ response, seen, _ = self._transact(
+ monkeypatch, "TransactWriteItems", "TransactItems", items,
+ ["dynamodb:UpdateItem", "dynamodb:DeleteItem"],
+ )
+ assert response[0] == 200
+ assert [a for a, _ in seen] == ["dynamodb:UpdateItem", "dynamodb:DeleteItem"]
+
+ def test_item_naming_several_members_is_checked_for_each(self, monkeypatch):
+ # AWS rejects an item with two members; the handler does not, so the
+ # second member must not run unchecked behind an allowed first one.
+ items = [{
+ "Update": {"TableName": "repro", "Key": {"pk": {"S": "a"}}, "UpdateExpression": "SET x = :x"},
+ "Delete": {"TableName": "repro", "Key": {"pk": {"S": "a"}}},
+ }]
+ response, seen, handled = self._transact(
+ monkeypatch, "TransactWriteItems", "TransactItems", items, ["dynamodb:UpdateItem"],
+ )
+ assert [a for a, _ in seen] == ["dynamodb:UpdateItem", "dynamodb:DeleteItem"]
+ assert response[0] == 403
+ assert b"dynamodb:DeleteItem" in response[2]
+ assert not handled
+
+ def test_denial_on_a_later_table_refuses_the_whole_transaction(self, monkeypatch):
+ items = [
+ {"Put": {"TableName": "repro", "Item": {"pk": {"S": "a"}}}},
+ {"Put": {"TableName": "other", "Item": {"pk": {"S": "b"}}}},
+ ]
+ response, seen, handled = self._transact(
+ monkeypatch, "TransactWriteItems", "TransactItems", items, ["dynamodb:PutItem"],
+ resource=self._TABLE,
+ )
+ assert [r for _, r in seen] == [self._TABLE, self._TABLE.replace("repro", "other")]
+ assert response[0] == 403
+ assert b"AccessDenied" in response[2]
+ assert not handled
+
+ def test_get_is_authorised_per_item_on_its_own_table(self, monkeypatch):
+ items = [
+ {"Get": {"TableName": "repro", "Key": {"pk": {"S": "a"}}}},
+ {"Get": {"TableName": "other", "Key": {"pk": {"S": "b"}}}},
+ ]
+ response, seen, _ = self._transact(
+ monkeypatch, "TransactGetItems", "TransactItems", items, ["dynamodb:GetItem"],
+ )
+ assert response[0] == 200
+ assert seen == [
+ ("dynamodb:GetItem", self._TABLE),
+ ("dynamodb:GetItem", self._TABLE.replace("repro", "other")),
+ ]
+
+ 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(
+ monkeypatch, "TransactGetItems", "TransactItems", items,
+ ["dynamodb:TransactGetItems"],
+ )
+ assert response[0] == 403
+ assert b"AccessDenied" in response[2]
+ assert b"dynamodb:GetItem" in response[2]
+ assert not handled
+
+
class TestS3ActionMapping:
"""S3 authorizes by the IAM actions its documentation lists, not by API
operation name: every multipart operation except abort is ``s3:PutObject``."""