Skip to content

Commit 788d6f5

Browse files
authored
Merge commit from fork
* fix: reset CURLRequest options after exceptions * apply advisory suggestions
1 parent 515876c commit 788d6f5

5 files changed

Lines changed: 361 additions & 8 deletions

File tree

‎system/HTTP/CURLRequest.php‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ class CURLRequest extends OutgoingRequest
4848
*/
4949
protected $baseURI;
5050

51+
/**
52+
* The constructor's base URI, preserved independently of per-request changes.
53+
*/
54+
private readonly URI $defaultBaseURI;
55+
5156
/**
5257
* The setting values
5358
*
@@ -138,6 +143,7 @@ public function __construct(App $config, URI $uri, ?ResponseInterface $response
138143

139144
$this->config = $this->defaultConfig;
140145
$this->parseOptions($options);
146+
$this->defaultBaseURI = clone $this->baseURI;
141147

142148
// Share Connection
143149
$optShareConnection = config(ConfigCURLRequest::class)->shareConnectionOptions ?? [ // @phpstan-ignore nullCoalesce.property
@@ -165,16 +171,18 @@ public function request($method, string $url, array $options = []): ResponseInte
165171
{
166172
$this->response = clone $this->responseOrig;
167173

168-
$this->parseOptions($options);
174+
try {
175+
$this->parseOptions($options);
169176

170-
$url = $this->prepareURL($url);
177+
$url = $this->prepareURL($url);
171178

172-
$method = esc(strip_tags($method));
179+
$method = esc(strip_tags($method));
173180

174-
$this->send($method, $url);
175-
176-
if ($this->shareOptions === false) {
177-
$this->resetOptions();
181+
$this->send($method, $url);
182+
} finally {
183+
if ($this->shareOptions === false) {
184+
$this->resetOptions();
185+
}
178186
}
179187

180188
return $this->response;
@@ -197,6 +205,9 @@ protected function resetOptions()
197205
// Reset configs
198206
$this->config = $this->defaultConfig;
199207

208+
$this->baseURI = clone $this->defaultBaseURI;
209+
$this->delay = 0.0;
210+
200211
// Set the default options for next request
201212
$this->parseOptions($this->defaultOptions);
202213
}
Lines changed: 310 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,310 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\HTTP;
15+
16+
use CodeIgniter\Config\Factories;
17+
use CodeIgniter\HTTP\Exceptions\HTTPException;
18+
use CodeIgniter\Test\CIUnitTestCase;
19+
use CodeIgniter\Test\Mock\MockCURLRequest;
20+
use Config\App;
21+
use Config\CURLRequest as ConfigCURLRequest;
22+
use InvalidArgumentException;
23+
use PHPUnit\Framework\Attributes\DataProvider;
24+
use PHPUnit\Framework\Attributes\Group;
25+
use Throwable;
26+
27+
/**
28+
* @internal
29+
*/
30+
#[Group('Others')]
31+
final class CURLRequestExceptionTest extends CIUnitTestCase
32+
{
33+
#[DataProvider('provideFailureResetsSetterOptions')]
34+
public function testFailureResetsSetterOptions(string $failure, string $setter): void
35+
{
36+
$this->configureSharing(false);
37+
38+
$app = new App();
39+
$request = $failure === 'transport'
40+
? $this->failingRequest()
41+
: new MockCURLRequest($app, new URI(), new Response($app));
42+
43+
$request->setHeader('Authorization', 'Bearer secret');
44+
45+
match ($setter) {
46+
'auth' => $request->setAuth('user', 'password'),
47+
'body' => $request->setBody('private body'),
48+
'form' => $request->setForm(['private' => 'data']),
49+
'multipart' => $request->setForm(['private' => 'data'], true),
50+
'json' => $request->setJSON(['private' => 'data']),
51+
default => throw new InvalidArgumentException('Unknown setter: ' . $setter),
52+
};
53+
54+
$options = match ($failure) {
55+
'header' => ['headers' => ['Authorization' => 'Bearer secret', 'X-Invalid' => "invalid\0value"]],
56+
'uri' => ['baseURI' => 'https://private.example:invalid/'],
57+
'cert' => ['cert' => 'missing-certificate.pem'],
58+
'verify' => ['verify' => 'missing-ca-bundle.pem'],
59+
default => [],
60+
};
61+
62+
$request->setOutput(match ($failure) {
63+
'response header' => "HTTP/1.1 200 OK\r\nX-Invalid: invalid\0value\r\n\r\nprivate body",
64+
'response status' => "HTTP/1.1 999 Invalid\r\n\r\nprivate body",
65+
default => '',
66+
});
67+
68+
$exception = null;
69+
70+
try {
71+
$request->post('https://private.example/upload', $options);
72+
} catch (Throwable $e) {
73+
$exception = $e;
74+
}
75+
76+
$expectedException = in_array($failure, ['header', 'response header'], true)
77+
? InvalidArgumentException::class
78+
: HTTPException::class;
79+
80+
$this->assertInstanceOf($expectedException, $exception);
81+
$this->assertNull($request->header('Authorization'));
82+
$this->assertNull($request->getBody());
83+
84+
$request->setOutput('');
85+
$request->get('https://other.example/');
86+
87+
$options = $request->curl_options;
88+
89+
$this->assertSame('https://other.example/', $options[CURLOPT_URL]);
90+
$this->assertArrayNotHasKey(CURLOPT_HTTPHEADER, $options);
91+
$this->assertArrayNotHasKey(CURLOPT_POSTFIELDS, $options);
92+
$this->assertArrayNotHasKey(CURLOPT_USERPWD, $options);
93+
}
94+
95+
/**
96+
* @return iterable<string, array{string, string}>
97+
*/
98+
public static function provideFailureResetsSetterOptions(): iterable
99+
{
100+
foreach (['header', 'uri', 'cert', 'verify', 'transport', 'response header', 'response status'] as $failure) {
101+
foreach (['auth', 'body', 'form', 'multipart', 'json'] as $setter) {
102+
yield $failure . ' with ' . $setter => [$failure, $setter];
103+
}
104+
}
105+
}
106+
107+
#[DataProvider('provideRequestRestoresBaseURIAndDelay')]
108+
public function testRequestRestoresBaseURIAndDelay(bool $fail, string $defaults): void
109+
{
110+
$this->configureSharing(false);
111+
112+
$baseURI = 'https://default.example/api/?default=value';
113+
$options = $defaults === 'options' ? ['baseURI' => $baseURI, 'delay' => 100] : [];
114+
$uri = $defaults === 'uri' ? new URI($baseURI) : new URI();
115+
$app = new App();
116+
$request = $fail
117+
? $this->failingRequest($options, $uri)
118+
: new MockCURLRequest($app, $uri, new Response($app), $options);
119+
120+
try {
121+
$request->get('reports', [
122+
'baseURI' => 'https://alice@private.example:8443/v2/?api_key=secret#private',
123+
'delay' => 200,
124+
]);
125+
$this->assertFalse($fail, 'Expected a transport exception.');
126+
} catch (HTTPException $e) {
127+
$this->assertTrue($fail);
128+
$this->assertStringContainsString('simulated transport failure', $e->getMessage());
129+
}
130+
131+
$expectedURI = $defaults === 'none' ? (string) new URI() : $baseURI;
132+
$this->assertSame($expectedURI, (string) $request->getBaseURI());
133+
$this->assertEqualsWithDelta($defaults === 'options' ? 0.1 : 0.0, $request->getDelay(), PHP_FLOAT_EPSILON);
134+
135+
// Mutating the restored URI must not mutate the saved constructor defaults.
136+
$request->get('reports', ['baseURI' => 'https://bob@private.example:9443/v3/?token=secret']);
137+
$this->assertSame($expectedURI, (string) $request->getBaseURI());
138+
139+
$request->get('', ['baseURI' => 'https://other.example/']);
140+
141+
$expectedURL = $defaults === 'none' ? 'https://other.example/' : 'https://other.example/?default=value';
142+
$this->assertSame($expectedURL, $request->curl_options[CURLOPT_URL]);
143+
$this->assertSame($expectedURI, (string) $request->getBaseURI());
144+
}
145+
146+
/**
147+
* @return iterable<string, array{bool, string}>
148+
*/
149+
public static function provideRequestRestoresBaseURIAndDelay(): iterable
150+
{
151+
foreach ([false, true] as $fail) {
152+
foreach (['none', 'uri', 'options'] as $defaults) {
153+
yield ($fail ? 'failure' : 'success') . ' with ' . $defaults => [$fail, $defaults];
154+
}
155+
}
156+
}
157+
158+
#[DataProvider('provideSharingPreservesBaseURIAndDelay')]
159+
public function testSharingPreservesBaseURIAndDelay(bool $fail): void
160+
{
161+
$this->configureSharing(true);
162+
163+
$app = new App();
164+
$request = $fail
165+
? $this->failingRequest()
166+
: new MockCURLRequest($app, new URI(), new Response($app));
167+
$baseURI = 'https://alice@private.example:8443/v2/?api_key=secret';
168+
169+
try {
170+
$request->get('reports', ['baseURI' => $baseURI, 'delay' => 200]);
171+
$this->assertFalse($fail, 'Expected a transport exception.');
172+
} catch (HTTPException $e) {
173+
$this->assertTrue($fail);
174+
$this->assertStringContainsString('simulated transport failure', $e->getMessage());
175+
}
176+
177+
$this->assertSame($baseURI, (string) $request->getBaseURI());
178+
$this->assertEqualsWithDelta(0.2, $request->getDelay(), PHP_FLOAT_EPSILON);
179+
}
180+
181+
/**
182+
* @return iterable<string, array{bool}>
183+
*/
184+
public static function provideSharingPreservesBaseURIAndDelay(): iterable
185+
{
186+
yield 'success' => [false];
187+
188+
yield 'failure' => [true];
189+
}
190+
191+
public function testTransportFailureResetsRequestOptions(): void
192+
{
193+
$this->configureSharing(false);
194+
195+
$request = $this->failingRequest([
196+
'headers' => ['X-Default' => 'configured'],
197+
'user_agent' => 'DefaultAgent',
198+
]);
199+
200+
try {
201+
$request->post('https://private.example/upload', [
202+
'headers' => ['Authorization' => 'Bearer secret'],
203+
'body' => 'private body',
204+
'auth' => ['user', 'password'],
205+
'proxy' => 'http://proxy.example:3128',
206+
]);
207+
$this->fail('Expected a transport exception.');
208+
} catch (HTTPException $e) {
209+
$this->assertStringContainsString('simulated transport failure', $e->getMessage());
210+
}
211+
212+
$this->assertNull($request->header('Authorization'));
213+
$this->assertNull($request->getBody());
214+
215+
$request->get('https://other.example/');
216+
217+
$options = $request->curl_options;
218+
219+
$this->assertSame('https://other.example/', $options[CURLOPT_URL]);
220+
$this->assertSame(['X-Default: configured'], $options[CURLOPT_HTTPHEADER]);
221+
$this->assertSame('DefaultAgent', $options[CURLOPT_USERAGENT]);
222+
$this->assertArrayNotHasKey(CURLOPT_POSTFIELDS, $options);
223+
$this->assertArrayNotHasKey(CURLOPT_USERPWD, $options);
224+
$this->assertArrayNotHasKey(CURLOPT_PROXY, $options);
225+
}
226+
227+
public function testOptionValidationFailureResetsRequestOptions(): void
228+
{
229+
$this->configureSharing(false);
230+
231+
$app = new App();
232+
$request = new MockCURLRequest($app, new URI(), new Response($app));
233+
234+
try {
235+
$request->post('https://private.example/upload', [
236+
'headers' => ['Authorization' => 'Bearer secret'],
237+
'body' => 'private body',
238+
'cert' => 'missing-certificate.pem',
239+
]);
240+
$this->fail('Expected an invalid certificate exception.');
241+
} catch (HTTPException $e) {
242+
$this->assertStringContainsString('missing-certificate.pem', $e->getMessage());
243+
}
244+
245+
$this->assertNull($request->header('Authorization'));
246+
$this->assertNull($request->getBody());
247+
248+
$request->get('https://other.example/');
249+
250+
$options = $request->curl_options;
251+
252+
$this->assertArrayNotHasKey(CURLOPT_HTTPHEADER, $options);
253+
$this->assertArrayNotHasKey(CURLOPT_POSTFIELDS, $options);
254+
}
255+
256+
public function testTransportFailureKeepsOptionsWhenSharingEnabled(): void
257+
{
258+
$this->configureSharing(true);
259+
260+
$request = $this->failingRequest();
261+
262+
try {
263+
$request->post('https://private.example/upload', [
264+
'headers' => ['Authorization' => 'Bearer secret'],
265+
'body' => 'private body',
266+
]);
267+
$this->fail('Expected a transport exception.');
268+
} catch (HTTPException $e) {
269+
$this->assertStringContainsString('simulated transport failure', $e->getMessage());
270+
}
271+
272+
$request->get('https://other.example/');
273+
274+
$options = $request->curl_options;
275+
276+
$this->assertSame(['Authorization: Bearer secret'], $options[CURLOPT_HTTPHEADER]);
277+
$this->assertSame('private body', $options[CURLOPT_POSTFIELDS]);
278+
}
279+
280+
/**
281+
* @param array<string, mixed> $options
282+
*/
283+
private function failingRequest(array $options = [], ?URI $uri = null): MockCURLRequest
284+
{
285+
$app = new App();
286+
287+
return new class ($app, $uri ?? new URI(), new Response($app), $options) extends MockCURLRequest {
288+
private bool $failNextRequest = true;
289+
290+
protected function sendRequest(array $curlOptions = []): string
291+
{
292+
if ($this->failNextRequest) {
293+
$this->failNextRequest = false;
294+
295+
throw HTTPException::forCurlError('7', 'simulated transport failure');
296+
}
297+
298+
return parent::sendRequest($curlOptions);
299+
}
300+
};
301+
}
302+
303+
private function configureSharing(bool $shareOptions): void
304+
{
305+
$config = new ConfigCURLRequest();
306+
$config->shareOptions = $shareOptions;
307+
308+
Factories::injectMock('config', 'CURLRequest', $config);
309+
}
310+
}

‎user_guide_src/source/changelogs/v4.7.5.rst‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,17 @@ Release Date: Unreleased
1414
SECURITY
1515
********
1616

17+
- **CURLRequest:** Request-specific headers, body, and options
18+
are now cleared when a request throws an exception and ``shareOptions`` is ``false``.
19+
Previously, reusing the client after a failed request could send credentials
20+
or private data to a different destination. Options passed to the constructor
21+
remain available for subsequent requests.
22+
Per-request ``baseURI`` and ``delay`` values are also reset after successful
23+
and failed requests, preventing URI components from leaking into later requests.
24+
When retrying a failed request, pass its options again, or reapply settings
25+
made with ``setAuth()``, ``setBody()``, ``setForm()``, or ``setJSON()``.
26+
See the `Security advisory GHSA-9g9v-xgwj-697h <https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-9g9v-xgwj-697h>`_
27+
for more information.
1728
- **Validation:** The ``is_image`` and ``mime_in`` file upload rules now reject client filenames ending in dots while
1829
continuing to accept genuinely extensionless uploads. These rules and ``ext_in`` also reject filenames with a PHP
1930
handler extension before the final extension, such as ``shell.php.gif``, including extensions revealed by filename

0 commit comments

Comments
 (0)