Skip to content
Open
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
129 changes: 129 additions & 0 deletions Tests/Transport/ProxyOptionsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?php

/**
* @copyright Copyright (C) 2005 - 2026 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/

namespace Joomla\Http\Tests\Transport;

use Joomla\Http\Transport\Curl;
use Joomla\Http\Transport\Socket;
use Joomla\Http\Transport\Stream;
use Joomla\Uri\Uri;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

/**
* Test class for the proxy.* options of the transports.
*
* The stub server acts as the proxy: PHP's built-in server answers a request with an absolute URI in the
* request line, so the stub reports the full URI and the Proxy-Authorization header it received.
*/
#[CoversClass(Curl::class)]
#[CoversClass(Socket::class)]
#[CoversClass(Stream::class)]
class ProxyOptionsTest extends TestCase
{
/**
* Get the URL of the stub, or skip the test.
*
* @return Uri
*/
private function getStubUri(): Uri
{
if (!\defined('JTEST_HTTP_STUB') && getenv('JTEST_HTTP_STUB') == '') {
$this->markTestSkipped('The Transport test stub has not been configured');
}

return new Uri(\defined('JTEST_HTTP_STUB') ? JTEST_HTTP_STUB : getenv('JTEST_HTTP_STUB'));
}

public static function proxyCredentialsProvider(): \Generator
{
foreach ([Curl::class, Stream::class] as $transport) {
foreach (['proxy.pass', 'proxy.password'] as $passwordOption) {
yield substr(strrchr($transport, '\\'), 1) . ' with ' . $passwordOption => [$transport, $passwordOption];
}
}
}

#[DataProvider('proxyCredentialsProvider')]
public function testRequestIsSentThroughTheProxyWithCredentials(string $transportClass, string $passwordOption): void
{
if (!$transportClass::isSupported()) {
$this->markTestSkipped(sprintf('The "%s" adapter is not supported in this environment.', $transportClass));
}

$stub = $this->getStubUri();
$transport = new $transportClass([
'proxy.enabled' => true,
'proxy.host' => $stub->getHost(),
'proxy.port' => $stub->getPort() ?: 80,
'proxy.user' => 'proxyuser',
$passwordOption => 'proxysecret',
]);

$target = 'http://proxied.example.invalid' . $stub->getPath();
$response = $transport->request('GET', new Uri($target));
$body = json_decode((string) $response->getBody());
$headers = array_change_key_case((array) $body->headers);

$this->assertSame($target, $body->request_uri, 'The request did not go through the proxy.');
$this->assertSame('Basic ' . base64_encode('proxyuser:proxysecret'), $headers['proxy-authorization'] ?? null);
}

public static function incompleteProxyProvider(): \Generator
{
foreach ([Curl::class, Stream::class] as $transport) {
$name = substr(strrchr($transport, '\\'), 1);

yield $name . ' without port' => [$transport, ['proxy.enabled' => true, 'proxy.host' => 'proxy.example.invalid']];
yield $name . ' without host' => [$transport, ['proxy.enabled' => true, 'proxy.port' => 3128]];
}
}

#[DataProvider('incompleteProxyProvider')]
public function testIncompleteProxyConfigurationIsRejected(string $transportClass, array $options): void
{
if (!$transportClass::isSupported()) {
$this->markTestSkipped(sprintf('The "%s" adapter is not supported in this environment.', $transportClass));
}

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The proxy.host and proxy.port options are required when proxy.enabled is set.');

(new $transportClass($options))->request('GET', new Uri('http://127.0.0.1:1/'));
}

public function testSocketTransportWarnsThatItBypassesTheProxy(): void
{
if (!Socket::isSupported()) {
$this->markTestSkipped('The socket transport is not supported in this environment.');
}

$stub = $this->getStubUri();
$warnings = [];

set_error_handler(
static function (int $severity, string $message) use (&$warnings): bool {
$warnings[] = [$severity, $message];

return true;
}
);

try {
$response = (new Socket(['proxy.enabled' => true, 'proxy.host' => 'proxy.example.invalid', 'proxy.port' => 3128]))
->request('GET', $stub);
} finally {
restore_error_handler();
}

$this->assertSame(200, $response->getStatusCode());
$this->assertCount(1, $warnings);
$this->assertSame(E_USER_WARNING, $warnings[0][0]);
$this->assertStringContainsString('does not support proxies', $warnings[0][1]);
}
}
2 changes: 2 additions & 0 deletions Tests/stubs/jhttp_stub.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 4 additions & 0 deletions docs/classes/TransportInterface.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ $http = (new HttpFactory())->getHttp([], ['curl', 'stream']); // first suppor

> Prefer `curl` or `stream`. `Socket` connects with `fsockopen()`, which accepts no stream context,
> so no CA bundle, minimum TLS version or client certificate can be supplied for it.
> It also cannot use a proxy: with `proxy.enabled` set it raises an `E_USER_WARNING` and connects directly.

## Writing a transport

Expand Down Expand Up @@ -108,6 +109,9 @@ with `getOption($key, $default)` and are transport-specific; the commonly used o
| `follow_location` | Curl | Follow redirects, default `true` |
| `transport.curl` | Curl | Raw `CURLOPT_*` overrides, applied last |
| `stream.certpath` | Stream | CA bundle file or directory |
| `proxy.enabled` | Curl, Stream | Send requests through an HTTP proxy; `proxy.host` and `proxy.port` are then required |
| `proxy.host` / `proxy.port` | Curl, Stream | The proxy; an `InvalidArgumentException` is thrown if either is missing |
| `proxy.user` / `proxy.pass` | Curl, Stream | Basic credentials for the proxy; `proxy.password` is accepted for `proxy.pass` |
| `protocolVersion` | Curl | `1.0`, `1.1` or `2.0` |

See [the overview](../overview.md#things-to-know-before-you-build-on-this) for the caveats around
Expand Down
9 changes: 7 additions & 2 deletions src/Transport/Curl.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,15 @@ public function request($method, UriInterface $uri, $data = null, array $headers

// Proxy configuration
if ($this->getOption('proxy.enabled', false)) {
$options[CURLOPT_PROXY] = $this->getOption('proxy.host') . ':' . $this->getOption('proxy.port');
if (!$this->getOption('proxy.host') || !$this->getOption('proxy.port')) {
throw new \InvalidArgumentException('The proxy.host and proxy.port options are required when proxy.enabled is set.');
}

$options[\CURLOPT_PROXY] = $this->getOption('proxy.host') . ':' . (int) $this->getOption('proxy.port');

// proxy.password is accepted as an alias of proxy.pass
if ($user = $this->getOption('proxy.user')) {
$options[CURLOPT_PROXYUSERPWD] = $user . ':' . $this->getOption('proxy.pass');
$options[\CURLOPT_PROXYUSERPWD] = $user . ':' . $this->getOption('proxy.pass', $this->getOption('proxy.password', ''));
}
}

Expand Down
9 changes: 9 additions & 0 deletions src/Transport/Socket.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,15 @@ public function request($method, UriInterface $uri, $data = null, array $headers
$request[] = $value;
}

// This transport cannot use a proxy, so make it visible that the request bypasses the configured one.
if ($this->getOption('proxy.enabled', false)) {
trigger_error(
'The socket transport does not support proxies; the request is sent without the configured proxy.'
. ' Use the cURL or stream transport.',
E_USER_WARNING
);
}

// If we have data to send add it to the request payload.
if (!empty($data)) {
$request[] = null;
Expand Down
15 changes: 8 additions & 7 deletions src/Transport/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,17 @@ public function request(

// Add the proxy configuration if enabled
if ($this->getOption('proxy.enabled', false)) {
$options['request_fulluri'] = true;

if ($this->getOption('proxy.host') && $this->getOption('proxy.port')) {
$options['proxy'] = $this->getOption('proxy.host') . ':' . (int)$this->getOption('proxy.port');
if (!$this->getOption('proxy.host') || !$this->getOption('proxy.port')) {
throw new \InvalidArgumentException('The proxy.host and proxy.port options are required when proxy.enabled is set.');
}

// If authentication details are provided, add those as well
if ($this->getOption('proxy.user') && $this->getOption('proxy.password')) {
$options['request_fulluri'] = true;
$options['proxy'] = 'tcp://' . $this->getOption('proxy.host') . ':' . (int)$this->getOption('proxy.port');

// If authentication details are provided, add those as well; proxy.password is accepted as an alias of proxy.pass
if ($user = $this->getOption('proxy.user')) {
$headers['Proxy-Authorization'] = 'Basic ' . base64_encode(
$this->getOption('proxy.user') . ':' . $this->getOption('proxy.password')
$user . ':' . $this->getOption('proxy.pass', $this->getOption('proxy.password', ''))
);
}
}
Expand Down
Loading