Skip to content

fix(dsn): raise BadDsn instead of a bare ValueError for invalid ports - #8416

Open
qianeric-backup wants to merge 1 commit into
getsentry:masterfrom
qianeric-backup:fix/dsn-invalid-port
Open

qianeric-backup wants to merge 1 commit into
getsentry:masterfrom
qianeric-backup:fix/dsn-invalid-port

Conversation

@qianeric-backup

Copy link
Copy Markdown

A DSN with a malformed port raises urllib.parse's ValueError out of Dsn, not BadDsn:

>>> from sentry_sdk.utils import Dsn
>>> Dsn("https://public@example.com:8o8o/1")
Traceback (most recent call last):
  File ".../sentry_sdk/utils.py", line 334, in __init__
    if parts.port is None:
  File ".../urllib/parse.py", line 187, in port
    raise ValueError(message) from None
ValueError: Port could not be cast to integer value as '8o8o'

>>> Dsn("https://public@example.com:65536/1")
ValueError: Port out of range 0-65535

SplitResult.port parses lazily, so the exception surfaces on the line that reads it and carries none of the DSN context — the traceback points at urllib/parse.py and the message doesn't say which DSN was wrong. Because the DSN is parsed while the client is constructed (Client.__init__ → make_transport → Transport.__init__ → Dsn), a typo in SENTRY_DSN takes down initialisation, and except BadDsn: — the documented way to handle a bad DSN — does not catch it.

Every other field in Dsn.__init__ is validated as BadDsn, and project_id already uses the exact idiom this needs:

        if self.scheme not in ("http", "https"):
            raise BadDsn("Unsupported scheme %r" % self.scheme)
        ...
        if not parts.hostname:
            raise BadDsn("Missing hostname")
        ...
        if not parts.username:
            raise BadDsn("Missing public key")
        ...
        try:
            project_id = int(project_id)
        except (ValueError, TypeError):
            raise BadDsn("Invalid project in DSN (%r)" % project_id)

so the change just extends it to the one field that reaches into urllib directly:

        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],)
            )

The message reports netloc with the userinfo stripped, so a mistyped DSN in a log or crash report doesn't leak the secret key.

Tests

Two cases added to the existing test_dsn_validations table in tests/utils/test_general.py: https://foobar@example.com:foo/1 and ...:65536/1, both expecting the new message — the table already covers the other four BadDsn paths, so this is the same shape rather than a new test module.

  • Red, on master with only the tests: 2 failed, 9 passed
  • Green: 11 passed
  • Whole suite (tests, excluding tests/integrations): 164 failed, 1437 passed; the 164 are identical on both trees and the comm -3 against master is empty. They are environment noise here — 156 from test_shadowed_module.py with half the optional integrations installed, 4 transports missing h2, 2 urllib3-length assertions, 1 without dist metadata, 1 span_streaming.
  • Eleven valid DSNs (default 443/80, explicit ports, secret key, o1234. org prefix, copy-construction, org_id= override) dump identically before and after.
  • ruff==0.17.6 (the uv.lock pin): ruff check and ruff format --check clean on both trees.

I did not fix the same bare-ValueError on a malformed IPv6 host in urlsplit — it raises before any of the sibling checks, so folding it in would make this PR argue two things at once. Happy to follow up separately.

AI disclosure

Written with an AI coding assistant (Claude): used to trace the construction path, add the guard and the table entries, and run the before/after comparison. Reviewed by hand against the unpatched tree.

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.
@github-actions github-actions Bot added the risk: medium PR risk score: medium label Nov 27, 2026
@github-actions

Copy link
Copy Markdown
Contributor

PR risk: medium

For commit 0ec2403.

Main concerns: reach, host stability, public contract.

This label is a hint for reviewers, not an approval.

@qianeric-backup
qianeric-backup marked this pull request as ready for review November 27, 2026 06:36
@qianeric-backup
qianeric-backup requested a review from a team as a code owner November 27, 2026 06:36
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Nov 27, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: medium PR risk score: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant