diff --git a/Tests/Transport/SocketRedirectTest.php b/Tests/Transport/SocketRedirectTest.php new file mode 100644 index 00000000..c7ab1ad3 --- /dev/null +++ b/Tests/Transport/SocketRedirectTest.php @@ -0,0 +1,190 @@ +markTestSkipped('The socket transport is not supported in this environment.'); + } + + if (!\defined('JTEST_HTTP_STUB') && getenv('JTEST_HTTP_STUB') == '') { + return; + } + + $stubUrl = \defined('JTEST_HTTP_STUB') ? JTEST_HTTP_STUB : getenv('JTEST_HTTP_STUB'); + $this->stubDirectory = substr($stubUrl, 0, strrpos($stubUrl, '/') + 1); + } + + /** + * Skip the test when no stub is configured. + * + * @return void + */ + private function requireStub(): void + { + if ($this->stubDirectory === '') { + $this->markTestSkipped('The Transport test stub has not been configured'); + } + } + + public static function locationProvider(): \Generator + { + $base = 'http://user:pass@example.com:8080/a/b/c.php?x=1'; + + yield 'relative path' => [$base, 'd.php', 'http://user:pass@example.com:8080/a/b/d.php']; + yield 'relative path with query' => [$base, 'd.php?y=2', 'http://user:pass@example.com:8080/a/b/d.php?y=2']; + yield 'parent directory' => [$base, '../d.php', 'http://user:pass@example.com:8080/a/d.php']; + yield 'current directory' => [$base, '.', 'http://user:pass@example.com:8080/a/b/']; + yield 'absolute path' => [$base, '/e/f', 'http://user:pass@example.com:8080/e/f']; + yield 'query only' => [$base, '?y=2', 'http://user:pass@example.com:8080/a/b/c.php?y=2']; + yield 'fragment is dropped' => [$base, 'd.php#top', 'http://user:pass@example.com:8080/a/b/d.php']; + yield 'network path' => [$base, '//other.example.org/p', 'http://other.example.org/p']; + yield 'absolute URI' => [$base, 'https://other.example.org/p?q=1', 'https://other.example.org/p?q=1']; + yield 'base without path' => ['http://example.com', 'd.php', 'http://example.com/d.php']; + } + + #[DataProvider('locationProvider')] + public function testLocationIsResolvedAgainstTheRequestUri(string $base, string $location, string $expected): void + { + $method = new \ReflectionMethod(Socket::class, 'resolveLocation'); + + $this->assertSame($expected, (string) $method->invoke(new Socket([]), new Uri($base), $location)); + } + + public function testRedirectsWithRelativeLocationAreFollowed(): void + { + $this->requireStub(); + + $response = (new Socket([]))->request('GET', new Uri($this->stubDirectory . 'redirect.php?hops=2')); + + $this->assertSame(200, $response->getStatusCode()); + $this->assertSame('GET', json_decode((string) $response->getBody())->method); + } + + public function testRedirectIsReturnedWhenFollowingIsDisabled(): void + { + $this->requireStub(); + + $response = (new Socket(['follow_location' => false]))->request('GET', new Uri($this->stubDirectory . 'redirect.php')); + + $this->assertSame(302, $response->getStatusCode()); + $this->assertSame('jhttp_stub.php', $response->getHeaderLine('Location')); + } + + public function testRedirectLoopIsAborted(): void + { + $this->requireStub(); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Maximum (20) redirects followed'); + + (new Socket([]))->request('GET', new Uri($this->stubDirectory . 'redirect.php?loop=1')); + } + + public function testPostIsRepeatedAsGetAfter303(): void + { + $this->requireStub(); + + $response = (new Socket([]))->request('POST', new Uri($this->stubDirectory . 'redirect.php?code=303'), ['key' => 'value']); + $body = json_decode((string) $response->getBody()); + + $this->assertSame('GET', $body->method); + $this->assertEmpty((array) $body->post); + } + + public function testPostIsRepeatedWithItsBodyAfter307(): void + { + $this->requireStub(); + + $response = (new Socket([]))->request('POST', new Uri($this->stubDirectory . 'redirect.php?code=307'), ['key' => 'value']); + $body = json_decode((string) $response->getBody()); + + $this->assertSame('POST', $body->method); + $this->assertSame('value', $body->post->key); + } + + public function testCredentialsAreKeptForTheSameOrigin(): void + { + $this->requireStub(); + + $uri = new Uri($this->stubDirectory . 'redirect.php'); + $uri->setUser('username'); + $uri->setPass('password'); + + $body = json_decode((string) (new Socket([]))->request('GET', $uri)->getBody()); + + $this->assertSame('username', $body->username); + $this->assertSame('password', $body->password); + } + + public function testCredentialsAreNotSentToAnotherOrigin(): void + { + $this->requireStub(); + + // The other origin is the same server under another name. + $stub = new Uri($this->stubDirectory); + $aliases = ['localhost' => ['127.0.0.1', '[::1]'], '127.0.0.1' => ['localhost'], '[::1]' => ['localhost']]; + $port = $stub->getPort() ?: 80; + $host = null; + + foreach ($aliases[$stub->getHost()] ?? [] as $alias) { + if ($socket = @fsockopen($alias, $port, $errno, $error, 2)) { + fclose($socket); + $host = $alias; + + break; + } + } + + if ($host === null) { + $this->markTestSkipped('The stub is not reachable under a second host name.'); + } + + $other = new Uri($this->stubDirectory); + $other->setHost($host); + + $uri = new Uri($this->stubDirectory . 'redirect.php?' . http_build_query(['to' => (string) $other])); + $uri->setUser('username'); + $uri->setPass('password'); + + $transport = new Socket(['userauth' => 'username', 'passwordauth' => 'password']); + $body = json_decode((string) $transport->request('GET', $uri, null, ['Cookie' => 'session=secret'])->getBody()); + + $this->assertSame($host, parse_url('http://' . $body->headers->Host, PHP_URL_HOST), 'The redirect was not followed to the other host.'); + $this->assertSame('', $body->username); + $this->assertSame('', $body->password); + $this->assertEmpty((array) $body->cookies); + } +} diff --git a/Tests/stubs/jhttp_stub.php b/Tests/stubs/jhttp_stub.php index b3b9a98e..e071f92e 100644 --- a/Tests/stubs/jhttp_stub.php +++ b/Tests/stubs/jhttp_stub.php @@ -28,6 +28,8 @@ $response->http_referer = getVar($_SERVER, 'HTTP_REFERER'); +$response->headers = function_exists('getallheaders') ? getallheaders() : []; + $response->get = $_GET; $response->post = $_POST; $response->files = $_FILES; diff --git a/Tests/stubs/redirect.php b/Tests/stubs/redirect.php new file mode 100644 index 00000000..50e42847 --- /dev/null +++ b/Tests/stubs/redirect.php @@ -0,0 +1,31 @@ + 1, 'code' => $code]); +} elseif ($hops > 1) { + $location = 'redirect.php?' . http_build_query(['hops' => $hops - 1, 'code' => $code, 'to' => $base]); +} else { + $location = 'jhttp_stub.php'; +} + +header('Location: ' . $base . $location, true, $code); diff --git a/docs/classes/TransportInterface.md b/docs/classes/TransportInterface.md index ffb364a5..15fa622a 100644 --- a/docs/classes/TransportInterface.md +++ b/docs/classes/TransportInterface.md @@ -110,5 +110,11 @@ with `getOption($key, $default)` and are transport-specific; the commonly used o | `stream.certpath` | Stream | CA bundle file or directory | | `protocolVersion` | Curl | `1.0`, `1.1` or `2.0` | +The socket transport follows redirects itself: it honours `follow_location`, resolves a relative +`Location` against the request URI and gives up after 20 redirects with a `RuntimeException`. A +`303`, and a `301` or `302` answering a `POST`, is repeated as a `GET` without a body. When a +redirect leads to another scheme, host or port, the `Authorization`, `Cookie` and `Host` headers +and the `userauth`/`passwordauth` credentials are not sent there. + See [the overview](../overview.md#things-to-know-before-you-build-on-this) for the caveats around `transport.curl` and redirect handling. diff --git a/src/Transport/Socket.php b/src/Transport/Socket.php index 9aedd4c8..767709c8 100644 --- a/src/Transport/Socket.php +++ b/src/Transport/Socket.php @@ -31,9 +31,20 @@ class Socket extends AbstractTransport */ protected $connections; + /** + * The maximum number of redirects to follow. + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + private const MAX_REDIRECTS = 20; + /** * Send a request to the server and return a Response object with the response. * + * Redirects are followed unless the `follow_location` option is false. Credentials and cookies are only sent + * to the origin (scheme, host and port) of the original request. + * * @param string $method The HTTP method for sending the request. * @param UriInterface $uri The URI to the resource to request. * @param mixed $data Either an associative array or a string to be sent with the request. @@ -47,6 +58,165 @@ class Socket extends AbstractTransport * @throws \RuntimeException */ public function request($method, UriInterface $uri, $data = null, array $headers = [], $timeout = null, $userAgent = null) + { + $sendCredentials = true; + + for ($redirects = 0;; $redirects++) { + $response = $this->sendRequest($method, $uri, $data, $headers, $timeout, $userAgent, $sendCredentials); + $status = $response->getStatusCode(); + + if ( + !$this->getOption('follow_location', true) + || !\in_array($status, [301, 302, 303, 307, 308], true) + || !$response->hasHeader('Location') + ) { + return $response; + } + + if ($redirects >= self::MAX_REDIRECTS) { + throw new \RuntimeException(sprintf('Maximum (%d) redirects followed', self::MAX_REDIRECTS)); + } + + $location = $this->resolveLocation($uri, $response->getHeaderLine('Location')); + + // Like browsers and cURL, repeat a POST as GET after 301 and 302, and anything but HEAD as GET after 303. + if (($status === 303 && strtoupper($method) !== 'HEAD') || (\in_array($status, [301, 302], true) && strtoupper($method) === 'POST')) { + $method = 'GET'; + $data = null; + $headers = $this->withoutHeaders($headers, ['Content-Type', 'Content-Length']); + } + + // Do not send credentials, cookies or the Host header to another origin. + if (!$this->isSameOrigin($uri, $location)) { + $sendCredentials = false; + $headers = $this->withoutHeaders($headers, ['Authorization', 'Cookie', 'Host']); + } + + $uri = $location; + } + } + + /** + * Resolve the Location header of a redirect against the URI of the request. + * + * @param UriInterface $base The URI of the request that was redirected. + * @param string $location The value of the Location header. + * + * @return Uri + * + * @since __DEPLOY_VERSION__ + */ + private function resolveLocation(UriInterface $base, string $location): Uri + { + // An absolute URI + if (preg_match('#^[a-z][a-z0-9+.-]*:#i', $location)) { + return new Uri($location); + } + + // A network-path reference + if (str_starts_with($location, '//')) { + return new Uri($base->getScheme() . ':' . $location); + } + + $location = explode('#', $location, 2)[0]; + $parts = explode('?', $location, 2); + $path = $parts[0]; + $query = $parts[1] ?? null; + $basePath = (string) $base->getPath() !== '' ? (string) $base->getPath() : '/'; + + if ($path === '') { + $path = $basePath; + $query = $query ?? (string) $base->getQuery(); + } elseif ($path[0] !== '/') { + $path = substr($basePath, 0, (int) strrpos($basePath, '/') + 1) . $path; + } + + // Remove dot segments + $segments = []; + + foreach (explode('/', $path) as $segment) { + if ($segment === '..') { + if (\count($segments) > 1) { + array_pop($segments); + } + } elseif ($segment !== '.') { + $segments[] = $segment; + } + } + + $path = implode('/', $segments); + + if (\in_array(basename($parts[0]), ['.', '..'], true)) { + $path .= '/'; + } + + return new Uri( + $base->toString(['scheme', 'user', 'pass', 'host', 'port']) . ($path !== '' ? $path : '/') + . ($query !== null && $query !== '' ? '?' . $query : '') + ); + } + + /** + * Check whether two URIs have the same scheme, host and port. + * + * @param UriInterface $a The first URI. + * @param UriInterface $b The second URI. + * + * @return boolean + * + * @since __DEPLOY_VERSION__ + */ + private function isSameOrigin(UriInterface $a, UriInterface $b): bool + { + $port = static function (UriInterface $uri): int { + return (int) ($uri->getPort() ?: (strtolower((string) $uri->getScheme()) === 'https' ? 443 : 80)); + }; + + return strtolower((string) $a->getScheme()) === strtolower((string) $b->getScheme()) + && strtolower((string) $a->getHost()) === strtolower((string) $b->getHost()) + && $port($a) === $port($b); + } + + /** + * Remove headers, ignoring the case of their names. + * + * @param array $headers The request headers. + * @param string[] $names The names of the headers to remove. + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private function withoutHeaders(array $headers, array $names): array + { + $names = array_map('strtolower', $names); + + foreach (array_keys($headers) as $key) { + if (\in_array(strtolower((string) $key), $names, true)) { + unset($headers[$key]); + } + } + + return $headers; + } + + /** + * Send a single request to the server and return a Response object with the response. + * + * @param string $method The HTTP method for sending the request. + * @param UriInterface $uri The URI to the resource to request. + * @param mixed $data Either an associative array or a string to be sent with the request. + * @param array $headers An array of request headers to send with the request. + * @param ?integer $timeout Read timeout in seconds. + * @param ?string $userAgent The optional user agent string to send with the request. + * @param boolean $sendCredentials Whether to send the credentials from the userauth and passwordauth options. + * + * @return Response + * + * @since __DEPLOY_VERSION__ + * @throws \RuntimeException + */ + private function sendRequest($method, UriInterface $uri, $data, array $headers, $timeout, $userAgent, bool $sendCredentials) { $connection = $this->connect($uri, $timeout); @@ -121,7 +291,7 @@ public function request($method, UriInterface $uri, $data = null, array $headers } // Authentication, if needed - if ($this->getOption('userauth') && $this->getOption('passwordauth')) { + if ($sendCredentials && $this->getOption('userauth') && $this->getOption('passwordauth')) { $request[] = 'Authorization: Basic ' . base64_encode($this->getOption('userauth') . ':' . $this->getOption('passwordauth')); } @@ -146,14 +316,7 @@ public function request($method, UriInterface $uri, $data = null, array $headers $content .= fgets($connection, 4096); } - $content = $this->getResponse($content); - - // Follow Http redirects - if ($content->getStatusCode() >= 301 && $content->getStatusCode() < 400 && $content->hasHeader('Location')) { - return $this->request($method, new Uri($content->getHeaderLine('Location')), $data, $headers, $timeout, $userAgent); - } - - return $content; + return $this->getResponse($content); } /**