Skip to content

Fix portRFC returning default port for bracketed IPv6 hosts - #118569

Closed
lizardoluis wants to merge 13 commits into
ClickHouse:masterfrom
lizardoluis:fix-portrfc-ipv6-port
Closed

lizardoluis wants to merge 13 commits into
ClickHouse:masterfrom
lizardoluis:fix-portrfc-ipv6-port

Conversation

@lizardoluis

@lizardoluis lizardoluis commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #118487

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed portRFC and domainRFC silently returning the default port or an empty string instead of parsing IPv6 hosts in brackets correctly, including when preceded by a userinfo@ prefix, e.g. portRFC('http://user@[2001:db8::1]:8080/'). Also fixed domainRFC and portRFC resolving to the wrong host when a URL's userinfo contains more than one @, e.g. domainRFC('http://[email protected]@evil.com/') incorrectly returned paypal.com instead of the real host evil.com.


Workflow [PR]
Sync PR [sync-upstream/pr/118569]

extractPort in port.cpp required the character right after the host
to be ':', but getURLHostRFC returns an IPv6 literal host without its
surrounding brackets, so for a URL like http://[::1]:8080/ that
character is the closing ']' instead. This made portRFC silently fall
back to the default port for any URL with a bracketed IPv6 authority,
even though getURLHostRFC parses the host correctly (and domainRFC
already returns it as expected).

Skip one trailing ']' before checking for ':' to fix this. This is a
no-op for every other case: the non-RFC getURLHost never returns a
host ending in ']', and a valid reg-name host is only ever followed by
':', '/', '?', '#', or the end of the string.
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b04f63b]

Summary: ✅


AI Review

Summary

This PR finishes the portRFC/domainRFC bracketed-IPv6 fixes by teaching the shared RFC host parser to handle userinfo@[ipv6], query/fragment terminators after ports, malformed bracketed authorities, mixed IPv6/IPv4-tail literals, leading-dot hosts, and repeated raw @ correctly. On the current head, I did not find any remaining blocker or major issue in the touched code, and the focused stateless tests cover the failures that showed up in earlier revisions.

Final Verdict

✅ No new findings. The current revision looks good to merge.

LLVM Coverage Report

Measured on commit b04f63b.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 65/66 (98.48%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 7, 2026
@PedroTadim PedroTadim self-assigned this Sep 7, 2026
Comment thread src/Functions/URL/port.cpp Resolved
Per review on ClickHouse#118569: portRFC still returned the default port for
authorities of the form user@[ipv6]:port, e.g.
portRFC('http://user@[2001:db8::1]:8080/'), because getURLHostRFC only
enabled IP-literal parsing for the character right after the scheme,
never re-checking for '[' once a userinfo '@' had been consumed. The
done: label's shortcut for returning a bracketed host was also gated
on "no userinfo seen", so even a URL that got the brackets right would
fall through to the dot-requiring reg-name path and come back empty.

Recognize '[' immediately after '@' as the start of an IP-literal, and
return the bracketed host regardless of whether a userinfo prefix was
present. An '@' encountered while already inside an open bracket (e.g.
a URL that begins with a literal, unescaped '[' and contains a stray
'@' before it closes) is rejected as before, since userinfo cannot
appear inside an IP-literal.
Comment thread src/Functions/URL/domain.h Resolved
Per review on ClickHouse#118569: the fast-path return for a completed IP-literal
host returned as soon as it saw the closing ']', without checking what
came after it. So domainRFC('http://[2001:db8::1]evil.com') (and the
same with a userinfo@ prefix) returned '2001:db8::1' instead of '',
even though 'evil.com' immediately after the bracket makes the URL
unparsable as RFC 3986 authority = host [":" port].

Only end of input, ':', '/', '?', or '#' may legally follow the
closing bracket; anything else now makes the function return an empty
host, matching the same rule checkAndReturnHost already applies to the
character after a dot in a reg-name host.
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 7, 2026
Comment thread src/Functions/URL/domain.h Resolved
Per review on ClickHouse#118569: colon_pos, dot_pos, and has_terminator_after_colon
kept whatever value they had from parsing the userinfo when '@' was
crossed, so a colon or dot appearing before '@' could validate a
malformed host after it using state that actually describes the
userinfo, not the host.

domainRFC('http://user:password@[20[01:db8::1]:80') returned
'20[01:db8::1' instead of '': the stray '[' inside the address should
have been rejected, but the leftover colon_pos from 'user:password'
made the parser treat it as already past a legal host:port boundary.

domainRFC('http://user.name@[2001:db8::1') (missing closing ']')
returned '2001:db8::1' instead of '': once the unterminated bracket
fell through to checkAndReturnHost, the leftover dot_pos from
'user.name' satisfied its dot-based validation, which is meant for
reg-name hosts and has nothing to do with the userinfo.

Reset all three at the '@' boundary so host validation always starts
fresh, regardless of what appeared in the userinfo.
Comment thread src/Functions/URL/port.cpp Resolved
Per review on ClickHouse#118569: the port-digit loop in extractPort only treated
'/' as the end of an explicit port, so a query string or fragment
right after the port, e.g. https://example.com:8443?x=1, made the
loop reject the '?' as a non-digit and fall back to the default port
even though the port itself was perfectly valid.

The host parsers already treat '/', '?', and '#' as the end of the
authority; do the same for the port digits. This mirrors the fix in
the separately open ClickHouse#118482, which covers reg-name hosts; this change
additionally covers bracketed IPv6 hosts, which ClickHouse#118482 does not
touch.
Comment thread src/Functions/URL/domain.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b04f63b89 with master 87a70daf3 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

14 translation units recompiled, 24 s compile time in total, 14 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -1.7 s (-7%) in total before that adjustment.

Job report

Per review on ClickHouse#118569: the bracket fast path returned whatever was
between '[' and ']' as soon as the brackets balanced and a legal
delimiter followed, without checking that the contents were actually
an IPv6 address. domainRFC('http://[2001db81]:80') returned
'2001db81' instead of '', even though that string has no colons and
is not a valid IP-literal at all.

Validate the substring with parseIPv6Whole (already used elsewhere in
the codebase for the same purpose, e.g. isIPAddressInRange.cpp)
before returning it, rejecting the host if the brackets don't contain
a syntactically valid IPv6 address.
Comment thread src/Functions/URL/domain.h Resolved
Per review on ClickHouse#118569: the bracket-scanning loop rejected any '.'
while has_open_bracket was set, so a mixed IPv6/IPv4 tail literal such
as "::ffff:192.0.2.128" was always rejected, even though it is a
valid IPv6 address and parseIPv6Whole (added in the previous commit)
already supports that syntax.

Treat '.' the same as ':' inside brackets: just continue scanning and
let parseIPv6Whole make the final call on validity, instead of
special-casing it as always invalid.
Comment thread src/Functions/URL/domain.h Resolved
Per review on ClickHouse#118569: RFC 3986 allows userinfo to contain more than
one ':' (userinfo = *( unreserved / pct-encoded / sub-delims / ":" )),
but the scanner stopped at the second ':' before ever seeing '@', so
domainRFC('http://user:pass:word@[2001:db8::1]:80') returned '' and
portRFC(..., 443) fell back to 443, even though the authority is
valid.

Until '@' is seen, keep only the first ':' as a fallback host:port
separator (in case no '@' ever shows up) instead of stopping the scan
on a second one - it may still turn out to be part of userinfo.

This exposed a latent bug in the same case: past '@', the change was
first written as "stop only on a second ':'", but the host itself
(outside brackets) can only have one ':', the port separator, and
colon_pos is reset at each '@' and never read again for that branch -
so it must goto done unconditionally on the first ':' seen past '@',
same as before this change.
userinfo cannot legally contain a raw '@' (RFC 3986: userinfo = *(
unreserved / pct-encoded / sub-delims / ":" )), so a second (or
later) '@' means everything up to it was actually userinfo, not the
host found so far. getURLHostRFC used to stop at the second '@' and
return the segment in between as if it were the host:

domainRFC('http://[email protected]@evil.com/') returned 'paypal.com'
instead of 'evil.com' - the classic URL-confusion/phishing pattern of
an authentication-lookalike host preceding the real one. This
reproduces identically on unmodified master, so it predates and is
independent of the bracketed-IPv6 work in this branch, but was found
while auditing getURLHostRFC against RFC 3986 for this PR.

Re-anchor start_of_host (and the per-segment colon_pos/dot_pos/
has_terminator_after_colon state) on every '@' instead of stopping at
the second one, so the host resolves to whatever follows the LAST
'@'. A stray '@' inside an unclosed IP-literal is still rejected, as
before.
domain('http://[email protected]/'), domain('.com'), and domain('http://.com/')
all returned '.com' instead of empty, since checkAndReturnHost never
checked for the dot marking the very first character of the host -
only that something came after it. This is shared by domain() and
domainRFC() alike and reproduces identically on unmodified master, so
it predates this branch.

It surfaced as a regression in 00398_url_functions
(domainRFC('http://user:pass@[email protected]') expects empty) once the
previous commit made getURLHostRFC correctly resolve to the host
after the last '@' instead of stopping at the second one: advancing
past the last '@' to look at ".com" exposed this same pre-existing
bug, which previously went unnoticed because the old "stop at the
second '@'" behavior happened to return empty for that string by
accident (no dot in the segment it stopped at), not because the
leading-dot case was actually handled.

Reject dot_pos == start_of_host the same way the existing checks
already reject a dot with nothing before or after it.
Comment thread src/Functions/URL/domain.h Resolved
Per review on ClickHouse#118569: userinfo cannot legally contain a raw '@'
(RFC 3986: userinfo = *( unreserved / pct-encoded / sub-delims /
":" )), so a second (or later) '@' makes the authority unparseable.
The previous commit re-anchored start_of_host on the latest '@' to
correctly resolve http://[email protected]@evil.com/ to evil.com
instead of the wrong paypal.com - but domainRFC/portRFC document
empty/default results for an authority that cannot be parsed, and
guessing a host out of an invalid authority doesn't meet that
contract, however less wrong the guess is than before.

Reject a second '@' outright instead: return empty from getURLHostRFC
as soon as has_at_symbol is already true, matching the same
empty/default result the caller already gets for other unparseable
authorities. A single '@' is unaffected.
@PedroTadim

Copy link
Copy Markdown
Member

It seems #118487 has been fixed already. Thanks @lizardoluis for your support!

@PedroTadim PedroTadim closed this Sep 9, 2026
@lizardoluis

lizardoluis commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor Author

@PedroTadim this PR actually goes a bit further and fixes several other bugs in the same getURLHostRFC parser that are still open on master, including one that already has its own new issue, #118890, which explicitly credits this PR:

The alternative open PR #118569 does handle the mixed IPv6/IPv4 tail.

Beyond that one, I found (and this PR fixes, with regression tests for each) five more cases where master currently returns a wrong, non-empty host instead of failing safe:

Input Current master This PR
[::ffff:192.168.0.1]:8080 (#118890) empty (wrong) ::ffff:192.168.0.1 / port 8080
[2001db81]:80 — not real IPv6 wrongly returns 2001db81 rejected
[2001:db8::1]evil.com — garbage after ] wrongly returns 2001:db8::1 rejected
user:password@[20[01:db8::1]:80 — malformed nested bracket wrongly returns 20[01:db8::1 rejected
user:pass:word@[2001:db8::1]:80 — multi-colon userinfo (RFC 3986 allows this) empty (wrong) 2001:db8::1
user@[email protected]/ — second raw @ wrongly returns paypal.com rejected

The last one in particular is a real host-confusion bug (the classic trusted@fake URL pattern). master currently returns the fake paypal.com instead of failing safe, independent of anything IPv6-specific.

Since #118632 already covers the base userinfo@[ipv6] case, I'd like to rebase this branch on current master and resubmit covering just these remaining gaps, closing #118890 and fixing the rest. Would you mind reopening this PR (or should I open a fresh one against current master instead, whichever you'd prefer)?

@PedroTadim

Copy link
Copy Markdown
Member

@lizardoluis can you open a new PR to fix the remaining bugs, or do you want to keep this one?

@lizardoluis

Copy link
Copy Markdown
Contributor Author

I can open a new one. One sec.

@lizardoluis

Copy link
Copy Markdown
Contributor Author

@PedroTadim this one #118979

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

Labels

can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

portRFC returns the default port instead of the explicit port for URLs with a bracketed IPv6 host

3 participants