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):