From 0ec2403ea0bca4a4465e47ea030802033a974157 Mon Sep 17 00:00:00 2001 From: QianEric Date: Fri, 27 Nov 2026 14:35:33 +0800 Subject: [PATCH] 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. --- sentry_sdk/utils.py | 13 +++++++++++-- tests/utils/test_general.py | 5 +++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/sentry_sdk/utils.py b/sentry_sdk/utils.py index da15448028..70e2f691da 100644 --- a/sentry_sdk/utils.py +++ b/sentry_sdk/utils.py @@ -331,10 +331,19 @@ def __init__( org_id_match = Dsn.ORG_ID_REGEX.match(self.host) self.org_id = org_id_match.group(1) if org_id_match else None - if parts.port is None: + try: + # `urlsplit` parses the port lazily and raises a bare `ValueError` + # for ports that are not an integer in the range 0-65535. + port = parts.port + except ValueError: + raise BadDsn( + "Invalid port in DSN (%r)" % (parts.netloc.rpartition("@")[-1],) + ) + + if port is None: self.port: int = self.scheme == "https" and 443 or 80 else: - self.port = parts.port + self.port = port if not parts.username: raise BadDsn("Missing public key") diff --git a/tests/utils/test_general.py b/tests/utils/test_general.py index d518717729..5455afb994 100644 --- a/tests/utils/test_general.py +++ b/tests/utils/test_general.py @@ -156,6 +156,11 @@ def test_parse_invalid_dsn(dsn): ("foo://barbaz@sentry.io", "Unsupported scheme 'foo'"), ("https://foobar@", "Missing hostname"), ("https://@sentry.io", "Missing public key"), + ("https://foobar@example.com:foo/1", "Invalid port in DSN ('example.com:foo')"), + ( + "https://foobar@example.com:65536/1", + "Invalid port in DSN ('example.com:65536')", + ), ], ) def test_dsn_validations(dsn, error_message):