Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add basic host validation in Uri and add port validation to the Uri constructor #196

Draft
wants to merge 2 commits into
base: 3.4.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,20 @@
<MixedAssignment>
<code><![CDATA[$test]]></code>
</MixedAssignment>
<PossiblyUnusedMethod>
<code><![CDATA[authorityInfo]]></code>
<code><![CDATA[invalidHosts]]></code>
<code><![CDATA[invalidPaths]]></code>
<code><![CDATA[invalidQueryStrings]]></code>
<code><![CDATA[invalidUriProvider]]></code>
<code><![CDATA[mutations]]></code>
<code><![CDATA[queryStringsForEncoding]]></code>
<code><![CDATA[standardSchemePortCombinations]]></code>
<code><![CDATA[userInfoProvider]]></code>
<code><![CDATA[utf8PathsDataProvider]]></code>
<code><![CDATA[utf8QueryStringsDataProvider]]></code>
<code><![CDATA[validPorts]]></code>
</PossiblyUnusedMethod>
<PossiblyUnusedParam>
<code><![CDATA[$query]]></code>
</PossiblyUnusedParam>
Expand Down
77 changes: 69 additions & 8 deletions src/Uri.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use function array_keys;
use function explode;
use function filter_var;
use function implode;
use function ltrim;
use function parse_url;
Expand All @@ -19,11 +20,15 @@
use function rawurlencode;
use function sprintf;
use function str_contains;
use function str_ends_with;
use function str_split;
use function str_starts_with;
use function strtolower;
use function substr;

use const FILTER_FLAG_IPV6;
use const FILTER_VALIDATE_IP;

/**
* Implementation of Psr\Http\UriInterface.
*
Expand Down Expand Up @@ -274,8 +279,10 @@ public function withHost(string $host): UriInterface
return $this;
}

$host = $this->filterHost($host);

$new = clone $this;
$new->host = strtolower($host);
$new->host = $host;

return $new;
}
Expand All @@ -290,11 +297,8 @@ public function withPort(?int $port): UriInterface
return $this;
}

if ($port !== null && ($port < 1 || $port > 65535)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid port "%d" specified; must be a valid TCP/UDP port',
$port
));
if (null !== $port) {
$port = $this->filterPort($port);
}

$new = clone $this;
Expand Down Expand Up @@ -393,8 +397,8 @@ private function parseUri(string $uri): void

$this->scheme = isset($parts['scheme']) ? $this->filterScheme($parts['scheme']) : '';
$this->userInfo = isset($parts['user']) ? $this->filterUserInfoPart($parts['user']) : '';
$this->host = isset($parts['host']) ? strtolower($parts['host']) : '';
$this->port = $parts['port'] ?? null;
$this->host = isset($parts['host']) ? $this->filterHost($parts['host']) : '';
$this->port = isset($parts['port']) ? $this->filterPort($parts['port']) : null;
$this->path = isset($parts['path']) ? $this->filterPath($parts['path']) : '';
$this->query = isset($parts['query']) ? $this->filterQuery($parts['query']) : '';
$this->fragment = isset($parts['fragment']) ? $this->filterFragment($parts['fragment']) : '';
Expand Down Expand Up @@ -503,6 +507,63 @@ private function filterUserInfoPart(string $part): string
);
}

/**
* Valid host subcomponent can be IP-literal, dotted IPv4 or reg-name
*/
private function filterHost(string $host): string
{
if ($host === '') {
return $host;
}
$host = strtolower($host);

// only IP-literal is allowed colon
if (str_contains($host, ':')) {
/**
* RFC3986 defines IP-literal in the host subcomponent as an IPv6 address enclosed in brackets.
* While implementations are somewhat lenient, particularly php's parse_url(), enclosing IPv6
* into the brackets here ensures uri authority is always valid even if assembled manually
* outside of this implementation. This would prevent last IPv6 segment from being treated
* as a port number.
*/
$ipv6 = $host;
if (str_starts_with($ipv6, '[') && str_ends_with($ipv6, ']')) {
$ipv6 = substr($ipv6, 1, -1);
}
$ipv6 = filter_var($ipv6, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
if (false === $ipv6) {
throw new Exception\InvalidArgumentException($host . ' Host contains invalid IPv6 address');
}

return '[' . $ipv6 . ']';
}

/**
* @todo consult with interop tests for a stricter validation across implementations.
*
* Check for forbidden RFC3986 gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
*/
if (preg_match('~[:/?#\[\]@]~', $host)) {
throw new Exception\InvalidArgumentException('Host contains forbidden characters');
}

return $host;
}

private function filterPort(int $port): int
{
if ($port < 1 || $port > 65535) {
throw new Exception\InvalidArgumentException(
sprintf(
'Invalid port "%d" specified; must be a valid TCP/UDP port',
$port
)
);
}

return $port;
}

/**
* Filters the path of a URI to ensure it is properly encoded.
*/
Expand Down
Loading