: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): stop rejecting Twilio Standard API keys (#78033)
jake sciottoadad8bce9475
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.pyindex 6675cdc312bf..114fd7607a79 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py@@ -121,6 +121,17 @@ TWILIO_ENDPOINTS: dict[str, TwilioEndpointConfig] = {ENDPOINTS = tuple(TWILIO_ENDPOINTS.keys())+# Twilio grants the Keys resource (/Accounts/{SID}/Keys) only to the Auth Token and to Main API keys.+# Standard and Restricted API keys get a 401 with error 20003 on it, so the table has to be reported+# as unreachable for those credentials instead of read as a failed credential check.+# https://www.twilio.com/docs/iam/api-keys+MAIN_KEY_ONLY_ENDPOINTS = frozenset({"keys"})++# `get_endpoint_permissions` only runs on the schema-picker path, so one-shot setup would otherwise+# enable a table it has no way to check. Defaulting these off covers both paths, since the picker and+# `build_default_schemas` honor it, and the recommended credential is a Standard key.+SHOULD_SYNC_DEFAULT: dict[str, bool] = {name: name not in MAIN_KEY_ONLY_ENDPOINTS for name in ENDPOINTS}+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in TWILIO_ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.pyindex 62cb6848911b..7901d7296a9b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py@@ -26,10 +26,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.twilio.settings import (ENDPOINTS,INCREMENTAL_FIELDS,+ SHOULD_SYNC_DEFAULT,)from products.warehouse_sources.backend.temporal.data_imports.sources.twilio.twilio import (TwilioAuth,TwilioResumeConfig,+ check_endpoint_permissions as check_twilio_endpoint_permissions,twilio_source,validate_credentials as validate_twilio_credentials,)@@ -57,7 +59,9 @@ class TwilioSource(ResumableSource[TwilioSourceConfig, TwilioResumeConfig]):releaseStatus=ReleaseStatus.ALPHA,caption="""Enter your Twilio credentials to pull your Twilio data into the PostHog Data warehouse.-Your **Account SID** is on the [Twilio Console dashboard](https://console.twilio.com). For credentials we recommend creating a [Standard API key](https://console.twilio.com/us1/account/keys-credentials/api-keys) (SID + Secret) since it can be revoked independently — alternatively you can use your Account SID and Auth Token.""",+Your **Account SID** is on the [Twilio Console dashboard](https://console.twilio.com). For credentials we recommend creating a [Standard API key](https://console.twilio.com/us1/account/keys-credentials/api-keys) (SID + Secret) since it can be revoked independently. You can also use your Account SID and Auth Token.++Create the key in the same Twilio account as the Account SID above, in Twilio's default us1 region. A Standard key can read every table except `keys`, which needs your Auth Token or a Main API key.""",iconPath="/static/services/twilio.png",docsUrl="https://posthog.com/docs/cdp/sources/twilio",fields=cast(@@ -134,7 +138,10 @@ Your **Account SID** is on the [Twilio Console dashboard](https://console.twiliodef get_non_retryable_errors(self) -> dict[str, str | None]:return {- "401 Client Error: Unauthorized for url: https://api.twilio.com": "Invalid Twilio credentials. Please check your Account SID and Auth Token (or API key SID and secret) and reconnect.",+ # Twilio returns 401 both for a bad secret and for a valid credential that isn't allowed to+ # read the resource (error 20003), and the two are indistinguishable from the status alone,+ # so this message has to cover both rather than asserting the credentials are invalid.+ "401 Client Error: Unauthorized for url: https://api.twilio.com": "Twilio rejected these credentials for this table. Either the Account SID and secret are wrong, or the credential can't read this resource. A Restricted API key needs read access granted for it, and the keys table needs your Auth token or a Main API key. Fix the credential, then reconnect the source.","403 Client Error: Forbidden for url: https://api.twilio.com": "Your Twilio credentials lack permission for this resource. Please check the credential's permissions and try again.",}@@ -157,7 +164,7 @@ Your **Account SID** is on the [Twilio Console dashboard](https://console.twilioforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, should_sync_default=SHOULD_SYNC_DEFAULT)def validate_credentials(self,@@ -172,6 +179,17 @@ Your **Account SID** is on the [Twilio Console dashboard](https://console.twilioreturn False, str(e)return validate_twilio_credentials(auth, config.account_sid, schema_name)+ def get_endpoint_permissions(+ self, config: TwilioSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None+ ) -> dict[str, str | None]:+ try:+ auth = self._get_auth(config)+ except ValueError:+ # validate_credentials already reports a missing secret, so treat every table as available+ # rather than blocking the picker on a condition the caller has surfaced.+ return dict.fromkeys(endpoints)+ return check_twilio_endpoint_permissions(auth, config.account_sid, endpoints)+def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TwilioResumeConfig]:return ResumableSourceManager[TwilioResumeConfig](inputs, TwilioResumeConfig)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.pyindex 294903a366cb..1c469706de74 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.py@@ -9,14 +9,23 @@ from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.twilio.settings import TWILIO_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.twilio.twilio import (+ CREDENTIAL_PROBE_ENDPOINTS,+ TWILIO_ACCOUNT_NOT_FOUND_MESSAGE,+ TWILIO_INVALID_CREDENTIALS_MESSAGE,+ TWILIO_MAIN_KEY_REQUIRED_MESSAGE,+ TWILIO_MAIN_KEY_REQUIRED_REASON,+ TWILIO_UNREACHABLE_MESSAGE,TwilioResumeConfig,_build_initial_params,_format_filter_date,+ _unexpected_status_message,twilio_source,validate_credentials,)ACCOUNT_SID = "AC00000000000000000000000000000000"+# A Standard API key, the credential the source's caption recommends.+API_KEY_AUTH = ("SK00000000000000000000000000000000", "secret")# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -154,8 +163,10 @@ class TestValidateCredentials:(200, "messages", True),(401, None, False),(401, "messages", False),- (403, None, True), # valid token, no resource selected yet -> accept- (403, "messages", False), # valid token, but no access to the chosen endpoint+ # Twilio denies by 401, so a 403 carries no extra meaning and cannot be accepted either.+ (403, None, False),+ (403, "messages", False),+ (404, None, False),(500, None, False),],)@@ -166,11 +177,66 @@ class TestValidateCredentials:assert is_valid is expected_valid@mock.patch(TWILIO_SESSION_PATCH)- def test_unauthorized_returns_actionable_message(self, mock_session):- mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)- is_valid, msg = validate_credentials((ACCOUNT_SID, "token"), ACCOUNT_SID)- assert is_valid is False- assert msg is not None and "credentials" in msg.lower()+ def test_standard_api_key_denied_the_account_resource_is_still_accepted(self, mock_session):+ # Twilio 401s the Accounts resource for Standard and Restricted API keys, so probing it at+ # source-create time rejected the credential the caption recommends.+ def _get(url, **kwargs):+ status = 401 if url.endswith(f"Accounts/{ACCOUNT_SID}.json") else 200+ return mock.MagicMock(status_code=status)++ getter = mock_session.return_value.get+ getter.side_effect = _get++ is_valid, msg = validate_credentials(API_KEY_AUTH, ACCOUNT_SID)++ assert (is_valid, msg) == (True, None)+ probed = [call.args[0] for call in getter.call_args_list]+ assert not any(url.endswith(f"Accounts/{ACCOUNT_SID}.json") for url in probed)++ @mock.patch(TWILIO_SESSION_PATCH)+ def test_create_probe_walks_candidates_until_one_is_readable(self, mock_session):+ # A Restricted key scoped to one product area is denied the earlier candidates.+ getter = mock_session.return_value.get+ getter.side_effect = [mock.MagicMock(status_code=s) for s in (401, 401, 200)]++ is_valid, msg = validate_credentials(API_KEY_AUTH, ACCOUNT_SID)++ assert (is_valid, msg) == (True, None)+ probed = [call.args[0] for call in getter.call_args_list]+ assert probed == [+ f"https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/{TWILIO_ENDPOINTS[name].path}?PageSize=1"+ for name in CREDENTIAL_PROBE_ENDPOINTS+ ]++ @mock.patch(TWILIO_SESSION_PATCH)+ def test_create_probe_rejects_when_every_candidate_is_denied(self, mock_session):+ getter = mock_session.return_value.get+ getter.return_value = mock.MagicMock(status_code=401)++ is_valid, msg = validate_credentials(API_KEY_AUTH, ACCOUNT_SID)++ assert (is_valid, msg) == (False, TWILIO_INVALID_CREDENTIALS_MESSAGE)+ assert getter.call_count == len(CREDENTIAL_PROBE_ENDPOINTS)++ @pytest.mark.parametrize(+ "status_code, expected_message",+ [+ (500, "Twilio returned an unexpected status (500) while validating credentials."),+ (429, "Twilio returned an unexpected status (429) while validating credentials."),+ (404, TWILIO_ACCOUNT_NOT_FOUND_MESSAGE),+ ],+ )+ @mock.patch(TWILIO_SESSION_PATCH)+ def test_create_probe_stops_on_a_status_that_is_not_a_denial(self, mock_session, status_code, expected_message):+ # A throttle, a server error, or a missing account is not a verdict on the credential, so the+ # remaining candidates must not be walked.+ getter = mock_session.return_value.get+ getter.return_value = mock.MagicMock(status_code=status_code)++ is_valid, msg = validate_credentials(API_KEY_AUTH, ACCOUNT_SID)++ assert (is_valid, msg) == (False, expected_message)+ assert getter.call_count == 1@mock.patch(TWILIO_SESSION_PATCH)def test_specific_schema_probes_endpoint_path(self, mock_session):@@ -180,12 +246,57 @@ class TestValidateCredentials:probed_url = getter.call_args.args[0]assert probed_url == f"https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/Messages.json?PageSize=1"+ @pytest.mark.parametrize(+ "schema_name, expected_message",+ [+ ("keys", TWILIO_MAIN_KEY_REQUIRED_MESSAGE),+ (+ "messages",+ "Twilio rejected these credentials for messages. Check that the Account SID and secret are "+ "correct, and if this is a Restricted API key, give it read access to messages.",+ ),+ ],+ )@mock.patch(TWILIO_SESSION_PATCH)- def test_transport_error_is_not_valid(self, mock_session):+ def test_denied_schema_message_names_the_cause(self, mock_session, schema_name, expected_message):+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)+ is_valid, msg = validate_credentials(API_KEY_AUTH, ACCOUNT_SID, schema_name)+ assert (is_valid, msg) == (False, expected_message)++ @mock.patch(TWILIO_SESSION_PATCH)+ def test_chosen_schema_reports_a_server_error_as_such(self, mock_session):+ # Reporting a Twilio outage on a chosen table as a permission problem would send the user off+ # to rebuild a working API key.+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=503)+ is_valid, msg = validate_credentials(API_KEY_AUTH, ACCOUNT_SID, "messages")+ assert (is_valid, msg) == (False, _unexpected_status_message(503))++ @pytest.mark.parametrize("schema_name", [None, "messages"])+ @mock.patch(TWILIO_SESSION_PATCH)+ def test_transport_error_is_not_valid(self, mock_session, schema_name):# validate_via_probe swallows the exception; the source must report "not validated".- mock_session.return_value.get.side_effect = Exception("boom")- is_valid, _msg = validate_credentials((ACCOUNT_SID, "token"), ACCOUNT_SID)- assert is_valid is False+ getter = mock_session.return_value.get+ getter.side_effect = Exception("boom")++ is_valid, msg = validate_credentials((ACCOUNT_SID, "token"), ACCOUNT_SID, schema_name)++ assert (is_valid, msg) == (False, TWILIO_UNREACHABLE_MESSAGE)+ assert getter.call_count == 1++ def test_probe_candidates_are_real_endpoints(self):+ # A typo here raises KeyError out of validate_credentials and 500s source creation.+ assert set(CREDENTIAL_PROBE_ENDPOINTS) <= set(TWILIO_ENDPOINTS)++ def test_create_denial_message_names_restricted_key_scope(self):+ # Only three of the eleven tables have a probe rung, so a Restricted key scoped elsewhere+ # lands here and the message has to name scope alongside the SID, secret, and region causes.+ assert "Restricted API key" in TWILIO_INVALID_CREDENTIALS_MESSAGE++ def test_picker_reason_is_a_fragment(self):+ # The schema picker interpolates this into "...cannot read this table: {reason}. Grant the+ # missing scope...", so a trailing period doubles up and a full sentence reads as two.+ assert not TWILIO_MAIN_KEY_REQUIRED_REASON.endswith(".")+ assert TWILIO_MAIN_KEY_REQUIRED_REASON.count(".") == 0class TestPagination:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.pyindex af87a4cff4ff..5c3c0aa5458b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.py@@ -13,10 +13,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.twilio.setINCREMENTAL_FIELDS,)from products.warehouse_sources.backend.temporal.data_imports.sources.twilio.source import TwilioSource-from products.warehouse_sources.backend.temporal.data_imports.sources.twilio.twilio import TwilioResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.twilio.twilio import (+ TWILIO_MAIN_KEY_REQUIRED_REASON,+ TwilioResumeConfig,+)from products.warehouse_sources.backend.types import ExternalDataSourceTypeACCOUNT_SID = "AC00000000000000000000000000000000"+TWILIO_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.twilio.twilio.make_tracked_session"+)def _api_key_config():@@ -107,6 +113,14 @@ class TestTwilioSource:schemas = self.source.get_schemas(self.config, self.team_id, names=["calls"])assert [s.name for s in schemas] == ["calls"]+ def test_main_key_only_tables_default_off(self):+ # One-shot setup builds its schema list straight from get_schemas and never calls+ # get_endpoint_permissions, so without this the `keys` table is enabled for a Standard API+ # key and its first sync fails non-retryably.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["keys"].should_sync_default is False+ assert all(s.should_sync_default for name, s in schemas.items() if name != "keys")+@pytest.mark.parametrize("config_factory, expected_auth",[@@ -139,6 +153,40 @@ class TestTwilioSource:assert error is Nonemock_validate.assert_called_once_with(("SK123", "secret"), ACCOUNT_SID, "messages")+ @pytest.mark.parametrize(+ "status_code, expected_keys_reason",+ [+ (401, TWILIO_MAIN_KEY_REQUIRED_REASON),+ (403, TWILIO_MAIN_KEY_REQUIRED_REASON),+ (200, None),+ # A throttle or a server error must not hide a table the credential can actually read.+ (429, None),+ (500, None),+ ],+ )+ @mock.patch(TWILIO_SESSION_PATCH)+ def test_get_endpoint_permissions_gates_only_the_keys_table(self, mock_session, status_code, expected_keys_reason):+ getter = mock_session.return_value.get+ getter.return_value = mock.MagicMock(status_code=status_code)++ result = self.source.get_endpoint_permissions(self.config, self.team_id, list(ENDPOINTS))++ assert result["keys"] == expected_keys_reason+ assert {name: reason for name, reason in result.items() if name != "keys"} == dict.fromkeys(+ name for name in ENDPOINTS if name != "keys"+ )+ # Probing every table would add a round-trip per table to an interactive request.+ assert getter.call_count == 1++ @mock.patch(TWILIO_SESSION_PATCH)+ def test_get_endpoint_permissions_survives_missing_secrets(self, mock_session):+ config = TwilioSourceConfig(account_sid=ACCOUNT_SID, auth_method=TwilioAuthMethodConfig(selection="api_key"))++ result = self.source.get_endpoint_permissions(config, self.team_id, list(ENDPOINTS))++ assert result == dict.fromkeys(ENDPOINTS)+ mock_session.assert_not_called()+def test_get_resumable_source_manager_binds_resume_config(self):manager = self.source.get_resumable_source_manager(mock.MagicMock())assert isinstance(manager, ResumableSourceManager)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.pyindex c3ad4f13b305..e119dd11afbd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.twilio.settings import (+ MAIN_KEY_ONLY_ENDPOINTS,TWILIO_ENDPOINTS,TwilioEndpointConfig,)@@ -28,6 +29,40 @@ DEFAULT_PAGE_SIZE = 1000TwilioAuth = tuple[str, str]+# Candidates probed in order at source-create time, when no table has been picked yet. Each one is a+# data resource under /Accounts/{SID}/ rather than /Accounts/{SID}.json itself, because Twilio denies+# the Accounts resource to Standard and Restricted API keys with a 401 (error 20003), and a Standard+# key is the credential this source recommends. Probing the account resource therefore rejected the+# credential type our own caption tells users to create. The three candidates cover one Restricted-key+# permission area each (Messaging, Voice, Phone Numbers), which is what a Restricted key scoped to this+# catalog's high-volume tables can read. Twilio scopes the rest of the catalog separately though, so a+# Restricted key granted only Recordings, say, is denied every candidate and fails here even though the+# table it wants is readable. TWILIO_INVALID_CREDENTIALS_MESSAGE names that as a cause. Widening the+# ladder to cover all 11 tables would make the all-denied path cost 11 sequential requests, so the+# message carries it instead. An account that has never sent a message returns 200 with an empty list,+# so probing real data does not penalize an unused account.+CREDENTIAL_PROBE_ENDPOINTS: tuple[str, ...] = ("messages", "calls", "incoming_phone_numbers")++TWILIO_INVALID_CREDENTIALS_MESSAGE = (+ "Twilio rejected these credentials. Check that the Account SID and secret are correct and have no "+ "extra spaces, and that the API key was created in the same Twilio account as that Account SID. "+ "PostHog connects to api.twilio.com, so a key created in another Twilio region will not work. A "+ "Restricted API key also needs read access to Messages, Calls, or Phone Numbers, which is how "+ "PostHog checks the credential before you pick a table."+)+TWILIO_ACCOUNT_NOT_FOUND_MESSAGE = (+ "Twilio has no account with that Account SID. Copy the Account SID from your Twilio Console "+ "dashboard. It starts with AC."+)+TWILIO_MAIN_KEY_REQUIRED_MESSAGE = (+ "Twilio's Keys resource needs your Auth Token or a Main API key. Standard and Restricted API keys cannot read it."+)+# The schema picker interpolates a reason into its own sentence ("Source credentials cannot read this+# table: {reason}. Grant the missing scope..."), so this has to be a fragment rather than the sentence+# above, and it has to lead with the fix, since no scope grant makes a Standard key work here.+TWILIO_MAIN_KEY_REQUIRED_REASON = "Twilio grants this resource only to your Auth Token or a Main API key"+TWILIO_UNREACHABLE_MESSAGE = "Could not reach Twilio to validate credentials."+@dataclasses.dataclassclass TwilioResumeConfig:@@ -100,36 +135,79 @@ def _build_resource_path(config: TwilioEndpointConfig, account_sid: str) -> str:return f"/{TWILIO_API_VERSION}/Accounts/{account_sid}/{config.path}"-def validate_credentials(- auth: TwilioAuth, account_sid: str, schema_name: Optional[str] = None-) -> tuple[bool, str | None]:- if schema_name is not None and schema_name in TWILIO_ENDPOINTS:- config = TWILIO_ENDPOINTS[schema_name]- url = f"{TWILIO_BASE_URL}{_build_resource_path(config, account_sid)}?PageSize=1"- else:- url = f"{TWILIO_BASE_URL}/{TWILIO_API_VERSION}/Accounts/{account_sid}.json"+def _unexpected_status_message(status: int) -> str:+ return f"Twilio returned an unexpected status ({status}) while validating credentials."++def _endpoint_denied_message(schema_name: str) -> str:+ if schema_name in MAIN_KEY_ONLY_ENDPOINTS:+ return TWILIO_MAIN_KEY_REQUIRED_MESSAGE+ return (+ f"Twilio rejected these credentials for {schema_name}. Check that the Account SID and secret are "+ f"correct, and if this is a Restricted API key, give it read access to {schema_name}."+ )+++def _probe_status(auth: TwilioAuth, account_sid: str, schema_name: str) -> int | None:+ """GET one list resource with PageSize=1 and report the HTTP status, or None on transport failure."""+ config = TWILIO_ENDPOINTS[schema_name]+ url = f"{TWILIO_BASE_URL}{_build_resource_path(config, account_sid)}?PageSize=1"_ok, status = validate_via_probe(lambda: make_tracked_session(redact_values=(auth[1],)),url,auth=HTTPBasicAuth(*auth),)+ return status- if status == 200:- return True, None-- if status == 401:- return False, "Invalid Twilio credentials. Check your Account SID and Auth Token (or API key SID and secret)."-- # A valid token without access to a specific resource is acceptable at source-create time- # (no schema selected yet); only treat it as a failure when validating a specific endpoint.- if status == 403 and schema_name is None:- return True, None-- if status is None:- return False, "Could not reach Twilio to validate credentials."- return False, f"Twilio returned an unexpected status ({status}) while validating credentials."+def validate_credentials(+ auth: TwilioAuth, account_sid: str, schema_name: Optional[str] = None+) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name in TWILIO_ENDPOINTS:+ status = _probe_status(auth, account_sid, schema_name)+ if status == 200:+ return True, None+ if status is None:+ return False, TWILIO_UNREACHABLE_MESSAGE+ # Twilio answers a permission denial with 401 (error 20003) rather than 403, so on this API the+ # two statuses carry the same meaning and neither can be read as a valid credential.+ if status in (401, 403):+ return False, _endpoint_denied_message(schema_name)+ # A 404 is not mapped to "no such account" here the way it is on the create path below: this+ # branch probes one chosen table, so a 404 more likely means that resource is unavailable on+ # the account than that the Account SID is wrong.+ return False, _unexpected_status_message(status)++ # No table chosen yet, so prove the credential can read something rather than asking Twilio to+ # confirm the account itself. See CREDENTIAL_PROBE_ENDPOINTS for why the account resource is unsafe+ # to probe here.+ for candidate in CREDENTIAL_PROBE_ENDPOINTS:+ status = _probe_status(auth, account_sid, candidate)+ if status == 200:+ return True, None+ if status is None:+ return False, TWILIO_UNREACHABLE_MESSAGE+ if status == 404:+ return False, TWILIO_ACCOUNT_NOT_FOUND_MESSAGE+ if status not in (401, 403):+ # A throttle or a server error is not a verdict on the credential, so stop rather than+ # walking the remaining candidates only to report them as invalid.+ return False, _unexpected_status_message(status)++ return False, TWILIO_INVALID_CREDENTIALS_MESSAGE+++def check_endpoint_permissions(auth: TwilioAuth, account_sid: str, endpoints: list[str]) -> dict[str, str | None]:+ """Report which tables these credentials cannot read, so the schema picker can disable them."""+ permissions: dict[str, str | None] = dict.fromkeys(endpoints)+ for endpoint in endpoints:+ if endpoint not in MAIN_KEY_ONLY_ENDPOINTS:+ continue+ # Only an outright denial hides the table. A throttle, a server error, or a network blip must+ # not remove a table the credential can actually read.+ if _probe_status(auth, account_sid, endpoint) in (401, 403):+ permissions[endpoint] = TWILIO_MAIN_KEY_REQUIRED_REASON+ return permissionsdef twilio_source(