Skip to content

Commit 0ec2403

Browse files
fix(dsn): raise BadDsn instead of a bare ValueError for invalid ports
Dsn.__init__ reads parts.port, which urlsplit parses lazily and which raises a bare ValueError for ports outside 0-65535 or not numeric. The exception escapes Dsn, so a typo in SENTRY_DSN breaks Client() at startup with a traceback in urllib/parse.py and except BadDsn cannot catch it. Every other field in __init__ raises BadDsn, and project_id already uses the same try/except idiom. Extend it to the port.
1 parent 566beb0 commit 0ec2403

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

‎sentry_sdk/utils.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -331,10 +331,19 @@ def __init__(
331331
org_id_match = Dsn.ORG_ID_REGEX.match(self.host)
332332
self.org_id = org_id_match.group(1) if org_id_match else None
333333

334-
if parts.port is None:
334+
try:
335+
# `urlsplit` parses the port lazily and raises a bare `ValueError`
336+
# for ports that are not an integer in the range 0-65535.
337+
port = parts.port
338+
except ValueError:
339+
raise BadDsn(
340+
"Invalid port in DSN (%r)" % (parts.netloc.rpartition("@")[-1],)
341+
)
342+
343+
if port is None:
335344
self.port: int = self.scheme == "https" and 443 or 80
336345
else:
337-
self.port = parts.port
346+
self.port = port
338347

339348
if not parts.username:
340349
raise BadDsn("Missing public key")

‎tests/utils/test_general.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,11 @@ def test_parse_invalid_dsn(dsn):
156156
("foo://barbaz@sentry.io", "Unsupported scheme 'foo'"),
157157
("https://foobar@", "Missing hostname"),
158158
("https://@sentry.io", "Missing public key"),
159+
("https://foobar@example.com:foo/1", "Invalid port in DSN ('example.com:foo')"),
160+
(
161+
"https://foobar@example.com:65536/1",
162+
"Invalid port in DSN ('example.com:65536')",
163+
),
159164
],
160165
)
161166
def test_dsn_validations(dsn, error_message):

0 commit comments

Comments
 (0)