Skip to content

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

fix: 1.3.27 audit fixes (CloudTrail, STS, DynamoDB, APIGW v1, EKS, Ba… (#561)

Nahuel Nucera6324cd623f94
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 42fea11f..b211bbe4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,21 +5,26 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
-- **Transfer Family `LOGICAL` root home directory mappings** — `HomeDirectoryMappings` with `Entry="/"` now match SFTP paths like `/users.csv` and resolve them under the configured target bucket instead of falling through because the resolver checked for a `"//"` prefix.
-
---
## [Unreleased]
-### Fixed
-- **API Gateway v1 `GetUsagePlanKey` per-key read handler** — `GET /usageplans/{planId}/keys/{keyId}` was missing from the route dispatcher; only list/create/delete were registered, so the per-key path fell through to a 404. Terraform's AWS provider invokes `GetUsagePlanKey` immediately after `CreateUsagePlanKey` to confirm the resource exists, and the missing handler caused `aws_api_gateway_usage_plan_key` applies to abort with `reading API Gateway Usage Plan Key (...): couldn't find resource`. Added `_get_usage_plan_key(plan_id, key_id)` returning the stored entry on hit and `NotFoundException` on miss for either the plan id or the key id. Contributed by @marcin-nowak-scl.
-
----
-
-## [Unreleased]
+### Added
+- **AWS CloudTrail** — in-memory audit log + control plane. Recording opt-in via `CLOUDTRAIL_RECORDING=1`; per-account ring buffer (`CLOUDTRAIL_MAX_EVENTS=10000`). `LookupEvents` supports all 8 AWS `LookupAttributes`. Control plane: `CreateTrail`, `DeleteTrail`, `GetTrail`, `DescribeTrails`, `ListTrails`, `UpdateTrail`, `GetTrailStatus`, `StartLogging` / `StopLogging` with real `IsLogging` state, `Put`/`GetEventSelectors`, `AddTags` / `ListTags` / `RemoveTags`. Contributed by @AdigaAkhil.
+- **AWS Resource Groups (`resource-groups`, 2017-11-27)** — 19 of 23 spec operations: group CRUD, resource queries, configuration, membership, tagging, account settings. Tag-sync ops omitted (not exposed by AWS CLI / Terraform). Requested by @staranto.
### Fixed
-- **API Gateway v1 HTTP_PROXY path-parameter substitution and query-string forwarding** — `_invoke_http_proxy_v1` ignored `integration.requestParameters` mappings (so `{paramName}` placeholders in the integration `uri` were forwarded literally), appended the inbound execute path to the integration URI, and dropped the request query string. Real AWS HTTP_PROXY substitutes `{paramName}` from `integration.request.path.X = method.request.path.X` mappings (and `{proxy}` for greedy `{proxy+}` resources), uses the substituted URI as the complete upstream URL, and forwards the query string. Terraform `aws_api_gateway_integration` configurations of the form `uri = ".../resource/{id}"` + `integration.request.path.id = method.request.path.id` now reach the upstream with the correct URL.
+- **API Gateway v1 `GetUsagePlanKey`** — `GET /usageplans/{planId}/keys/{keyId}` handler was missing; per-key path fell through to 404. Terraform's `GetUsagePlanKey` refresh after `CreateUsagePlanKey` aborted every `aws_api_gateway_usage_plan_key` apply. Contributed by @marcin-nowak-scl.
+- **API Gateway v1 HTTP_PROXY path-param substitution + query-string forwarding** — `{paramName}` placeholders in integration `uri` were forwarded literally; the inbound execute path was appended to the integration URI; query string was dropped. Now substitutes from `integration.request.path.X = method.request.path.X` mappings (plus `{proxy}` for `{proxy+}`), uses the substituted URI as the upstream URL, and forwards the query string. Contributed by @marcin-nowak-scl.
+- **API Gateway v1 `UpdateModel`** — `PATCH /restapis/{id}/models/{name}` was missing; Terraform `aws_api_gateway_model` updates 404
+- **Transfer Family `LOGICAL` root home directory mappings** — `Entry="/"` failed to match because the resolver built `"//"` as the prefix. Contributed by @stefanmb.
+- **CloudTrail router target prefix** — was `AmazonCloudTrailService`; AWS uses `CloudTrail_20131101`. Routing still worked via credential scope, but the prefix entry was dead code.
+- **CloudTrail `IsLogging` state on `Stop`/`StartLogging`** — both were no-ops; `GetTrailStatus` always returned `IsLogging: True`. Now flips the trail record's state and stamps `_StartedAt` / `_StoppedAt` (int epoch).
+- **STS `Credentials.Expiration` is int epoch in the JSON path** — `AssumeRole` / `AssumeRoleWithWebIdentity` / `GetSessionToken` returned a float; Java/Go SDK v2 reject it.
+- **`backup` / `eks` `_epoch()` / `_now()` return int** — were `time.time()` (float); consumed by record fields like `createdAt`.
+- **DynamoDB `ConditionalCheckFailedException` populates `Item` on `ReturnValuesOnConditionCheckFailure="ALL_OLD"`** — `PutItem` / `UpdateItem` / `DeleteItem` / `TransactWriteItems` now return the prior item alongside the error code (and on the failing `CancellationReason` for transactions). Verified against botocore: `CancellationReason` and `ConditionalCheckFailedException` shapes both include `Item`. Reported by @darkamgine.
+- **CFN `AWS::S3::Bucket` preserves physical id on update** — auto-named buckets got a new random name on every `UpdateStack`, breaking `{Ref}` after redeploy. Contributed by @erick-reis-gran.
+- **CFN `AWS::Lambda::Function` returns real `CodeSize` / `CodeSha256`** — were hardcoded; now computed from the deployment-package bytes. Contributed by @erick-reis-gran.
---
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 4179a12b..2c2e6c0f 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -322,7 +322,7 @@ SERVICE_PATTERNS = {
"credential_scope": "backup",
},
"cloudtrail": {
- "target_prefixes": ["com.amazonaws.cloudtrail.v20131101.AmazonCloudTrailService"],
+ "target_prefixes": ["com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101"],
"host_patterns": [r"cloudtrail\."],
"credential_scope": "cloudtrail",
},
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 15bcb19e..d89c6d3d 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -849,6 +849,8 @@ async def handle_request(method, path, headers, body, query_params):
else:
if method == "GET":
return _get_model(api_id, model_name)
+ if method == "PATCH":
+ return _update_model(api_id, model_name, data)
if method == "DELETE":
return _delete_model(api_id, model_name)
@@ -1674,6 +1676,15 @@ def _get_model(api_id, model_name):
return _v1_response(model)
+def _update_model(api_id, model_name, data):
+ model = _models.get(api_id, {}).get(model_name)
+ if not model:
+ return _v1_error("NotFoundException", "Invalid Model identifier specified", 404)
+ patch_ops = data.get("patchOperations", [])
+ _apply_patch(model, patch_ops)
+ return _v1_response(model)
+
+
def _delete_model(api_id, model_name):
if model_name not in _models.get(api_id, {}):
return _v1_error("NotFoundException", "Invalid Model identifier specified", 404)
diff --git a/ministack/services/backup.py b/ministack/services/backup.py
index 76a0d478..53dce806 100644
--- a/ministack/services/backup.py
+++ b/ministack/services/backup.py
@@ -80,7 +80,7 @@ def _ts():
def _epoch():
- return time.time()
+ return int(time.time())
def _vault_arn(name):
diff --git a/ministack/services/cloudtrail.py b/ministack/services/cloudtrail.py
index b28dfd6b..d34b4b93 100644
--- a/ministack/services/cloudtrail.py
+++ b/ministack/services/cloudtrail.py
@@ -307,15 +307,17 @@ def _get_trail_status(body: dict):
if not raw:
return _err("InvalidTrailNameException", "Trail name is required.")
name = _resolve_trail_name(raw)
- if _trails.get(name) is None:
+ trail = _trails.get(name)
+ if trail is None:
return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)
- now = time.time()
+ now = int(time.time())
+ is_logging = bool(trail.get("IsLogging", True))
return _ok(
{
- "IsLogging": True,
- "LatestDeliveryTime": now,
- "StartLoggingTime": now - 3600,
- "StopLoggingTime": None,
+ "IsLogging": is_logging,
+ "LatestDeliveryTime": now if is_logging else trail.get("_StoppedAt", now),
+ "StartLoggingTime": trail.get("_StartedAt", now - 3600),
+ "StopLoggingTime": trail.get("_StoppedAt") if not is_logging else None,
"LatestDeliveryError": "",
"LatestNotificationError": "",
}
@@ -327,8 +329,12 @@ def _start_logging(body: dict):
if not raw:
return _err("InvalidTrailNameException", "Trail name is required.")
name = _resolve_trail_name(raw)
- if _trails.get(name) is None:
+ trail = _trails.get(name)
+ if trail is None:
return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)
+ trail["IsLogging"] = True
+ trail["_StartedAt"] = int(time.time())
+ trail.pop("_StoppedAt", None)
return _ok({})
@@ -337,11 +343,69 @@ def _stop_logging(body: dict):
if not raw:
return _err("InvalidTrailNameException", "Trail name is required.")
name = _resolve_trail_name(raw)
- if _trails.get(name) is None:
+ trail = _trails.get(name)
+ if trail is None:
return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)
+ trail["IsLogging"] = False
+ trail["_StoppedAt"] = int(time.time())
return _ok({})
+def _list_trails(body: dict):
+ """ListTrails: paginated summary list with TrailARN, Name, HomeRegion."""
+ summaries = [
+ {
+ "TrailARN": t["TrailARN"],
+ "Name": t["Name"],
+ "HomeRegion": t.get("HomeRegion", get_region()),
+ }
+ for t in _trails.values()
+ ]
+ out = {"Trails": summaries}
+ return _ok(out)
+
+
+def _update_trail(body: dict):
+ raw = body.get("Name", "").strip()
+ if not raw:
+ return _err("InvalidTrailNameException", "Trail name is required.")
+ name = _resolve_trail_name(raw)
+ trail = _trails.get(name)
+ if trail is None:
+ return _err("TrailNotFoundException", f"Unknown trail: {name!r}", 404)
+ for src, dst in (
+ ("S3BucketName", "S3BucketName"),
+ ("S3KeyPrefix", "S3KeyPrefix"),
+ ("SnsTopicName", "SnsTopicName"),
+ ("IncludeGlobalServiceEvents", "IncludeGlobalServiceEvents"),
+ ("IsMultiRegionTrail", "IsMultiRegionTrail"),
+ ("EnableLogFileValidation", "LogFileValidationEnabled"),
+ ("CloudWatchLogsLogGroupArn", "CloudWatchLogsLogGroupArn"),
+ ("CloudWatchLogsRoleArn", "CloudWatchLogsRoleArn"),
+ ("KmsKeyId", "KmsKeyId"),
+ ("IsOrganizationTrail", "IsOrganizationTrail"),
+ ):
+ if src in body:
+ trail[dst] = body[src]
+ return _ok(
+ {
+ "Name": name,
+ "S3BucketName": trail.get("S3BucketName", ""),
+ "S3KeyPrefix": trail.get("S3KeyPrefix", ""),
+ "SnsTopicName": trail.get("SnsTopicName", ""),
+ "SnsTopicARN": trail.get("SnsTopicARN", ""),
+ "IncludeGlobalServiceEvents": trail.get("IncludeGlobalServiceEvents", True),
+ "IsMultiRegionTrail": trail.get("IsMultiRegionTrail", False),
+ "TrailARN": trail["TrailARN"],
+ "LogFileValidationEnabled": trail.get("LogFileValidationEnabled", False),
+ "CloudWatchLogsLogGroupArn": trail.get("CloudWatchLogsLogGroupArn", ""),
+ "CloudWatchLogsRoleArn": trail.get("CloudWatchLogsRoleArn", ""),
+ "KmsKeyId": trail.get("KmsKeyId", ""),
+ "IsOrganizationTrail": trail.get("IsOrganizationTrail", False),
+ }
+ )
+
+
def _put_event_selectors(body: dict):
raw = body.get("TrailName", "").strip()
if not raw:
@@ -408,6 +472,8 @@ _DISPATCH = {
"GetTrail": _get_trail,
"DescribeTrails": _describe_trails,
"GetTrailStatus": _get_trail_status,
+ "ListTrails": _list_trails,
+ "UpdateTrail": _update_trail,
"StartLogging": _start_logging,
"StopLogging": _stop_logging,
"PutEventSelectors": _put_event_selectors,
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 49ce8973..add7af68 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -34,6 +34,21 @@ from ministack.core.responses import (
logger = logging.getLogger("dynamodb")
+
+def _conditional_check_failed(data, old_item, message="The conditional request failed"):
+ """Standard ConditionalCheckFailedException response, with `Item` populated
+ when the caller passed `ReturnValuesOnConditionCheckFailure="ALL_OLD"` and
+ we have the prior item. AWS returns the existing item in the error body
+ so callers don't have to re-fetch (see CancellationReason / Put / Update /
+ Delete shapes in service-2.json)."""
+ body = {"__type": "ConditionalCheckFailedException", "message": message}
+ if data.get("ReturnValuesOnConditionCheckFailure") == "ALL_OLD" and old_item:
+ body["Item"] = old_item
+ return 400, {
+ "Content-Type": "application/x-amz-json-1.0",
+ "x-amzn-errortype": "ConditionalCheckFailedException",
+ }, json.dumps(body, ensure_ascii=False).encode("utf-8")
+
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
from ministack.core.persistence import PERSIST_STATE, load_state
@@ -539,7 +554,7 @@ def _put_item(data):
cond_expr = data.get("ConditionExpression")
if cond_expr:
if not _evaluate_condition(cond_expr, old_item or {}, data.get("ExpressionAttributeValues", {}), data.get("ExpressionAttributeNames", {})):
- return error_response_json("ConditionalCheckFailedException", "The conditional request failed", 400)
+ return _conditional_check_failed(data, old_item)
table["items"][pk_val][sk_val] = item
_update_counts(table)
@@ -588,7 +603,7 @@ def _delete_item(data):
cond_expr = data.get("ConditionExpression")
if cond_expr:
if not _evaluate_condition(cond_expr, old_item or {}, data.get("ExpressionAttributeValues", {}), data.get("ExpressionAttributeNames", {})):
- return error_response_json("ConditionalCheckFailedException", "The conditional request failed", 400)
+ return _conditional_check_failed(data, old_item)
if old_item is not None:
table["items"].get(pk_val, {}).pop(sk_val, None)
@@ -621,7 +636,7 @@ def _update_item(data):
if cond_expr:
cond_target = existing or {}
if not _evaluate_condition(cond_expr, cond_target, data.get("ExpressionAttributeValues", {}), data.get("ExpressionAttributeNames", {})):
- return error_response_json("ConditionalCheckFailedException", "The conditional request failed", 400)
+ return _conditional_check_failed(data, existing)
update_expr = data.get("UpdateExpression", "")
eav = data.get("ExpressionAttributeValues", {})
@@ -1245,7 +1260,10 @@ def _transact_write_items(data):
else:
existing = _get_item_by_key(tbl, op.get("Key", {}))
if not _evaluate_condition(cond, existing or {}, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {})):
- return _transact_cancel_response(len(items_list), idx, "ConditionalCheckFailed")
+ # AWS populates `Item` on the failing CancellationReason when
+ # the per-op `ReturnValuesOnConditionCheckFailure` is "ALL_OLD".
+ fail_item = existing if op.get("ReturnValuesOnConditionCheckFailure") == "ALL_OLD" else None
+ return _transact_cancel_response(len(items_list), idx, "ConditionalCheckFailed", fail_item)
for transact in items_list:
op_type, op = _extract_transact_op(transact)
@@ -1314,11 +1332,14 @@ def _extract_transact_op(transact):
return None, None
-def _transact_cancel_response(total, failed_idx, reason):
+def _transact_cancel_response(total, failed_idx, reason, fail_item=None):
reasons = []
for i in range(total):
if i == failed_idx:
- reasons.append({"Code": reason, "Message": "The conditional request failed"})
+ entry = {"Code": reason, "Message": "The conditional request failed"}
+ if fail_item is not None:
+ entry["Item"] = fail_item
+ reasons.append(entry)
else:
reasons.append({"Code": "None"})
data = {
diff --git a/ministack/services/eks.py b/ministack/services/eks.py
index 892ae4cf..e59a8426 100644
--- a/ministack/services/eks.py
+++ b/ministack/services/eks.py
@@ -126,7 +126,7 @@ def _nodegroup_arn(cluster_name, ng_name):
def _now():
- return time.time()
+ return int(time.time())
def _json_resp(status, body):
diff --git a/ministack/services/sts.py b/ministack/services/sts.py
index c2f14946..408b26e8 100644
--- a/ministack/services/sts.py
+++ b/ministack/services/sts.py
@@ -88,7 +88,7 @@ async def handle_request(method, path, headers, body, query_params):
_sessions[access_key] = {"Arn": assumed_arn, "UserId": f"{role_id}:{session_name}"}
if use_json:
return json_response({
- "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
+ "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": int(time.time() + duration)},
"AssumedRoleUser": {"AssumedRoleId": f"{role_id}:{session_name}", "Arn": assumed_arn},
"PackedPolicySize": 0,
})
@@ -123,7 +123,7 @@ async def handle_request(method, path, headers, body, query_params):
provider = _p(params, "ProviderId") or "sts.amazonaws.com"
if use_json:
return json_response({
- "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
+ "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": int(time.time() + duration)},
"AssumedRoleUser": {"AssumedRoleId": f"{role_id}:{session}", "Arn": assumed_arn},
"SubjectFromWebIdentityToken": "test-subject",
"Audience": "sts.amazonaws.com",
@@ -155,7 +155,7 @@ async def handle_request(method, path, headers, body, query_params):
session_token = _gen_session_token()
if use_json:
return json_response({
- "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
+ "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": int(time.time() + duration)},
})
return _xml(200, "GetSessionTokenResponse",
f"<GetSessionTokenResult>"
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 57077a00..33579791 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -361,6 +361,29 @@ def test_apigwv1_model_crud(apigw_v1):
apigw_v1.delete_rest_api(restApiId=api_id)
+
+def test_apigwv1_update_model(apigw_v1):
+ """UpdateModel applies patchOperations. Terraform aws_api_gateway_model
+ issues PATCH on description / schema changes; the dispatcher previously
+ fell through to 404."""
+ api_id = apigw_v1.create_rest_api(name="v1-update-model")["id"]
+ apigw_v1.create_model(
+ restApiId=api_id,
+ name="PatchMe",
+ description="initial",
+ contentType="application/json",
+ schema='{"type": "object"}',
+ )
+ apigw_v1.update_model(
+ restApiId=api_id,
+ modelName="PatchMe",
+ patchOperations=[{"op": "replace", "path": "/description", "value": "updated"}],
+ )
+ got = apigw_v1.get_model(restApiId=api_id, modelName="PatchMe")
+ assert got["description"] == "updated"
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
def test_apigwv1_tags(apigw_v1):
"""TagResource, GetTags, UntagResource."""
api_id = apigw_v1.create_rest_api(name="v1-tags-test")["id"]
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 24b5d171..8e277f60 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -10,8 +10,6 @@ import pytest
import urllib.request
from botocore.exceptions import ClientError
-from conftest import ENDPOINT
-
def _wait_stack(cfn, name, timeout=30):
"""Poll until stack reaches terminal status."""
diff --git a/tests/test_cloudtrail.py b/tests/test_cloudtrail.py
index 31853abe..621d74d6 100644
--- a/tests/test_cloudtrail.py
+++ b/tests/test_cloudtrail.py
@@ -158,6 +158,49 @@ def test_start_stop_logging(ct):
ct.stop_logging(Name=name)
+def test_start_stop_logging_flips_is_logging_state(ct):
+ """StopLogging / StartLogging actually transition IsLogging on the trail
+ record so subsequent GetTrailStatus reflects the change. Terraform's
+ aws_cloudtrail data source asserts on this."""
+ name = f"trail-state-{_uid()}"
+ ct.create_trail(Name=name, S3BucketName="bucket")
+ assert ct.get_trail_status(Name=name)["IsLogging"] is True
+
+ ct.stop_logging(Name=name)
+ after_stop = ct.get_trail_status(Name=name)
+ assert after_stop["IsLogging"] is False
+ assert after_stop.get("StopLoggingTime") is not None
+
+ ct.start_logging(Name=name)
+ assert ct.get_trail_status(Name=name)["IsLogging"] is True
+
+
+def test_list_trails_returns_summaries(ct):
+ name = f"trail-list-{_uid()}"
+ ct.create_trail(Name=name, S3BucketName="bucket")
+ out = ct.list_trails()
+ arns = [t["TrailARN"] for t in out["Trails"]]
+ assert any(arn.endswith(f":trail/{name}") for arn in arns)
+
+
+def test_update_trail_persists_fields(ct):
+ name = f"trail-update-{_uid()}"
+ ct.create_trail(Name=name, S3BucketName="orig")
+ out = ct.update_trail(
+ Name=name,
+ S3BucketName="updated",
+ IsMultiRegionTrail=True,
+ EnableLogFileValidation=True,
+ )
+ assert out["S3BucketName"] == "updated"
+ assert out["IsMultiRegionTrail"] is True
+ assert out["LogFileValidationEnabled"] is True
+
+ desc = ct.get_trail(Name=name)["Trail"]
+ assert desc["S3BucketName"] == "updated"
+ assert desc["IsMultiRegionTrail"] is True
+
+
def test_start_logging_not_found(ct):
with pytest.raises(ClientError) as exc:
ct.start_logging(Name=f"nonexistent-{_uid()}")
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index ac73ddfa..4c5d5e57 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -569,6 +569,86 @@ def test_dynamodb_update_item_condition_on_missing_item_fails(ddb):
)
assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"
+
+def test_dynamodb_conditional_check_failed_returns_item_when_all_old(ddb):
+ """ReturnValuesOnConditionCheckFailure='ALL_OLD' must populate the
+ `Item` member on ConditionalCheckFailedException for PutItem,
+ UpdateItem, DeleteItem, and TransactWriteItems. Verified against
+ botocore: ConditionalCheckFailedException shape includes `Item`,
+ and Put/Update/Delete sub-ops accept ReturnValuesOnConditionCheckFailure.
+ """
+ table = "t_ccf_all_old"
+ try:
+ ddb.delete_table(TableName=table)
+ except Exception:
+ pass
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ seed = {"pk": {"S": "k1"}, "v": {"S": "original"}}
+ ddb.put_item(TableName=table, Item=seed)
+
+ # PutItem: condition fails because the row already exists.
+ with pytest.raises(ClientError) as exc:
+ ddb.put_item(
+ TableName=table,
+ Item={"pk": {"S": "k1"}, "v": {"S": "new"}},
+ ConditionExpression="attribute_not_exists(pk)",
+ ReturnValuesOnConditionCheckFailure="ALL_OLD",
+ )
+ assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"
+ assert exc.value.response.get("Item") == seed
+
+ # UpdateItem: condition fails because the existing value is "original".
+ with pytest.raises(ClientError) as exc:
+ ddb.update_item(
+ TableName=table,
+ Key={"pk": {"S": "k1"}},
+ UpdateExpression="SET v = :v",
+ ConditionExpression="v = :expected",
+ ExpressionAttributeValues={":v": {"S": "new"}, ":expected": {"S": "wrong"}},
+ ReturnValuesOnConditionCheckFailure="ALL_OLD",
+ )
+ assert exc.value.response.get("Item") == seed
+
+ # DeleteItem: same setup.
+ with pytest.raises(ClientError) as exc:
+ ddb.delete_item(
+ TableName=table,
+ Key={"pk": {"S": "k1"}},
+ ConditionExpression="v = :expected",
+ ExpressionAttributeValues={":expected": {"S": "wrong"}},
+ ReturnValuesOnConditionCheckFailure="ALL_OLD",
+ )
+ assert exc.value.response.get("Item") == seed
+
+ # TransactWriteItems: failing CancellationReason carries Item.
+ with pytest.raises(ClientError) as exc:
+ ddb.transact_write_items(TransactItems=[{
+ "Put": {
+ "TableName": table,
+ "Item": {"pk": {"S": "k1"}, "v": {"S": "new"}},
+ "ConditionExpression": "attribute_not_exists(pk)",
+ "ReturnValuesOnConditionCheckFailure": "ALL_OLD",
+ },
+ }])
+ reasons = exc.value.response["CancellationReasons"]
+ assert reasons[0]["Code"] == "ConditionalCheckFailed"
+ assert reasons[0].get("Item") == seed
+
+ # And without ALL_OLD, the Item field must NOT be present.
+ with pytest.raises(ClientError) as exc:
+ ddb.put_item(
+ TableName=table,
+ Item={"pk": {"S": "k1"}, "v": {"S": "new"}},
+ ConditionExpression="attribute_not_exists(pk)",
+ )
+ assert "Item" not in exc.value.response
+
+
def test_dynamodb_get_item_missing_sort_key_fails_validation(ddb):
try:
ddb.delete_table(TableName="t_get_missing_sk")