Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(warehouse-sources): explain an SES error that has no message (#98511)

posthog[bot]cc6c24314898
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.py
index 9e073d68e3ac..1349214e6a98 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.py
@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.se
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import BoundedRetry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.url_utils import scrub_url
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -42,6 +43,18 @@ _CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
_IAM_ACTION_PATTERN = re.compile(r"ses:[A-Za-z0-9]+")
+# SESv2 declares BadRequestException with zero members, so the response carries no `message`.
+_BAD_REQUEST_EXPLANATION = (
+ "Amazon SES rejected the request and gave no reason. "
+ "This table might not be available in the AWS region this source is connected to."
+)
+
+# Codes AWS can answer with when a saved pagination token is no longer accepted. Only
+# ListSuppressedDestinations models InvalidNextTokenException; the other list operations report
+# a rejected NextToken as BadRequestException, the same code a region that cannot serve the
+# table returns.
+_STALE_TOKEN_ERROR_CODES = ("InvalidNextTokenException", "BadRequestException")
+
# Codes that mean the key itself is bad, as opposed to a valid key missing an IAM permission.
_CREDENTIAL_ERROR_CODES = (
"UnrecognizedClientException",
@@ -53,7 +66,13 @@ _CREDENTIAL_ERROR_CODES = (
class AwsSesError(Exception):
- pass
+ def __init__(self, code: str, message: str, endpoint: str, path: str) -> None:
+ # A verified SES identity can be an email address, and the fan-out puts it in the detail
+ # path. This message reaches the job log and the stored error, so mask the address the
+ # same way the tracked transport masks a recorded URL.
+ super().__init__(f"Amazon SES request failed: {code} - {message} (table {endpoint}, GET {scrub_url(path)})")
+ self.code = code
+ self.message = message
@dataclasses.dataclass(frozen=True)
@@ -129,29 +148,37 @@ def normalize_row(endpoint_config: AwsSesEndpointConfig, obj: dict[str, Any]) ->
return row
-def _error_code(response: requests.Response) -> str:
+def _error_code(response: requests.Response, body: dict[str, Any]) -> str:
header = response.headers.get("x-amzn-ErrorType") or ""
if header:
return header.split(":")[0].split("#")[-1]
- try:
- body = response.json()
- except ValueError:
- return f"HTTP {response.status_code}"
raw = body.get("__type") or body.get("code") or f"HTTP {response.status_code}"
return str(raw).split("#")[-1]
-def _error_message(response: requests.Response) -> str:
- try:
- body = response.json()
- except ValueError:
- return response.text[:500]
+def _error_message(response: requests.Response, body: dict[str, Any], code: str) -> str:
message = body.get("message") or body.get("Message") or ""
- return str(message)[:500]
+ if message:
+ return str(message)[:500]
+ if code == "BadRequestException":
+ return _BAD_REQUEST_EXPLANATION
+ return f"Amazon SES returned HTTP {response.status_code} with no message."
-def error_for_response(response: requests.Response) -> AwsSesError:
- return AwsSesError(f"Amazon SES request failed: {_error_code(response)} - {_error_message(response)}")
+def error_for_response(response: requests.Response, endpoint: str, path: str) -> AwsSesError:
+ try:
+ parsed = response.json()
+ except ValueError:
+ parsed = None
+ body = parsed if isinstance(parsed, dict) else {}
+ code = _error_code(response, body)
+ # A body that is not JSON carries the message as text, unless there is no text at all. A
+ # zero-member exception model constrains the members, not the wire body, so a bodyless
+ # response has to reach the explanation rather than trail off after the dash.
+ text = "" if isinstance(parsed, dict) else response.text.strip()
+ if text:
+ return AwsSesError(code, text[:500], endpoint, path)
+ return AwsSesError(code, _error_message(response, body, code), endpoint, path)
def make_session(secret_access_key: str, session_token: Optional[str]) -> requests.Session:
@@ -163,6 +190,7 @@ def send_request(
session: requests.Session,
credentials: Credentials,
region: str,
+ endpoint: str,
path: str,
params: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
@@ -178,7 +206,7 @@ def send_request(
response = session.get(url, headers=dict(aws_request.headers.items()), timeout=REQUEST_TIMEOUT_SECONDS)
if response.status_code >= 400:
- raise error_for_response(response)
+ raise error_for_response(response, endpoint, path)
return response.json()
@@ -212,10 +240,14 @@ def _fanout_page_rows(
try:
detail = send_request(
- session, credentials, region, endpoint_config.detail_path.format(name=quote(name, safe=""))
+ session,
+ credentials,
+ region,
+ endpoint_config.name,
+ endpoint_config.detail_path.format(name=quote(name, safe="")),
)
except AwsSesError as error:
- if "NotFoundException" in str(error):
+ if error.code == "NotFoundException":
logger.debug(f"Skipping {endpoint_config.name} item deleted mid-sync. name={name}")
continue
raise
@@ -250,11 +282,13 @@ def _walk_pages(
page_params["NextToken"] = next_token
try:
- body = send_request(session, credentials, region, endpoint_config.path, page_params)
+ body = send_request(session, credentials, region, endpoint_config.name, endpoint_config.path, page_params)
except AwsSesError as error:
# A token saved by a previous attempt can expire; restart the walk instead of
- # failing the job. Merge on the primary key absorbs the re-read rows.
- if resumed_token and "InvalidNextTokenException" in str(error):
+ # failing the job. Merge on the primary key absorbs the re-read rows. The restart
+ # runs once per walk, so a table the region really cannot serve fails on the
+ # retry from page 1 and still reaches the non-retryable classification.
+ if resumed_token and error.code in _STALE_TOKEN_ERROR_CODES:
logger.debug(f"Saved page token no longer valid; restarting. endpoint={endpoint_config.name}")
next_token = None
resumed_token = False
@@ -294,7 +328,12 @@ def get_rows(
credentials = Credentials(aws_access_key_id, aws_secret_access_key, aws_session_token or None)
if endpoint_config.page_size is None:
- yield [normalize_row(endpoint_config, send_request(session, credentials, region, endpoint_config.path))]
+ yield [
+ normalize_row(
+ endpoint_config,
+ send_request(session, credentials, region, endpoint_config.name, endpoint_config.path),
+ )
+ ]
return
params: dict[str, Any] = {"PageSize": endpoint_config.page_size}
@@ -314,14 +353,17 @@ def get_rows(
def _permission_reason(error: AwsSesError) -> Optional[str]:
- text = str(error)
- if "AccessDeniedException" in text:
- match = _IAM_ACTION_PATTERN.search(text)
+ if error.code == "AccessDeniedException":
+ match = _IAM_ACTION_PATTERN.search(error.message)
if match:
return f"Missing IAM permission {match.group(0)}"
return "The connected IAM user or role is not allowed to read this table"
- if any(code in text for code in _CREDENTIAL_ERROR_CODES):
+ if error.code in _CREDENTIAL_ERROR_CODES:
return "AWS rejected the access key. Please check the access key ID and secret access key."
+ if error.code == "BadRequestException":
+ # A 400 on the probe is deterministic, not a blip, so reporting it keeps the table out of
+ # the picker in a region that can never load it.
+ return _BAD_REQUEST_EXPLANATION
return None
@@ -338,16 +380,20 @@ def endpoint_permission_reason(
"""
try:
if endpoint_config.page_size is None:
- send_request(session, credentials, region, endpoint_config.path)
+ send_request(session, credentials, region, endpoint_config.name, endpoint_config.path)
return None
- body = send_request(session, credentials, region, endpoint_config.path, {"PageSize": 1})
+ body = send_request(session, credentials, region, endpoint_config.name, endpoint_config.path, {"PageSize": 1})
if endpoint_config.detail_path:
for item in (body.get(endpoint_config.result_key or "") or [])[:1]:
name = item.get(endpoint_config.item_name_key) if isinstance(item, dict) else item
if isinstance(name, str) and name:
send_request(
- session, credentials, region, endpoint_config.detail_path.format(name=quote(name, safe=""))
+ session,
+ credentials,
+ region,
+ endpoint_config.name,
+ endpoint_config.detail_path.format(name=quote(name, safe="")),
)
except AwsSesError as error:
return _permission_reason(error)
@@ -405,11 +451,12 @@ def validate_credentials(
return reason is None, reason
try:
- send_request(session, credentials, region, AWS_SES_ENDPOINTS["account"].path)
+ account = AWS_SES_ENDPOINTS["account"]
+ send_request(session, credentials, region, account.name, account.path)
except AwsSesError as error:
# A denied GetAccount still proves the key is genuine; per-table access is reported in
# the schema picker instead of blocking source creation.
- if "AccessDeniedException" in str(error):
+ if error.code == "AccessDeniedException":
return True, None
return False, str(error)
except Exception:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/source.py
index 4d4e91e92eed..5eed8c1aacd5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/source.py
@@ -59,6 +59,11 @@ class AwsSesSource(ResumableSource[AwsSesSourceConfig, AwsSesResumeConfig]):
"Amazon SES request failed: InvalidSignatureException": "AWS rejected the request signature. If you are using temporary credentials, the session token has expired.",
"Amazon SES request failed: ExpiredTokenException": "The AWS session token has expired. Please reconnect with fresh credentials.",
"Amazon SES request failed: AccessDeniedException": "These AWS credentials are missing SES read permissions. Grant ses:GetAccount, ses:ListConfigurationSets, ses:GetConfigurationSet, ses:ListEmailIdentities, ses:GetEmailIdentity, ses:ListSuppressedDestinations, ses:ListEmailTemplates, ses:GetEmailTemplate, ses:ListContactLists, ses:GetContactList, ses:ListDedicatedIpPools, ses:GetDedicatedIpPool, ses:GetDedicatedIps, ses:ListCustomVerificationEmailTemplates, ses:GetCustomVerificationEmailTemplate and ses:ListMultiRegionEndpoints to the IAM user or role.",
+ # No retry turns a 400 into rows. `None` keeps the raised message, which names the
+ # table; a fixed string here could not say which of the ten tables AWS rejected.
+ # A stale pagination token also surfaces as a 400, so the walk restarts itself once
+ # before one can reach this map.
+ "Amazon SES request failed: BadRequestException": None,
"Invalid AWS region": "Enter a valid AWS region code like us-east-1.",
"AWS access key ID and secret access key are required": "Enter both an AWS access key ID and a secret access key.",
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py
index 14ac10d7f93c..440530cbb5cc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py
@@ -153,7 +153,7 @@ class TestSendRequest:
credentials = Credentials("AKIAEXAMPLE", "secret")
with time_machine.travel("2026-08-07T10:00:00Z", tick=False):
- send_request(session, credentials, "eu-west-1", "/v2/email/account")
+ send_request(session, credentials, "eu-west-1", "account", "/v2/email/account")
assert session.get.call_args[0][0] == "https://email.eu-west-1.amazonaws.com/v2/email/account"
headers = session.get.call_args[1]["headers"]
@@ -170,6 +170,7 @@ class TestSendRequest:
session,
Credentials("key", "secret"),
"us-east-1",
+ "suppressed_destinations",
"/v2/email/suppression/addresses",
{"StartDate": "2026-08-01T00:00:00Z", "PageSize": 1000},
)
@@ -182,7 +183,9 @@ class TestSendRequest:
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = make_response(200, {})
- send_request(session, Credentials("key", "secret", "session-token"), "us-east-1", "/v2/email/account")
+ send_request(
+ session, Credentials("key", "secret", "session-token"), "us-east-1", "account", "/v2/email/account"
+ )
assert session.get.call_args[1]["headers"]["X-Amz-Security-Token"] == "session-token"
@@ -195,19 +198,54 @@ class TestErrorClassification:
headers={"x-amzn-ErrorType": "AccessDeniedException:http://internal.amazon.example/coral/"},
)
- assert str(error_for_response(response)) == "Amazon SES request failed: AccessDeniedException - denied"
+ assert str(error_for_response(response, "account", "/v2/email/account")) == (
+ "Amazon SES request failed: AccessDeniedException - denied (table account, GET /v2/email/account)"
+ )
def test_the_namespaced_body_type_is_stripped_to_the_bare_code(self) -> None:
response = make_response(400, {"__type": "com.amazonaws.ses#BadRequestException", "message": "bad"})
- assert str(error_for_response(response)) == "Amazon SES request failed: BadRequestException - bad"
+ assert str(error_for_response(response, "account", "/v2/email/account")) == (
+ "Amazon SES request failed: BadRequestException - bad (table account, GET /v2/email/account)"
+ )
+
+ # A zero-member exception model constrains the members, not the wire body, so SES can answer
+ # with an empty JSON object or with no bytes at all.
+ @pytest.mark.parametrize("content", [b"{}", b"", b" \n "])
+ def test_a_bodyless_bad_request_is_explained_instead_of_trailing_off_after_the_dash(self, content: bytes) -> None:
+ response = requests.Response()
+ response.status_code = 400
+ response.headers["x-amzn-ErrorType"] = "BadRequestException:http://internal.amazon.example/coral/"
+ response._content = content
+
+ message = str(error_for_response(response, "multi_region_endpoints", "/v2/email/multi-region-endpoints"))
+
+ assert f"BadRequestException - {aws_ses._BAD_REQUEST_EXPLANATION}" in message
+ assert message.endswith("(table multi_region_endpoints, GET /v2/email/multi-region-endpoints)")
+
+ def test_a_bodyless_error_that_is_not_a_bad_request_reports_its_status(self) -> None:
+ response = requests.Response()
+ response.status_code = 502
+ response._content = b""
+
+ assert "Amazon SES returned HTTP 502 with no message." in str(
+ error_for_response(response, "account", "/v2/email/account")
+ )
+
+ def test_an_email_identity_in_the_path_is_masked(self) -> None:
+ response = make_response(400, {"message": "bad"})
+
+ message = str(error_for_response(response, "email_identities", "/v2/email/identities/user%40example.com"))
+
+ assert message.endswith("(table email_identities, GET /v2/email/identities/{email})")
+ assert "example.com" not in message
def test_a_non_json_error_body_still_produces_a_usable_message(self) -> None:
response = requests.Response()
response.status_code = 503
response._content = b"<html>gateway</html>"
- assert "HTTP 503" in str(error_for_response(response))
+ assert "HTTP 503" in str(error_for_response(response, "account", "/v2/email/account"))
class TestResolveStartDate:
@@ -261,7 +299,7 @@ class TestGetRows:
assert batches == [[{"sending_enabled": True, "enforcement_status": "HEALTHY"}]]
assert send.call_count == 1
- assert send.call_args[0][3] == "/v2/email/account"
+ assert send.call_args[0][4] == "/v2/email/account"
def test_pagination_follows_next_token_until_aws_stops_returning_one(self) -> None:
batches, send, _ = self._run(
@@ -273,8 +311,8 @@ class TestGetRows:
assert [row["email_address"] for batch in batches for row in batch] == ["[email protected]", "[email protected]"]
assert batches[0][0]["last_update_time"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
- assert "NextToken" not in send.call_args_list[0][0][4]
- assert send.call_args_list[1][0][4]["NextToken"] == "page-2"
+ assert "NextToken" not in send.call_args_list[0][0][5]
+ assert send.call_args_list[1][0][5]["NextToken"] == "page-2"
def test_state_is_saved_after_each_page_and_cleared_once_the_walk_completes(self) -> None:
_, _, manager = self._run(
@@ -294,20 +332,20 @@ class TestGetRows:
)
assert send.call_count == 1
- assert send.call_args[0][4]["NextToken"] == "page-7"
+ assert send.call_args[0][5]["NextToken"] == "page-7"
def test_an_expired_saved_token_restarts_the_walk_instead_of_failing_the_job(self) -> None:
batches, send, manager = self._run(
[
- AwsSesError("Amazon SES request failed: InvalidNextTokenException - expired"),
+ AwsSesError("InvalidNextTokenException", "expired", "suppressed_destinations", "/path"),
suppression_page(["[email protected]"]),
],
manager=FakeResumeManager(AwsSesResumeConfig(next_token="stale")),
)
assert [row["email_address"] for batch in batches for row in batch] == ["[email protected]"]
- assert send.call_args_list[0][0][4].get("NextToken") == "stale"
- assert "NextToken" not in send.call_args_list[1][0][4]
+ assert send.call_args_list[0][0][5].get("NextToken") == "stale"
+ assert "NextToken" not in send.call_args_list[1][0][5]
assert manager.cleared is True
def test_an_invalid_token_from_aws_itself_is_not_swallowed(self) -> None:
@@ -316,10 +354,48 @@ class TestGetRows:
with pytest.raises(AwsSesError, match="InvalidNextTokenException"):
self._run(
[
- AwsSesError("Amazon SES request failed: InvalidNextTokenException - expired"),
- AwsSesError("Amazon SES request failed: InvalidNextTokenException - expired"),
+ AwsSesError("InvalidNextTokenException", "expired", "suppressed_destinations", "/path"),
+ AwsSesError("InvalidNextTokenException", "expired", "suppressed_destinations", "/path"),
+ ],
+ manager=FakeResumeManager(AwsSesResumeConfig(next_token="stale")),
+ )
+
+ def test_a_saved_token_rejected_as_a_bad_request_restarts_the_walk(self) -> None:
+ # Only ListSuppressedDestinations models a rejected token as InvalidNextTokenException.
+ # Every other list operation answers one with BadRequestException, which is otherwise
+ # classified as permanent and would disable a healthy table.
+ batches, send, manager = self._run(
+ [
+ AwsSesError("BadRequestException", "invalid", "multi_region_endpoints", "/path"),
+ {"MultiRegionEndpoints": [{"EndpointId": "e-1"}]},
+ ],
+ manager=FakeResumeManager(AwsSesResumeConfig(next_token="stale")),
+ endpoint="multi_region_endpoints",
+ )
+
+ assert [row["endpoint_id"] for batch in batches for row in batch] == ["e-1"]
+ assert send.call_args_list[0][0][5].get("NextToken") == "stale"
+ assert "NextToken" not in send.call_args_list[1][0][5]
+ assert manager.cleared is True
+
+ def test_a_bad_request_that_outlives_the_restart_still_fails_the_job(self) -> None:
+ # The region genuinely cannot serve the table: page 1 fails the same way, and the error
+ # has to reach the non-retryable classification that disables the schema.
+ with pytest.raises(AwsSesError, match="BadRequestException"):
+ self._run(
+ [
+ AwsSesError("BadRequestException", "invalid", "multi_region_endpoints", "/path"),
+ AwsSesError("BadRequestException", "invalid", "multi_region_endpoints", "/path"),
],
manager=FakeResumeManager(AwsSesResumeConfig(next_token="stale")),
+ endpoint="multi_region_endpoints",
+ )
+
+ def test_a_bad_request_with_no_saved_token_fails_without_a_retry(self) -> None:
+ with pytest.raises(AwsSesError, match="BadRequestException"):
+ self._run(
+ [AwsSesError("BadRequestException", "invalid", "multi_region_endpoints", "/path")],
+ endpoint="multi_region_endpoints",
)
def test_an_incremental_run_asks_aws_only_for_updates_since_the_watermark(self) -> None:
@@ -329,12 +405,12 @@ class TestGetRows:
db_incremental_field_last_value=dt.datetime(2026, 8, 7, 12, 0, tzinfo=dt.UTC),
)
- assert send.call_args[0][4]["StartDate"] == "2026-08-06T12:00:00Z"
+ assert send.call_args[0][5]["StartDate"] == "2026-08-06T12:00:00Z"
def test_a_full_refresh_walks_the_list_unbounded(self) -> None:
_, send, _ = self._run([suppression_page([])])
- assert "StartDate" not in send.call_args[0][4]
+ assert "StartDate" not in send.call_args[0][5]
def test_configuration_sets_fan_out_from_bare_names_to_full_rows(self) -> None:
batches, send, _ = self._run(
@@ -351,7 +427,7 @@ class TestGetRows:
endpoint="configuration_sets",
)
- assert send.call_args_list[1][0][3] == "/v2/email/configuration-sets/transactional"
+ assert send.call_args_list[1][0][4] == "/v2/email/configuration-sets/transactional"
first, second = batches[0][0], batches[1][0]
assert first["configuration_set_name"] == "transactional"
assert first["sending_options_sending_enabled"] is True
@@ -379,7 +455,7 @@ class TestGetRows:
endpoint="email_identities",
)
- assert send.call_args_list[1][0][3] == "/v2/email/identities/user%40example.com"
+ assert send.call_args_list[1][0][4] == "/v2/email/identities/user%40example.com"
row = batches[0][0]
assert row["identity_name"] == "[email protected]"
assert row["sending_enabled"] is True
@@ -390,7 +466,7 @@ class TestGetRows:
batches, _, _ = self._run(
[
{"EmailIdentities": [{"IdentityName": "gone.example.com"}, {"IdentityName": "kept.example.com"}]},
- AwsSesError("Amazon SES request failed: NotFoundException - not found"),
+ AwsSesError("NotFoundException", "not found", "email_identities", "/path"),
{"IdentityType": "DOMAIN"},
],
endpoint="email_identities",
@@ -557,7 +633,7 @@ class TestGetRows:
for key_column in primary_key:
assert expected_row[key_column]
if detail_path is not None:
- assert send.call_args_list[1][0][3] == detail_path
+ assert send.call_args_list[1][0][4] == detail_path
def test_an_account_with_no_dedicated_ips_yields_an_empty_table_and_stays_reachable(self) -> None:
batches, _, manager = self._run([{"DedicatedIps": []}], endpoint="dedicated_ips")
@@ -594,17 +670,17 @@ class TestValidateCredentials:
with mock.patch.object(aws_ses, "send_request", return_value={"SendingEnabled": True}) as send:
assert validate_credentials("key", "secret", None, "us-east-1") == (True, None)
- assert send.call_args[0][3] == "/v2/email/account"
+ assert send.call_args[0][4] == "/v2/email/account"
def test_a_genuine_key_missing_the_account_permission_still_validates_at_create(self) -> None:
# Scope for each table is reported per endpoint in the schema picker instead.
- error = AwsSesError("Amazon SES request failed: AccessDeniedException - not authorized")
+ error = AwsSesError("AccessDeniedException", "not authorized", "account", "/v2/email/account")
with mock.patch.object(aws_ses, "send_request", side_effect=error):
assert validate_credentials("key", "secret", None, "us-east-1") == (True, None)
def test_a_rejected_key_is_surfaced_to_the_user(self) -> None:
- error = AwsSesError("Amazon SES request failed: UnrecognizedClientException - invalid token")
+ error = AwsSesError("UnrecognizedClientException", "invalid token", "account", "/v2/email/account")
with mock.patch.object(aws_ses, "send_request", side_effect=error):
assert validate_credentials("key", "secret", None, "us-east-1") == (False, str(error))
@@ -618,8 +694,11 @@ class TestValidateCredentials:
def test_validating_a_schema_probes_that_endpoint_and_names_the_missing_permission(self) -> None:
error = AwsSesError(
- "Amazon SES request failed: AccessDeniedException - User: arn:aws:iam::123456789012:user/etl "
- "is not authorized to perform: ses:ListSuppressedDestinations on resource: arn:aws:ses:us-east-1:123456789012:suppression-list"
+ "AccessDeniedException",
+ "User: arn:aws:iam::123456789012:user/etl is not authorized to perform: "
+ "ses:ListSuppressedDestinations on resource: arn:aws:ses:us-east-1:123456789012:suppression-list",
+ "suppressed_destinations",
+ "/v2/email/suppression/addresses",
)
with mock.patch.object(aws_ses, "send_request", side_effect=error):
@@ -638,11 +717,11 @@ class TestValidateCredentials:
class TestEndpointPermissions:
def test_only_the_denied_endpoint_is_reported_unreachable(self) -> None:
- def respond(session: Any, credentials: Any, region: str, path: str, params: Any = None) -> dict[str, Any]:
+ def respond(
+ session: Any, credentials: Any, region: str, endpoint: str, path: str, params: Any = None
+ ) -> dict[str, Any]:
if path == "/v2/email/account":
- raise AwsSesError(
- "Amazon SES request failed: AccessDeniedException - not authorized to perform: ses:GetAccount"
- )
+ raise AwsSesError("AccessDeniedException", "not authorized to perform: ses:GetAccount", endpoint, path)
return {}
with mock.patch.object(aws_ses, "send_request", side_effect=respond):
@@ -660,7 +739,10 @@ class TestEndpointPermissions:
responses = [
{"EmailIdentities": [{"IdentityName": "example.com"}]},
AwsSesError(
- "Amazon SES request failed: AccessDeniedException - not authorized to perform: ses:GetEmailIdentity"
+ "AccessDeniedException",
+ "not authorized to perform: ses:GetEmailIdentity",
+ "email_identities",
+ "/v2/email/identities/example.com",
),
]
@@ -671,8 +753,25 @@ class TestEndpointPermissions:
def test_transient_failures_do_not_hide_tables_from_the_schema_picker(self) -> None:
with mock.patch.object(
- aws_ses, "send_request", side_effect=AwsSesError("Amazon SES request failed: HTTP 503 - gateway")
+ aws_ses,
+ "send_request",
+ side_effect=AwsSesError(
+ "HTTP 503", "gateway", "suppressed_destinations", "/v2/email/suppression/addresses"
+ ),
):
reasons = probe_endpoint_permissions("key", "secret", None, "us-east-1", ["suppressed_destinations"])
assert reasons == {"suppressed_destinations": None}
+
+ def test_a_table_the_region_cannot_serve_is_reported_instead_of_staying_selectable(self) -> None:
+ # SESv2 answers an operation the region does not support with a bodyless 400.
+ with mock.patch.object(
+ aws_ses,
+ "send_request",
+ side_effect=AwsSesError(
+ "BadRequestException", "no reason", "multi_region_endpoints", "/v2/email/multi-region-endpoints"
+ ),
+ ):
+ reasons = probe_endpoint_permissions("key", "secret", None, "us-east-1", ["multi_region_endpoints"])
+
+ assert reasons == {"multi_region_endpoints": aws_ses._BAD_REQUEST_EXPLANATION}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses_source.py
index 33cfbd97002c..6f79c09d205e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses_source.py
@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses im
aws_ses as transport_module,
source as source_module,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.aws_ses import AwsSesError
from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.source import AwsSesSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsses import AwsSesSourceConfig
@@ -56,21 +57,27 @@ class TestAwsSesSource:
@pytest.mark.parametrize(
"observed_error",
[
- "Amazon SES request failed: UnrecognizedClientException - The security token included in the request is invalid",
- "Amazon SES request failed: SignatureDoesNotMatch - Signature expired",
- "Amazon SES request failed: ExpiredTokenException - The security token included in the request is expired",
- "Amazon SES request failed: AccessDeniedException - not authorized to perform: ses:GetAccount",
+ str(AwsSesError("UnrecognizedClientException", "The security token is invalid", "account", "/p")),
+ str(AwsSesError("SignatureDoesNotMatch", "Signature expired", "account", "/p")),
+ str(AwsSesError("ExpiredTokenException", "The security token is expired", "account", "/p")),
+ str(AwsSesError("AccessDeniedException", "not authorized to perform: ses:GetAccount", "account", "/p")),
+ str(AwsSesError("BadRequestException", "no reason", "multi_region_endpoints", "/p")),
"Invalid AWS region: 'email.evil.example/'",
],
)
def test_permanent_aws_failures_stop_the_sync_instead_of_retrying(self, observed_error: str) -> None:
assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+ def test_a_rejected_request_keeps_the_message_that_names_the_failing_table(self) -> None:
+ # A fixed friendly string would replace the raised message and hide which of the ten
+ # tables AWS rejected.
+ assert self.source.get_non_retryable_errors()["Amazon SES request failed: BadRequestException"] is None
+
@pytest.mark.parametrize(
"observed_error",
[
- "Amazon SES request failed: TooManyRequestsException - Rate exceeded",
- "Amazon SES request failed: HTTP 503 - ",
+ str(AwsSesError("TooManyRequestsException", "Rate exceeded", "account", "/p")),
+ str(AwsSesError("HTTP 503", "", "account", "/p")),
],
)
def test_transient_aws_failures_keep_retrying(self, observed_error: str) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index b29e1a6a62bc..1afed73fcb5d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -226,7 +226,8 @@ class _BaseSource(ABC, Generic[ConfigType]):
Returns `dict[str, str | None]`:
key = a partial error message to match on
- value = a friendly error message to show to users. We fallback to displaying the key when this is missing
+ value = a friendly error message to show to users. `None` keeps the raised error message,
+ which is what a source wants when that message carries detail no fixed string could
"""
return {}