Skip to content

Commit 3265c05

Browse files
committed
fix(ggclient): check API key encoding early
1 parent 8a35e10 commit 3265c05

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

pygitguardian/client.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def __init__(
8181
:param user_agent: user agent to identify requests, defaults to ""
8282
:param timeout: request timeout, defaults to 20s
8383
84-
:raises ValueError: if the protocol is invalid
84+
:raises ValueError: if the protocol or the api_key is invalid
8585
"""
8686

8787
if isinstance(base_uri, str):
@@ -93,6 +93,18 @@ def __init__(
9393
if not isinstance(api_key, str):
9494
raise TypeError("api_key is not a string")
9595

96+
try:
97+
# The requests module encodes headers in latin-1, if api_key contains
98+
# characters which cannot be encoded in latin-1, the raised exception is
99+
# going to be very obscure. Catch the problem early to raise a clearer
100+
# exception.
101+
# See https://github.com/GitGuardian/ggshield/issues/101
102+
api_key.encode("latin-1")
103+
except UnicodeEncodeError:
104+
raise ValueError(
105+
"Invalid value for API Key: must be only latin-1 characters."
106+
)
107+
96108
self.base_uri = base_uri
97109
self.api_key = api_key
98110
self.session = session if isinstance(session, Session) else Session()

tests/test_client.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,14 @@
179179
None,
180180
id="Custom headers",
181181
),
182+
pytest.param(
183+
"–––––––FILL-ME–––––––––",
184+
"https://api.gitguardian.com/",
185+
"None",
186+
30.0,
187+
ValueError,
188+
id="U+2013 dash characters in API key",
189+
),
182190
],
183191
)
184192
def test_client_creation(

0 commit comments

Comments
 (0)