Clearer diagnostic when an API Key SID is passed without `account_sid`
Les mainteneurs répondent en général sous 1 jour
Évaluation
- Difficulté
- 2/5
- Temps estimé
- 1-3 heures
- Accessibilité débutants
- 82/100
Piste de recherche
Commencez par twilio/base/client_base.py au niveau du fallback de account_sid et examinez les tests unitaires associés dans tests/unit. Ajoutez des tests pour une API Key SID sans account_sid, tout en vérifiant qu’un account_sid explicite et la configuration de token existante fonctionnent toujours. Le travail est terminé lorsque le cas où l’Account SID est manquant renvoie une erreur indiquant comment procéder et que les tests pertinents passent.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
Location (twilio/twilio-python @ default branch 74b9629):
self.account_sid = account_sid or self.username
Problem
The README shows API-key authentication as Client(api_key, api_secret, account_sid). If the third argument is forgotten, e.g. Client("SKxxxx...", "secret"), the constructor accepts it and ClientBase.__init__ falls back to self.account_sid = account_sid or self.username, so the API Key SID is used as the account SID in account-scoped resource paths. The fallback is silent: there is no validation or hint in the constructor, and the mistake only surfaces later as an authentication/not-found error from the API, which does not point at the missing account_sid.
Reproduction
from twilio.rest import Client
client = Client("SK" + "a" * 32, "my-api-secret") # no error
print(client.account_sid) # 'SKaaaa...'
client.messages.create(...) # fails later with an API error
Environment:
- Commit:
74b96296b0805986252b798bda4bca90341487ee(main, twilio 9.12.0) - Toolchain: Python 3.13.18
Workaround: always pass account_sid= explicitly when authenticating with API keys.
Already fixed in twilio/twilio-node
PR: https://github.com/twilio/twilio-node/pull/828 — "fix: give more descriptive error for accountSid init issues" (merged 2022-11-28T17:54:36Z, merge commit e18440d317c). When the SID used as accountSid starts with SK, the constructor error now says that an API Key requires the accountSid to be passed as an additional option. twilio-node already rejects non-AC account SIDs; that check is not being proposed here, only the API Key hint.
How twilio-node fixed it:
--- a/lib/base/BaseTwilio.ts
+++ b/lib/base/BaseTwilio.ts
@@ -88,7 +88,11 @@ export class BaseTwilio {
...
if (!this.accountSid?.startsWith("AC")) {
- throw new Error("accountSid must start with AC");
+ const apiKeyMsg = this.accountSid.startsWith("SK")
+ ? ". The given SID indicates an API Key which requires the accountSid to be passed as an additional option"
+ : "";
+
+ throw new Error("accountSid must start with AC" + apiKeyMsg);
Suggested fix
Mirroring twilio-node's API Key hint, ClientBase.__init__ raises a TwilioException with an actionable message when username starts with SK and neither account_sid nor a credential_provider is given; no AC prefix is enforced and other setups are unchanged:
diff --git a/twilio/base/client_base.py b/twilio/base/client_base.py
--- a/twilio/base/client_base.py
+++ b/twilio/base/client_base.py
@@ -4,6 +4,7 @@ from typing import Dict, List, MutableMapping, Optional, Tuple
from urllib.parse import urlparse, urlunparse
from twilio import __version__
+from twilio.base.exceptions import TwilioException
from twilio.http import HttpClient
from twilio.http.http_client import TwilioHttpClient
from twilio.http.response import Response
@@ -54,6 +55,17 @@ class ClientBase(object):
self.credential_provider = credential_provider or None
""" :type : CredentialProvider """
+ if (
+ not account_sid
+ and not self.credential_provider
+ and self.username
+ and self.username.startswith("SK")
+ ):
+ raise TwilioException(
+ "The given username indicates an API Key SID, which requires "
+ "your Account SID to be passed via account_sid"
+ )
+
self.account_sid = account_sid or self.username
""" :type : str """
self.auth = (self.username, self.password)
Verified on 74b9629 (Python 3.13.18, pytest 9.2.0): a unit test for the reproduction above (Client("SK...", "my-api-secret") must raise an error mentioning the API Key and account_sid, while Client("SK...", secret, account_sid="AC...") and Client("AC...", token) keep working) fails without this patch and passes with it; no other test results change in tests/unit.
I can submit a PR for this.
Checked: #259 / #286 (2016) were about API-key auth not being supported/how to pass the account SID; they predate the current account_sid parameter and don't cover diagnosing the omission.
- Langage dominant
- Python
- Étoiles
- 2.1k
- Forks
- 821
- Merge moyen
- 9 h 33 min
- PR mergées (30 j)
- 3
Préparer son environnement
- Fournit un Dockerfile ou un fichier Docker Compose
- Propose un modèle de pull request
- Lire le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de twilio/twilio-python
-
Docs: "Handling Exceptions" should mention that network errors are not `TwilioRestException`Peut-être pris @henricop l’a pris il y a 13 jours. Ouverte
Difficulté 1/5 1-3 heures Accessibilité débutants 90/100
twilio/twilio-python#986 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
-
TokenPagination.next_page_async() makes a sync request and fails with an async http clientPeut-être pris @sebxt l’a pris il y a 31 jours. Ouverte
Difficulté 2/5 1-3 heures Accessibilité débutants 82/100
twilio/twilio-python#976 ·
Les mainteneurs répondent en général sous 1 jour
-
AsyncTwilioHttpClient does not JSON-serialize request bodies for application/json endpoints (sync client does) → 400 on JSON-body v2 endpointsPeut-être pris @Steve0x2a l’a pris il y a 77 jours. Ouverte
Difficulté 2/5 1-3 heures Accessibilité débutants 82/100
twilio/twilio-python#932 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 1/5 Moins d'une heure Accessibilité débutants 88/100
twilio/twilio-python#930 ·
Les mainteneurs répondent en général sous 1 jour
-
[BUG] AsyncTwilioHttpClient.request does not use self.timeoutPeut-être pris @Hashim1999164 l’a pris il y a 96 jours. Ouvertetype: bug
Difficulté 2/5 1-3 heures Accessibilité débutants 74/100
twilio/twilio-python#925 ·
Les mainteneurs répondent en général sous 1 jour
Toutes les issues de twilio/twilio-python
Issues similaires
-
Difficulté 2/5 1-3 heures Accessibilité débutants 64/100
Les mainteneurs répondent en général sous 1 jour
-
Harden tools/pr_threads.sh: pass all printed thread fields through the deterministic sanitizerOuvertearea:cli area:security enhancement priority:medium size:small
Difficulté 2/5 1-3 heures Accessibilité débutants 76/100
RonaldHensbergen/composable-data-stack#1338 ·
Les mainteneurs répondent en général sous 1 jour
-
area:stdlib effort:S impact:med platform:linux type:bug
Difficulté 2/5 1-3 heures Accessibilité débutants 84/100
Les mainteneurs répondent en général sous 1 jour
-
automated endpoint-dead needs-curation
Difficulté 2/5 1-3 heures Accessibilité débutants 76/100
almanac-data/climate-almanac#139 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 82/100
UKGovernmentBEIS/inspect_ai#6695 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour