Skip to content

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

fix(wire): error envelope shape + success Content-Types — real-AWS conformance phase 2 (#2129)

Lisandro Pintose542d9d5d49f
diff --git a/ministack/app.py b/ministack/app.py
index 1c524ad6..595cec44 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -226,6 +226,7 @@ from ministack.core.persistence import PERSIST_STATE, load_state, save_all
from ministack.core.responses import (
_12_DIGIT_RE,
fix_error_content_type,
+ fix_success_content_type,
set_request_account_id,
set_request_region,
)
@@ -2558,8 +2559,9 @@ def _unknown_query_error(body: bytes, request_id: str):
else "The requested action is not valid for this web service."
)
msg = msg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+ # Query-protocol error envelopes carry no <?xml?> declaration on the
+ # real AWS wire (17-region capture sweep, 0/85 declarations).
xml = (
- '<?xml version="1.0" encoding="UTF-8"?>\n'
'<ErrorResponse xmlns="http://webservices.amazon.com/doc/2010-05-08/">'
f"<Error><Type>Sender</Type><Code>InvalidAction</Code><Message>{msg}</Message></Error>"
f"<RequestId>{request_id}</RequestId></ErrorResponse>"
@@ -2747,10 +2749,12 @@ async def _dispatch_service_request(
json.dumps({"__type": "InternalError", "message": str(e)}).encode(),
)
- # Real AWS picks an error's Content-Type from the service's protocol —
- # normalize any generic envelope the service emitted to the wire value
- # (evidence: diffs against committed real-AWS wire captures).
+ # Real AWS picks a response envelope's Content-Type from the service's
+ # protocol — normalize any generic envelope the service emitted to the
+ # wire value (evidence: diffs against committed real-AWS wire captures;
+ # multi-region for the success path).
fix_error_content_type(service, status, resp_headers)
+ fix_success_content_type(service, status, resp_headers)
_maybe_record_cloudtrail(service, method, path, headers, body, query_params, request_id, region)
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index e70e86a8..77c5a57b 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -2085,9 +2085,10 @@ def access_denied_response(service: str, action: str, principal_arn: str,
return status, {"Content-Type": "application/xml"}, body.encode()
if protocol == "query-xml":
+ # Query-protocol error envelopes carry no <?xml?> declaration on
+ # the real AWS wire (17-region capture sweep, 0/85 declarations).
ns = _QUERY_XML_NS.get(service, "https://iam.amazonaws.com/doc/2010-05-08/")
body = (
- '<?xml version="1.0" encoding="UTF-8"?>\n'
f'<ErrorResponse xmlns="{ns}">'
f"<Error><Type>Sender</Type><Code>{_esc_code}</Code>"
f"<Message>{_esc_msg}</Message></Error>"
diff --git a/ministack/core/responses.py b/ministack/core/responses.py
index 59303d42..5c6b220e 100644
--- a/ministack/core/responses.py
+++ b/ministack/core/responses.py
@@ -533,20 +533,21 @@ class StreamingResponse:
# ---------------------------------------------------------------------------
-# Error-envelope Content-Type normalization
+# Envelope Content-Type normalization
#
-# Real AWS picks an error's Content-Type from the *service's protocol*, not
-# from a generic default — and services disagree: DynamoDB answers
-# ``application/x-amz-json-1.0`` while Kinesis answers
+# Real AWS picks a response envelope's Content-Type from the *service's
+# protocol*, not from a generic default — and services disagree: DynamoDB
+# answers ``application/x-amz-json-1.0`` while Kinesis answers
# ``application/x-amz-json-1.1``; query-protocol services answer
# ``text/xml`` while EC2 answers ``text/xml;charset=UTF-8``. The botocore
# service model carries everything needed to reproduce this: ``protocol``
-# and ``jsonVersion``. A small override table covers wire quirks the model
+# and ``jsonVersion``. Small override tables cover wire quirks the model
# does not declare.
#
-# Evidence: real AWS wire captures diffed per service (us-east-1) — the
-# model values below matched the captured Content-Type on every probed
-# service.
+# Evidence: real AWS wire captures diffed per service — error-path values
+# from a us-east-1 sweep, success-path values from a us-east-1/us-west-2/
+# eu-west-1/ap-southeast-2 sweep. The model values below matched the
+# captured Content-Type on every probed service.
# ---------------------------------------------------------------------------
# Ministack registry/service names that differ from the botocore client name.
@@ -561,7 +562,9 @@ _BOTOCORE_NAME = {
# Wire-observed Content-Types that contradict what the model implies.
# sesv2 — rest-json service, but AWS emits application/x-amz-json-1.1 on
-# errors (capture: get_email_identity 404).
+# errors (capture: get_email_identity 404). Error-path only: its
+# successes answer application/json like any rest-json service,
+# so this override does not apply to success envelopes.
# s3 — rest-xml, but S3 answers application/xml where the other
# rest-xml services (route53) answer text/xml.
_WIRE_CT_OVERRIDE = {
@@ -569,6 +572,18 @@ _WIRE_CT_OVERRIDE = {
"s3": "application/xml",
}
+# Success-path overrides. The s3 quirk holds on both paths; sesv2's does
+# not (see above), so it is absent here.
+# monitoring — declared ``smithy-rpc-v2-cbor`` in newer botocore, but
+# MiniStack also serves its query-compatible JSON mode,
+# which AWS answers as application/x-amz-json-1.0 (real-AWS
+# capture). Same-family scoping keeps the XML query path on
+# the model-independent text/xml below.
+_WIRE_CT_SUCCESS_OVERRIDE = {
+ "s3": "application/xml",
+ "monitoring": "application/x-amz-json-1.0",
+}
+
_JSON_FAMILY = {
"application/json",
"application/x-amz-json-1.0",
@@ -591,20 +606,34 @@ def _service_model(service: str):
return None
-def expected_error_content_type(service: str, emitted_ct: str) -> str | None:
- """The Content-Type real AWS emits for this service's error envelope.
+def _family_of(ct_base: str):
+ """The envelope family ``ct_base`` belongs to, or None for payload
+ types (``application/octet-stream``, ``image/*``, ``text/plain``, ...)."""
+ if ct_base in _JSON_FAMILY:
+ return _JSON_FAMILY
+ if ct_base in _XML_FAMILY:
+ return _XML_FAMILY
+ return None
+
+
+def _expected_envelope_content_type(service: str, emitted_ct: str,
+ overrides: dict) -> str | None:
+ """The Content-Type real AWS emits for this service's envelopes.
``emitted_ct`` decides which family to correct within: a service that
answered an XML envelope gets the XML value for its protocol, a JSON
- envelope gets the JSON value. Returns None when there is nothing
- evidence-backed to enforce (unknown service, non-envelope type, or a
- protocol ministack does not wire-map, e.g. declared-cbor services it
- serves as query-compatible JSON).
+ envelope gets the JSON value. ``overrides`` is the path-appropriate
+ wire-quirk table; an override only applies inside its own family (the
+ s3 override must not turn a JSON success/error into XML). Returns None
+ when there is nothing evidence-backed to enforce (unknown service,
+ non-envelope type, or a family the model does not wire-map — e.g. a
+ JSON body from a declared-cbor service served as query-compatible
+ JSON).
"""
base = emitted_ct.split(";", 1)[0].strip().lower()
- families = _JSON_FAMILY | _XML_FAMILY
- if base in families and service in _WIRE_CT_OVERRIDE:
- return _WIRE_CT_OVERRIDE[service]
+ override = overrides.get(service)
+ if override is not None and _family_of(base) is _family_of(override):
+ return override
model = _service_model(service)
if model is None:
@@ -619,7 +648,11 @@ def expected_error_content_type(service: str, emitted_ct: str) -> str | None:
return "application/json"
return None
if base in _XML_FAMILY:
- if protocol == "query":
+ # A declared-cbor service that emitted an XML envelope is serving
+ # its legacy Query API mode (cloudwatch is the case in point) —
+ # AWS's query endpoint answers text/xml there like any other
+ # query-protocol service.
+ if protocol in ("query", "smithy-rpc-v2-cbor"):
return "text/xml"
if protocol == "ec2":
return "text/xml;charset=UTF-8"
@@ -628,13 +661,33 @@ def expected_error_content_type(service: str, emitted_ct: str) -> str | None:
return None
+def expected_error_content_type(service: str, emitted_ct: str) -> str | None:
+ """The Content-Type real AWS emits for this service's error envelope."""
+ return _expected_envelope_content_type(service, emitted_ct, _WIRE_CT_OVERRIDE)
+
+
+def expected_success_content_type(service: str, emitted_ct: str) -> str | None:
+ """The Content-Type real AWS emits for this service's success envelope.
+
+ An emitted ``text/xml`` is already wire-final and is never rewritten:
+ on an API envelope it is the correct value (route53, cloudfront), and
+ on e.g. an S3 object stored with a ``text/xml`` Content-Type it is
+ payload that the s3 override would otherwise corrupt to
+ ``application/xml``.
+ """
+ base = emitted_ct.split(";", 1)[0].strip().lower()
+ if base == "text/xml":
+ return None
+ return _expected_envelope_content_type(service, emitted_ct,
+ _WIRE_CT_SUCCESS_OVERRIDE)
+
+
def fix_error_content_type(service: str, status: int, headers: dict) -> None:
"""Rewrite ``headers['Content-Type']`` in place when an error envelope
carries the wrong wire value for the service's protocol.
- Scoped to error responses: the captures that drive this table are
- error probes, and success payloads (e.g. an S3 object that happens to
- be JSON) must never be rewritten.
+ Scoped to error responses: success payloads (e.g. an S3 object that
+ happens to be JSON) must never be rewritten by the error table.
"""
if status < 400:
return
@@ -646,6 +699,26 @@ def fix_error_content_type(service: str, status: int, headers: dict) -> None:
headers["Content-Type"] = expected
+def fix_success_content_type(service: str, status: int, headers: dict) -> None:
+ """Rewrite ``headers['Content-Type']`` in place when a success envelope
+ carries the wrong wire value for the service's protocol.
+
+ Scoped to non-error responses and, within them, to known envelope
+ Content-Types: binary/streaming/payload types
+ (``application/octet-stream``, ``text/plain``, ``image/*``, ...) are
+ never touched, and an emitted ``text/xml`` passes through untouched
+ (see ``expected_success_content_type``).
+ """
+ if status >= 400:
+ return
+ emitted = headers.get("Content-Type", "")
+ if not emitted:
+ return
+ expected = expected_success_content_type(service, emitted)
+ if expected and emitted != expected:
+ headers["Content-Type"] = expected
+
+
def now_iso() -> str:
"""Current time in AWS ISO format."""
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
diff --git a/ministack/services/alb.py b/ministack/services/alb.py
index e2affb5d..584d11f8 100644
--- a/ministack/services/alb.py
+++ b/ministack/services/alb.py
@@ -408,10 +408,13 @@ def _empty(action):
def _error(code, message, status=400):
+ # Query-protocol error envelope per real-AWS captures (17-region
+ # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx)
+ # and no <?xml?> declaration.
body = (
- f'<?xml version="1.0" encoding="UTF-8"?>'
f'<ErrorResponse xmlns="{NS}">'
- f'<Error><Code>{code}</Code><Message>{message}</Message></Error>'
+ f'<Error><Type>{"Sender" if status < 500 else "Receiver"}</Type>'
+ f'<Code>{code}</Code><Message>{message}</Message></Error>'
f'<RequestId>{new_uuid()}</RequestId>'
f'</ErrorResponse>'
).encode("utf-8")
diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.py
index 2f65045b..25170e5e 100644
--- a/ministack/services/autoscaling.py
+++ b/ministack/services/autoscaling.py
@@ -145,8 +145,15 @@ def _xml(status, root_tag, inner):
def _error(code, message, status=400):
- return _xml(status, "ErrorResponse",
- f'<Error><Type>Sender</Type><Code>{code}</Code><Message>{message}</Message></Error>')
+ # Query-protocol error envelope per real-AWS captures (17-region
+ # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx),
+ # <RequestId> as a direct child, and no <?xml?> declaration.
+ fault_type = "Sender" if status < 500 else "Receiver"
+ body = (f'<ErrorResponse xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/">'
+ f'<Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>'
+ f'<RequestId>{new_uuid()}</RequestId>'
+ f'</ErrorResponse>').encode("utf-8")
+ return status, {"Content-Type": "application/xml"}, body
def _asg_arn(name):
diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.py
index b2bd2139..d1aa7eaf 100644
--- a/ministack/services/cloudformation/helpers.py
+++ b/ministack/services/cloudformation/helpers.py
@@ -46,9 +46,10 @@ def _xml(status, root_tag, inner):
def _error(code, message, status=400):
+ # Query-protocol error envelope per real-AWS captures (17-region
+ # sweep): <Type> inside <Error> and no <?xml?> declaration.
t = "Sender" if status < 500 else "Receiver"
body = (
- f'<?xml version="1.0" encoding="UTF-8"?>'
f'<ErrorResponse xmlns="{CFN_NS}">'
f'<Error><Type>{t}</Type><Code>{code}</Code>'
f'<Message>{_esc(message)}</Message></Error>'
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index 923190e1..91a2a1e6 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -314,8 +314,12 @@ def _xml_response(root_tag: str, builder_fn, status: int = 200, extra_headers: d
def _error(code: str, message: str, status: int) -> tuple:
+ # rest-xml error envelope per real-AWS captures (17-region sweep):
+ # <?xml?> declaration present and <Type> inside <Error> (Sender for
+ # 4xx, Receiver for 5xx).
root = Element("ErrorResponse", xmlns=NS)
err = SubElement(root, "Error")
+ SubElement(err, "Type").text = "Sender" if status < 500 else "Receiver"
SubElement(err, "Code").text = code
SubElement(err, "Message").text = message
SubElement(root, "RequestId").text = new_uuid()
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index f87a8358..1c730d08 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -1853,10 +1853,13 @@ def _error(code, message, status, use_json=False, use_cbor=False):
{"Content-Type": "application/x-amz-json-1.0", "x-amzn-errortype": code},
json.dumps({"__type": code, "message": message}).encode(),
)
+ # Query-protocol error envelope per real-AWS captures (17-region
+ # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx)
+ # and no <?xml?> declaration.
+ fault_type = "Sender" if status < 500 else "Receiver"
body = (
- f'<?xml version="1.0" encoding="UTF-8"?>\n'
f'<ErrorResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">\n'
- f" <Error><Code>{code}</Code><Message>{message}</Message></Error>\n"
+ f" <Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>\n"
f" <RequestId>{new_uuid()}</RequestId>\n"
f"</ErrorResponse>"
).encode("utf-8")
diff --git a/ministack/services/documentdb.py b/ministack/services/documentdb.py
index 23f70707..bafce5d0 100644
--- a/ministack/services/documentdb.py
+++ b/ministack/services/documentdb.py
@@ -1694,9 +1694,10 @@ def _xml(status, root_tag, inner):
def _error(code, message, status):
"""Build an RDS-style XML error response."""
+ # Real AWS Query-protocol error envelopes carry <Type>Sender|Receiver
+ # </Type> and no <?xml?> declaration (17-region capture sweep).
fault_type = "Sender" if 400 <= status < 500 else "Receiver"
- body = f"""<?xml version="1.0" encoding="UTF-8"?>
-<ErrorResponse xmlns="http://rds.amazonaws.com/doc/2014-10-31/">
+ body = f"""<ErrorResponse xmlns="http://rds.amazonaws.com/doc/2014-10-31/">
<Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>
<RequestId>{new_uuid()}</RequestId>
</ErrorResponse>""".encode("utf-8")
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.py
index 37b8d3ce..348231cd 100644
--- a/ministack/services/elasticache.py
+++ b/ministack/services/elasticache.py
@@ -3052,9 +3052,12 @@ def _xml(status, root_tag, inner):
def _error(code, message, status):
- body = f"""<?xml version="1.0" encoding="UTF-8"?>
-<ErrorResponse xmlns="http://elasticache.amazonaws.com/doc/2015-02-02/">
- <Error><Code>{code}</Code><Message>{message}</Message></Error>
+ # Query-protocol error envelope per real-AWS captures (17-region
+ # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx)
+ # and no <?xml?> declaration.
+ fault_type = "Sender" if 400 <= status < 500 else "Receiver"
+ body = f"""<ErrorResponse xmlns="http://elasticache.amazonaws.com/doc/2015-02-02/">
+ <Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>
<RequestId>{new_uuid()}</RequestId>
</ErrorResponse>""".encode("utf-8")
return status, {"Content-Type": "application/xml"}, body
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index ba862725..0bfcaa75 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -3196,9 +3196,12 @@ def _error(status, code, message, ns="iam"):
"iam": "https://iam.amazonaws.com/doc/2010-05-08/",
"sts": "https://sts.amazonaws.com/doc/2011-06-15/",
}.get(ns, "")
- body = (f'<?xml version="1.0" encoding="UTF-8"?>'
- f'<ErrorResponse xmlns="{ns_url}">'
- f'<Error><Code>{code}</Code><Message>{message}</Message></Error>'
+ # Query-protocol error envelope per real-AWS captures (17-region
+ # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx)
+ # and no <?xml?> declaration.
+ fault_type = "Sender" if status < 500 else "Receiver"
+ body = (f'<ErrorResponse xmlns="{ns_url}">'
+ f'<Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>'
f'<RequestId>{new_uuid()}</RequestId>'
f'</ErrorResponse>').encode("utf-8")
return status, {"Content-Type": "application/xml"}, body
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 120bd31a..2fa3da38 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -11253,12 +11253,13 @@ def _xml(status, root_tag, inner):
def _error(code, message, status):
- # Real AWS Query-protocol responses include <Type>Sender|Receiver</Type>
- # — Sender for 4xx (caller's fault), Receiver for 5xx. Most SDKs ignore
- # this field but it's part of the documented AWS shape.
+ # Real AWS Query-protocol error envelopes include
+ # <Type>Sender|Receiver</Type> — Sender for 4xx (caller's fault),
+ # Receiver for 5xx — and carry no <?xml?> declaration (17-region
+ # real-AWS capture sweep). Most SDKs ignore the field but it's part
+ # of the observed AWS shape.
fault_type = "Sender" if 400 <= status < 500 else "Receiver"
- body = f"""<?xml version="1.0" encoding="UTF-8"?>
-<ErrorResponse xmlns="http://rds.amazonaws.com/doc/2014-10-31/">
+ body = f"""<ErrorResponse xmlns="http://rds.amazonaws.com/doc/2014-10-31/">
<Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error>
<RequestId>{new_uuid()}</RequestId>
</ErrorResponse>""".encode("utf-8")
diff --git a/ministack/services/ses.py b/ministack/services/ses.py
index b80f2211..fa7775a7 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -1412,12 +1412,14 @@ def _xml(status, root_tag, inner):
def _error(code, message, status, error_type="", fields=None):
- type_xml = f"<Type>{error_type}</Type>" if error_type else ""
+ # Query-protocol error envelope per real-AWS captures (17-region
+ # sweep): <Type> inside <Error> (Sender for 4xx, Receiver for 5xx —
+ # callers may pin an explicit value) and no <?xml?> declaration.
+ error_type = error_type or ("Sender" if status < 500 else "Receiver")
message_xml = f"<Message>{_esc(message)}</Message>" if message is not None else ""
message_xml += "".join(f"<{k}>{_esc(v)}</{k}>" for k, v in (fields or {}).items())
- body = (f'<?xml version="1.0" encoding="UTF-8"?>'
- f'<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">'
- f'<Error>{type_xml}<Code>{code}</Code>{message_xml}</Error>'
+ body = (f'<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">'
+ f'<Error><Type>{error_type}</Type><Code>{code}</Code>{message_xml}</Error>'
f'<RequestId>{new_uuid()}</RequestId>'
f'</ErrorResponse>').encode("utf-8")
return status, {"Content-Type": "application/xml"}, body
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index e2aefb6e..b3db24ed 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -132,10 +132,14 @@ def _get_topic(topic_arn: str, action: str | None = None):
Returns ``(topic, None)`` on success or ``(None, error_tuple)`` with a
``NotFound`` (404) or ``AuthorizationError`` (403) response.
+ ``not_found_error`` overrides the NotFound response for the APIs where
+ real AWS evaluates authorization before existence.
"""
arn = _normalize_arn(topic_arn)
topic = _topic_by_arn_any_scope(arn)
if topic is None:
+ if not_found_error is not None:
+ return None, not_found_error
return None, _error("NotFound", f"Topic does not exist: {arn}", 404)
if action is not None:
denied = _enforce_topic_policy(topic, action)
@@ -487,7 +491,16 @@ def _list_topics(params):
def _get_topic_attributes(params):
- topic, err = _get_topic(_p(params, "TopicArn"), "sns:GetTopicAttributes")
+ # Real AWS evaluates authorization before existence on this API:
+ # GetTopicAttributes on a nonexistent topic answers
+ # InvalidClientTokenId at 403, not NotFound/404 (real AWS wire
+ # capture). Neighboring topic APIs were not captured, so they keep
+ # their existing NotFound/404 ordering.
+ topic, err = _get_topic(
+ _p(params, "TopicArn"), "sns:GetTopicAttributes",
+ not_found_error=_error(
+ "InvalidClientTokenId",
+ "The security token included in the request is invalid.", 403))
if err is not None:
return err
_refresh_subscription_counts(topic)
@@ -1674,9 +1687,10 @@ def _xml(status, root_tag, inner):
def _error(code, message, status):
+ # Query-protocol error envelope per real-AWS captures (17-region
+ # sweep): <Type> inside <Error> and no <?xml?> declaration.
error_type = "Sender" if status < 500 else "Receiver"
body = (
- f'<?xml version="1.0" encoding="UTF-8"?>'
f'<ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">'
f'<Error><Type>{error_type}</Type><Code>{code}</Code><Message>{_xml_escape(message)}</Message></Error>'
f'<RequestId>{new_uuid()}</RequestId>'
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 0e42583f..617582ea 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -515,9 +515,15 @@ def _describe_state_machine(data):
"loggingConfiguration": base_sm.get("loggingConfiguration", {"level": "OFF"}),
"revisionId": base_sm.get("revisionId", ""),
})
+ # Real AWS evaluates authorization before existence on
+ # DescribeStateMachine: a stateMachineArn that resolves to nothing
+ # (no machine, version, or alias) answers AccessDeniedException, not
+ # StateMachineDoesNotExist (real AWS wire capture; also the API
+ # reference's error list). Other lookups were not captured and keep
+ # StateMachineDoesNotExist.
return error_response_json(
- "StateMachineDoesNotExist",
- f"State machine {arn} not found", 400)
+ "AccessDeniedException",
+ "User is not authorized to access this resource.", 400)
def _update_state_machine(data):
diff --git a/tests/test_ministack.py b/tests/test_ministack.py
index 2d9108cb..741024b1 100644
--- a/tests/test_ministack.py
+++ b/tests/test_ministack.py
@@ -1061,7 +1061,9 @@ def test_drop_containers_logs_the_ids_it_could_not_remove(caplog):
from ministack.core.responses import ( # noqa: E402
expected_error_content_type,
+ expected_success_content_type,
fix_error_content_type,
+ fix_success_content_type,
)
from ministack.core.router import detect_service # noqa: E402
@@ -1122,8 +1124,7 @@ def test_fix_error_content_type_scopes():
fix_error_content_type("kinesis", 400, headers)
assert headers["Content-Type"] == "application/x-amz-json-1.1"
- # success responses are never rewritten — an S3 object that happens to
- # be JSON must keep its real content type.
+ # success responses are never rewritten by the error path
headers = {"Content-Type": "application/json"}
fix_error_content_type("s3", 200, headers)
assert headers["Content-Type"] == "application/json"
@@ -1137,6 +1138,82 @@ def test_fix_error_content_type_scopes():
assert headers["Content-Type"] == "application/xml"
[email protected]("service,emitted,expected", [
+ # query successes answer text/xml; ec2 adds charset.
+ ("iam", "application/xml", "text/xml"),
+ ("sns", "application/xml", "text/xml"),
+ ("cloudformation", "application/xml", "text/xml"),
+ ("elasticloadbalancing", "application/xml", "text/xml"),
+ ("ec2", "application/xml", "text/xml;charset=UTF-8"),
+ # json successes follow the model's jsonVersion.
+ ("dynamodb", "application/json", "application/x-amz-json-1.0"),
+ ("dynamodb", "application/x-amz-json-1.1", "application/x-amz-json-1.0"),
+ ("kinesis", "application/x-amz-json-1.0", "application/x-amz-json-1.1"),
+ ("sqs", "application/json", "application/x-amz-json-1.0"),
+ # rest-json answers application/json.
+ ("lambda", "application/x-amz-json-1.0", "application/json"),
+ ("apigateway", "application/x-amz-json-1.0", "application/json"),
+ # sesv2's x-amz-json-1.1 override is error-path evidence only — its
+ # successes get the rest-json model value like any other service.
+ ("sesv2", "application/x-amz-json-1.0", "application/json"),
+ ("sesv2", "application/json", "application/json"),
+ # monitoring serves a query-compatible JSON mode AWS answers as
+ # x-amz-json-1.0 (success override); its XML query path still maps
+ # to the model's text/xml below.
+ ("monitoring", "application/json", "application/x-amz-json-1.0"),
+ ("monitoring", "application/xml", "text/xml"),
+ # rest-xml answers text/xml — except S3, which keeps application/xml.
+ ("route53", "application/xml", "text/xml"),
+ ("cloudfront", "application/xml", "text/xml"),
+ ("s3", "application/xml", "application/xml"),
+])
+def test_expected_success_content_type(service, emitted, expected):
+ assert expected_success_content_type(service, emitted) == expected
+
+
[email protected]("service,emitted", [
+ # An emitted text/xml is already wire-final: correct on API envelopes
+ # (route53/cloudfront/alb) and payload on e.g. a stored S3 object.
+ ("s3", "text/xml"),
+ ("route53", "text/xml"),
+ ("iam", "text/xml"),
+ ("ec2", "text/xml"),
+ # A stored S3 object's JSON or binary Content-Type is payload.
+ ("s3", "application/json"),
+ ("s3", "application/octet-stream"),
+ ("dynamodb", "application/octet-stream"),
+ ("iam", "text/plain"),
+ # Unknown service — nothing evidence-backed to enforce.
+ ("not-a-service", "application/xml"),
+ # An XML body from a json-protocol service has no modeled answer.
+ ("sqs", "application/xml"),
+])
+def test_expected_success_content_type_untouched(service, emitted):
+ assert expected_success_content_type(service, emitted) is None
+
+
+def test_fix_success_content_type_scopes():
+ headers = {"Content-Type": "application/xml"}
+ fix_success_content_type("iam", 200, headers)
+ assert headers["Content-Type"] == "text/xml"
+
+ # errors are never rewritten by the success path
+ headers = {"Content-Type": "application/xml"}
+ fix_success_content_type("iam", 400, headers)
+ assert headers["Content-Type"] == "application/xml"
+
+ # a stored S3 object's text/xml payload is not corrupted to the
+ # envelope value
+ headers = {"Content-Type": "text/xml"}
+ fix_success_content_type("s3", 200, headers)
+ assert headers["Content-Type"] == "text/xml"
+
+ # non-envelope payloads are untouched
+ headers = {"Content-Type": "application/octet-stream"}
+ fix_success_content_type("dynamodb", 200, headers)
+ assert headers["Content-Type"] == "application/octet-stream"
+
+
@pytest.mark.parametrize("scope", ["glacier", "pinpoint", "route53resolver"])
def test_unimplemented_real_service_surfaces_by_name(scope):
# A request signed for a real AWS service ministack does not implement
diff --git a/tests/test_ses_v2.py b/tests/test_ses_v2.py
index 43e0daf1..cf4debcf 100644
--- a/tests/test_ses_v2.py
+++ b/tests/test_ses_v2.py
@@ -745,7 +745,11 @@ def _tenant_error(client, operation, code, message, **params):
with pytest.raises(ClientError) as caught:
getattr(client, operation)(**params)
response = caught.value.response
- assert response["Error"] == {"Code": code, "Message": message}
+ # SES v1 speaks the query protocol, whose error envelope carries an
+ # additive <Type> member real AWS also sends — compare the fields the
+ # test means to pin rather than the whole dict.
+ assert response["Error"]["Code"] == code
+ assert response["Error"]["Message"] == message
assert response["ResponseMetadata"]["HTTPStatusCode"] == (404 if code == "NotFoundException" else 400)
diff --git a/tests/test_sns.py b/tests/test_sns.py
index 4836e1fc..49e42853 100644
--- a/tests/test_sns.py
+++ b/tests/test_sns.py
@@ -79,9 +79,14 @@ def test_sns_topics_are_region_scoped_by_name(sns):
assert west_arn in west_arns
assert east_arn not in west_arns
+ # Real AWS evaluates authorization before existence on
+ # GetTopicAttributes: a topic arn that does not exist in this region
+ # answers InvalidClientTokenId/403, not NotFound/404 (real-AWS
+ # capture).
with pytest.raises(ClientError) as exc:
sns.get_topic_attributes(TopicArn=west_arn)
- assert exc.value.response["Error"]["Code"] == "NotFound"
+ assert exc.value.response["Error"]["Code"] == "InvalidClientTokenId"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
def test_sns_set_topic_attributes(sns):
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 42ddf46f..e3c0d65b 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -105,9 +105,13 @@ def test_sfn_state_machines_are_region_scoped():
assert west_sm["stateMachineArn"] in west_arns
assert west_sm["stateMachineArn"] not in east_arns
+ # Real AWS evaluates authorization before existence on
+ # DescribeStateMachine: an arn that does not exist in this region
+ # answers AccessDeniedException, not StateMachineDoesNotExist
+ # (real-AWS capture).
with pytest.raises(ClientError) as exc:
west.describe_state_machine(stateMachineArn=east_sm["stateMachineArn"])
- assert exc.value.response["Error"]["Code"] == "StateMachineDoesNotExist"
+ assert exc.value.response["Error"]["Code"] == "AccessDeniedException"
def test_sfn_executions_are_region_scoped():
@@ -5524,13 +5528,15 @@ def test_sfn_create_idempotency_covers_version_description(sfn):
def test_sfn_describe_not_found(sfn):
- """DescribeStateMachine on non-existent ARN should fail."""
+ """DescribeStateMachine on a non-existent ARN: real AWS evaluates
+ authorization before existence and answers AccessDeniedException
+ (real-AWS capture), not StateMachineDoesNotExist."""
with pytest.raises(ClientError) as exc:
sfn.describe_state_machine(stateMachineArn="arn:aws:states:us-east-1:000000000000:stateMachine:nonexistent-99")
err = exc.value.response["Error"]["Code"]
- assert "StateMachineDoesNotExist" in err or "NotFound" in err or "ResourceNotFound" in err
+ assert err == "AccessDeniedException"
# Real AWS sends `x-amzn-errortype` on JSON-protocol errors; Java/Go SDK v2 read it.
- assert exc.value.response["ResponseMetadata"]["HTTPHeaders"].get("x-amzn-errortype") == "StateMachineDoesNotExist"
+ assert exc.value.response["ResponseMetadata"]["HTTPHeaders"].get("x-amzn-errortype") == "AccessDeniedException"
def test_sfn_start_execution_not_found(sfn):
"""StartExecution on non-existent SM should fail."""
diff --git a/tests/test_wire_envelopes.py b/tests/test_wire_envelopes.py
new file mode 100644
index 00000000..058be9e9
--- /dev/null
+++ b/tests/test_wire_envelopes.py
@@ -0,0 +1,285 @@
+"""Wire-fidelity assertions on response envelopes (issue #2128).
+
+Expected values are real AWS observations, not model guesses:
+
+- Error envelope shape comes from a 17-region capture sweep: the query
+ family (sns/iam/sts/rds/elbv2/cloudformation/...) carries ``<Type>``
+ inside ``<Error>`` and no ``<?xml?>`` declaration; ec2 carries the
+ declaration, no ``<Type>``, and ``text/xml;charset=UTF-8``; rest-xml
+ carries both the declaration and ``<Type>``.
+- Success Content-Types were verified across
+ us-east-1/us-west-2/eu-west-1/ap-southeast-2: query -> ``text/xml``,
+ ec2 -> ``text/xml;charset=UTF-8``, json -> ``application/x-amz-json-
+ 1.{jsonVersion}``, rest-json -> ``application/json``, rest-xml ->
+ ``application/xml`` (s3) or ``text/xml`` (route53).
+
+These tests run the enduser surface: boto3 clients against the live
+server, asserting exactly what an SDK caller parses back.
+"""
+
+import os
+import urllib.error
+import urllib.request
+
+import pytest
+from botocore.exceptions import ClientError
+
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+
+def _ct(resp):
+ """Response Content-Type as botocore exposes it (HTTPHeaderDict is
+ case-insensitive)."""
+ return resp["ResponseMetadata"]["HTTPHeaders"]["content-type"]
+
+
+def _status(err):
+ return err["ResponseMetadata"]["HTTPStatusCode"]
+
+
+# ---------------------------------------------------------------------------
+# Query-protocol error envelopes: <Type> inside <Error>, text/xml
+# ---------------------------------------------------------------------------
+
+
+def test_iam_query_error_envelope(iam):
+ with pytest.raises(ClientError) as exc:
+ iam.get_user(UserName="wire-missing-user")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "NoSuchEntity"
+ assert err["Error"]["Type"] == "Sender"
+ assert _status(err) == 404
+ assert _ct(err) == "text/xml"
+
+
+def test_sns_query_error_envelope(sns):
+ # set_topic_attributes was not part of the captured auth-ordering
+ # change, so it keeps its NotFound/404 on a missing topic — but the
+ # envelope still carries the query family's <Type>Sender</Type>.
+ with pytest.raises(ClientError) as exc:
+ sns.set_topic_attributes(
+ TopicArn="arn:aws:sns:us-east-1:000000000000:wire-missing",
+ AttributeName="DisplayName",
+ AttributeValue="x",
+ )
+ err = exc.value.response
+ assert err["Error"]["Code"] == "NotFound"
+ assert err["Error"]["Type"] == "Sender"
+ assert _ct(err) == "text/xml"
+
+
+def test_elbv2_query_error_envelope(elbv2):
+ with pytest.raises(ClientError) as exc:
+ elbv2.describe_load_balancers(Names=["wire-missing"])
+ err = exc.value.response
+ assert err["Error"]["Code"] == "LoadBalancerNotFound"
+ assert err["Error"]["Type"] == "Sender"
+ assert _ct(err) == "text/xml"
+
+
+def test_autoscaling_query_error_envelope(autoscaling):
+ with pytest.raises(ClientError) as exc:
+ autoscaling.update_auto_scaling_group(
+ AutoScalingGroupName="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "ValidationError"
+ assert err["Error"]["Type"] == "Sender"
+ assert _ct(err) == "text/xml"
+
+
+def test_elasticache_query_error_envelope(ec):
+ with pytest.raises(ClientError) as exc:
+ ec.describe_cache_clusters(CacheClusterId="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "CacheClusterNotFound"
+ assert err["Error"]["Type"] == "Sender"
+ assert _ct(err) == "text/xml"
+
+
+def test_rds_query_error_envelope(rds):
+ with pytest.raises(ClientError) as exc:
+ rds.describe_db_instances(DBInstanceIdentifier="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "DBInstanceNotFound"
+ assert err["Error"]["Type"] == "Sender"
+ assert _status(err) == 404
+ assert _ct(err) == "text/xml"
+
+
+def test_docdb_query_error_envelope(docdb):
+ with pytest.raises(ClientError) as exc:
+ docdb.describe_db_instances(DBInstanceIdentifier="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Type"] == "Sender"
+ assert _ct(err) == "text/xml"
+
+
+def test_cloudwatch_query_error_envelope():
+ # boto3 1.42+ speaks smithy-rpc-v2-cbor to CloudWatch, so the legacy
+ # Query API path is exercised with a raw form-encoded request — the
+ # shape an XML-mode client still parses.
+ req = urllib.request.Request(
+ f"{ENDPOINT}/",
+ data=b"Action=GetDashboard&Version=2010-08-01&DashboardName=wire-missing",
+ headers={
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/"
+ "us-east-1/monitoring/aws4_request, "
+ "SignedHeaders=host, Signature=x",
+ },
+ )
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ urllib.request.urlopen(req)
+ http_err = exc.value
+ body = http_err.read().decode()
+ assert http_err.headers["content-type"] == "text/xml"
+ # Query family: <Type> inside <Error>, no <?xml?> declaration.
+ assert not body.startswith("<?xml")
+ assert "<Type>Sender</Type>" in body
+ assert "ResourceNotFound" in body
+
+
+def test_ses_query_error_envelope(ses):
+ with pytest.raises(ClientError) as exc:
+ ses.describe_receipt_rule_set(RuleSetName="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "RuleSetDoesNotExist"
+ assert err["Error"]["Type"] == "Sender"
+ assert _ct(err) == "text/xml"
+
+
+def test_cfn_query_error_envelope(cfn):
+ with pytest.raises(ClientError) as exc:
+ cfn.describe_stacks(StackName="wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "ValidationError"
+ assert err["Error"]["Type"] == "Sender"
+ assert _ct(err) == "text/xml"
+
+
+# ---------------------------------------------------------------------------
+# Non-query envelopes: ec2 keeps its shape, rest-xml keeps <Type>
+# ---------------------------------------------------------------------------
+
+
+def test_ec2_error_envelope_has_no_type_and_charset(ec2):
+ with pytest.raises(ClientError) as exc:
+ ec2.describe_instances(InstanceIds=["i-0123456789abcdef0"])
+ err = exc.value.response
+ assert err["Error"]["Code"] == "InvalidInstanceID.NotFound"
+ # ec2 errors carry no <Type> on the real wire (0/17 captures).
+ assert err["Error"].get("Type") is None
+ assert _ct(err) == "text/xml;charset=UTF-8"
+
+
+def test_route53_restxml_error_envelope(r53):
+ with pytest.raises(ClientError) as exc:
+ r53.get_hosted_zone(Id="/hostedzone/ZWIREMISSING000")
+ err = exc.value.response
+ assert err["Error"]["Type"] == "Sender"
+ assert _ct(err) == "text/xml"
+
+
+# ---------------------------------------------------------------------------
+# Success Content-Types per protocol family
+# ---------------------------------------------------------------------------
+
+
+def test_query_success_content_types(iam, sns, sts, ec, autoscaling,
+ elbv2, ses, rds, docdb, cfn):
+ calls = [
+ (iam.list_users, {}),
+ (sns.list_topics, {}),
+ (sts.get_caller_identity, {}),
+ (ec.describe_cache_clusters, {}),
+ (autoscaling.describe_auto_scaling_groups, {}),
+ (elbv2.describe_load_balancers, {}),
+ (ses.list_identities, {}),
+ (rds.describe_db_instances, {}),
+ (docdb.describe_db_instances, {}),
+ (cfn.list_stacks, {}),
+ ]
+ for call, kwargs in calls:
+ assert _ct(call(**kwargs)) == "text/xml", call.__name__
+
+
+def test_cloudwatch_query_success_content_type():
+ # Raw Query API request — see test_cloudwatch_query_error_envelope.
+ req = urllib.request.Request(
+ f"{ENDPOINT}/",
+ data=b"Action=ListMetrics&Version=2010-08-01",
+ headers={
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/"
+ "us-east-1/monitoring/aws4_request, "
+ "SignedHeaders=host, Signature=x",
+ },
+ )
+ with urllib.request.urlopen(req) as resp:
+ assert resp.headers["content-type"] == "text/xml"
+
+
+def test_json_success_content_types(ddb, sqs, kin):
+ # jsonVersion comes from the botocore service model (dynamodb/sqs are
+ # 1.0, kinesis is 1.1) — matching what real AWS puts on the wire.
+ assert _ct(ddb.list_tables()) == "application/x-amz-json-1.0"
+ assert _ct(sqs.list_queues()) == "application/x-amz-json-1.0"
+ assert _ct(kin.list_streams()) == "application/x-amz-json-1.1"
+
+
+def test_restxml_success_content_types(s3, r53):
+ assert _ct(s3.list_buckets()) == "application/xml"
+ assert _ct(r53.list_hosted_zones()) == "text/xml"
+
+
+def test_restjson_success_content_type(lam):
+ assert _ct(lam.list_functions()) == "application/json"
+
+
+def test_ec2_success_content_type(ec2):
+ assert _ct(ec2.describe_regions()) == "text/xml;charset=UTF-8"
+
+
+def test_s3_object_payload_content_type_not_rewritten(s3):
+ # A stored object's Content-Type is payload, not an envelope — the
+ # success fixer must not rewrite text/xml into the s3 envelope value.
+ bucket = "wire-ct-payload"
+ s3.create_bucket(Bucket=bucket)
+ try:
+ s3.put_object(Bucket=bucket, Key="doc.xml", Body=b"<a/>",
+ ContentType="text/xml")
+ resp = s3.get_object(Bucket=bucket, Key="doc.xml")
+ assert _ct(resp) == "text/xml"
+ finally:
+ s3.delete_object(Bucket=bucket, Key="doc.xml")
+ s3.delete_bucket(Bucket=bucket)
+
+
+# ---------------------------------------------------------------------------
+# Per-service error-code ordering (real AWS captures)
+# ---------------------------------------------------------------------------
+
+
+def test_sfn_describe_state_machine_authz_before_existence(sfn):
+ # Real AWS evaluates authorization before existence: a nonexistent
+ # arn answers AccessDeniedException, not StateMachineDoesNotExist.
+ with pytest.raises(ClientError) as exc:
+ sfn.describe_state_machine(
+ stateMachineArn="arn:aws:states:us-east-1:000000000000:"
+ "stateMachine:wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "AccessDeniedException"
+ assert _status(err) == 400
+
+
+def test_sns_get_topic_attributes_auth_before_existence(sns):
+ # Real AWS answers InvalidClientTokenId 403 on a nonexistent topic —
+ # auth is evaluated before existence (real-AWS capture).
+ with pytest.raises(ClientError) as exc:
+ sns.get_topic_attributes(
+ TopicArn="arn:aws:sns:us-east-1:000000000000:wire-missing")
+ err = exc.value.response
+ assert err["Error"]["Code"] == "InvalidClientTokenId"
+ assert err["Error"]["Type"] == "Sender"
+ assert _status(err) == 403
+ assert _ct(err) == "text/xml"