Skip to content

Commit d6dc2d5

Browse files
authored
fix: prevent exception handlers from restarting FrankenPHP workers (#10721)
1 parent 72451b2 commit d6dc2d5

9 files changed

Lines changed: 167 additions & 6 deletions

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,6 @@ Release Date: Unreleased
1515
## Bugs Fixed
1616

1717
- **Security:** Fixed a bug where `Security::__construct()` threw a `TypeError` when the CSRF cookie was an array, causing an HTTP 500 response for affected requests.
18+
- **Worker Mode:** Fixed a bug where every request that ended with an uncaught exception, including a `404 Page Not Found` without a 404 override, called `exit()` in the exception handler. This ended the worker script, so FrankenPHP booted a new one, and the worker loop skipped its cleanup after the request. The exception handler now returns to the worker loop.
1819

1920
See the repo's [CHANGELOG.md](https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md) for a complete list of bugs fixed.

‎docs/installation/worker_mode.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ The `$persistentServices` array controls which services survive between requests
148148
|----|----|
149149
| `autoloader` | PSR-4 autoloading configuration. Safe to persist as class maps don't change. |
150150
| `locator` | File locator for finding framework files. Caches file paths for performance. |
151-
| `exceptions` | Exception handler. Stateless, safe to reuse. |
151+
| `exceptions` | Exception handler. Its request state is cleared before each request. |
152152
| `commands` | CLI commands registry. Only used during worker startup. |
153153
| `codeigniter` | Main application instance. Orchestrates the request/response cycle. |
154154
| `superglobals` | Superglobals wrapper. Properly isolated per request internally. |
@@ -249,6 +249,12 @@ Worker Mode can make debugging more challenging since the process persists acros
249249
- **Check logs** in **writable/logs/** for connection and state-related issues
250250
- **Use logging liberally** to trace request flow across the persistent process
251251

252+
### Error Handling
253+
254+
When a request ends with an uncaught exception, such as a `PageNotFoundException`, the exception handler displays the error and returns to the worker loop, which cleans up after the request as usual. The worker does not restart.
255+
256+
If you use a custom exception handler (see [Custom Exception Handlers](../general/errors.md#custom-exception-handlers)), do not call `exit()` in it. In Worker Mode, `exit()` ends the worker script, and FrankenPHP has to boot a new one.
257+
252258
### Session and Cache Handlers
253259

254260
**File-based handlers** may experience file locking contention between workers. For production environments, consider using:

‎system/Boot.php‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@
3030
*/
3131
class Boot
3232
{
33+
/**
34+
* Whether the application was booted by `bootWorker()`.
35+
*/
36+
private static bool $workerMode = false;
37+
3338
/**
3439
* Used by `public/index.php`
3540
*
@@ -87,6 +92,8 @@ public static function bootWeb(Paths $paths): int
8792
*/
8893
public static function bootWorker(Paths $paths): CodeIgniter
8994
{
95+
self::$workerMode = true;
96+
9097
static::definePathConstants($paths);
9198
if (! defined('APP_NAMESPACE')) {
9299
static::loadConstants();
@@ -109,6 +116,16 @@ public static function bootWorker(Paths $paths): CodeIgniter
109116
return Boot::initializeCodeIgniter();
110117
}
111118

119+
/**
120+
* Whether the application runs in FrankenPHP worker mode.
121+
*
122+
* @internal
123+
*/
124+
public static function isWorkerMode(): bool
125+
{
126+
return self::$workerMode;
127+
}
128+
112129
/**
113130
* Used by command line scripts other than
114131
* * `spark`

‎system/CodeIgniter.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,10 @@ public function resetForWorkerMode(): void
208208
$this->totalTime = 0;
209209

210210
$this->resetKintForWorkerMode();
211+
212+
if (Services::has('exceptions')) {
213+
Services::exceptions()->resetForWorkerMode();
214+
}
211215
}
212216

213217
/**

‎system/Debug/ExceptionHandler.php‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use Closure;
1717
use CodeIgniter\API\ResponseTrait;
18+
use CodeIgniter\Boot;
1819
use CodeIgniter\Exceptions\PageNotFoundException;
1920
use CodeIgniter\HTTP\CLIRequest;
2021
use CodeIgniter\HTTP\Exceptions\HTTPException;
@@ -91,7 +92,7 @@ public function handle(
9192

9293
$this->respond($data, $statusCode)->send();
9394

94-
if (ENVIRONMENT !== 'testing') {
95+
if ($this->shouldExit()) {
9596
// @codeCoverageIgnoreStart
9697
exit($exitCode);
9798
// @codeCoverageIgnoreEnd
@@ -122,13 +123,24 @@ public function handle(
122123
// Displays the HTML or CLI error code.
123124
$this->render($exception, $statusCode, $viewFile);
124125

125-
if (ENVIRONMENT !== 'testing') {
126+
if ($this->shouldExit()) {
126127
// @codeCoverageIgnoreStart
127128
exit($exitCode);
128129
// @codeCoverageIgnoreEnd
129130
}
130131
}
131132

133+
/**
134+
* Whether to end the script after the error is displayed.
135+
*
136+
* In worker mode, the worker loop must keep running, so the
137+
* handler returns and the worker cleans up after the request.
138+
*/
139+
private function shouldExit(): bool
140+
{
141+
return ENVIRONMENT !== 'testing' && ! Boot::isWorkerMode();
142+
}
143+
132144
/**
133145
* Determines the view to display based on the exception thrown, HTTP status
134146
* code, whether an HTTP or CLI request, etc.

‎system/Debug/Exceptions.php‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
namespace CodeIgniter\Debug;
1515

1616
use CodeIgniter\API\ResponseTrait;
17+
use CodeIgniter\Boot;
1718
use CodeIgniter\Exceptions\HasExitCodeInterface;
1819
use CodeIgniter\Exceptions\HTTPExceptionInterface;
1920
use CodeIgniter\Exceptions\PageNotFoundException;
@@ -69,7 +70,7 @@ class Exceptions
6970
/**
7071
* The outgoing response.
7172
*
72-
* @var ResponseInterface
73+
* @var ResponseInterface|null
7374
*/
7475
protected $response;
7576

@@ -174,13 +175,31 @@ public function exceptionHandler(Throwable $exception)
174175
if (! str_contains($this->request->getHeaderLine('accept'), 'text/html')) {
175176
$this->respond(ENVIRONMENT === 'development' ? $this->collectVars($exception, $statusCode) : '', $statusCode)->send();
176177

177-
exit($exitCode);
178+
if (! Boot::isWorkerMode()) {
179+
exit($exitCode);
180+
}
181+
182+
return;
178183
}
179184
}
180185

181186
$this->render($exception, $statusCode);
182187

183-
exit($exitCode);
188+
if (! Boot::isWorkerMode()) {
189+
exit($exitCode);
190+
}
191+
}
192+
193+
/**
194+
* Clears the state of the previous request in worker mode.
195+
*
196+
* @internal
197+
*/
198+
public function resetForWorkerMode(): void
199+
{
200+
$this->exceptionCaughtByExceptionHandler = null;
201+
$this->request = null;
202+
$this->response = null;
184203
}
185204

186205
/**

‎tests/system/CodeIgniterTest.php‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use CodeIgniter\Config\Services;
1919
use CodeIgniter\Debug\Timer;
2020
use CodeIgniter\Exceptions\PageNotFoundException;
21+
use CodeIgniter\Exceptions\RuntimeException;
2122
use CodeIgniter\HTTP\Method;
2223
use CodeIgniter\HTTP\Response;
2324
use CodeIgniter\HTTP\ResponseInterface;
@@ -1309,6 +1310,23 @@ public function testResetForWorkerMode(): void
13091310
$this->assertTrue(RichRenderer::$needs_pre_render);
13101311
}
13111312

1313+
public function testResetForWorkerModeClearsExceptionsState(): void
1314+
{
1315+
$this->resetServices();
1316+
1317+
$exceptions = Services::exceptions();
1318+
$this->setPrivateProperty($exceptions, 'exceptionCaughtByExceptionHandler', new RuntimeException('Previous request'));
1319+
$this->setPrivateProperty($exceptions, 'request', service('request'));
1320+
$this->setPrivateProperty($exceptions, 'response', service('response'));
1321+
1322+
$codeigniter = new MockCodeIgniter(new App());
1323+
$codeigniter->resetForWorkerMode();
1324+
1325+
$this->assertNull($this->getPrivateProperty($exceptions, 'exceptionCaughtByExceptionHandler'));
1326+
$this->assertNull($this->getPrivateProperty($exceptions, 'request'));
1327+
$this->assertNull($this->getPrivateProperty($exceptions, 'response'));
1328+
}
1329+
13121330
public function testGatherOutputCalledOnceWhenControllerReturnsResponse(): void
13131331
{
13141332
$this->resetServices();

‎tests/system/Debug/ExceptionHandlerTest.php‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
use CodeIgniter\Test\StreamFilterTrait;
2323
use Config\Exceptions as ExceptionsConfig;
2424
use Config\Services;
25+
use PHPUnit\Framework\Attributes\DataProvider;
2526
use PHPUnit\Framework\Attributes\Group;
2627
use stdClass;
2728

@@ -168,6 +169,76 @@ public function testHandleCLIPageNotFoundException(): void
168169
$this->resetStreamFilterBuffer();
169170
}
170171

172+
/**
173+
* The handler can only exit outside the testing environment, so it
174+
* runs in a separate process with the production environment.
175+
*/
176+
#[DataProvider('provideHandleWebExceptionExitBehavior')]
177+
public function testHandleWebExceptionExitBehavior(
178+
string $accept,
179+
bool $workerMode,
180+
string $expectedOutput,
181+
int $expectedStatus,
182+
): void {
183+
$escapedHomePath = var_export(HOMEPATH, true);
184+
$escapedBootstrap = var_export(SYSTEMPATH . 'util_bootstrap.php', true);
185+
$escapedAccept = var_export($accept, true);
186+
$escapedWorker = var_export($workerMode, true);
187+
188+
$code = <<<PHP
189+
chdir({$escapedHomePath});
190+
define('ENVIRONMENT', 'production');
191+
require {$escapedBootstrap};
192+
193+
use CodeIgniter\\Boot;
194+
use CodeIgniter\\Debug\\ExceptionHandler;
195+
use CodeIgniter\\Exceptions\\PageNotFoundException;
196+
use Config\\Exceptions as ExceptionsConfig;
197+
198+
(new \\ReflectionProperty(Boot::class, 'workerMode'))->setValue(null, {$escapedWorker});
199+
200+
\$request = service('incomingrequest', null, false);
201+
\$request->setHeader('accept', {$escapedAccept});
202+
203+
(new ExceptionHandler(new ExceptionsConfig()))->handle(
204+
PageNotFoundException::forPageNotFound(),
205+
\$request,
206+
service('response'),
207+
404,
208+
EXIT_UNKNOWN_FILE,
209+
);
210+
211+
echo 'HANDLER RETURNED';
212+
PHP;
213+
214+
$cmd = sprintf('%s -r %s 2>&1', escapeshellarg(PHP_BINARY), escapeshellarg($code));
215+
exec($cmd, $output, $status);
216+
$output = implode(PHP_EOL, $output);
217+
218+
$this->assertSame($expectedStatus, $status, $output);
219+
$this->assertStringContainsString($expectedOutput, $output);
220+
221+
if ($workerMode) {
222+
$this->assertStringEndsWith('HANDLER RETURNED', $output);
223+
} else {
224+
$this->assertStringNotContainsString('HANDLER RETURNED', $output);
225+
}
226+
}
227+
228+
/**
229+
* @return iterable<string, array{string, bool, string, int}>
230+
*/
231+
public static function provideHandleWebExceptionExitBehavior(): iterable
232+
{
233+
yield 'non-HTML, worker mode' => ['application/json', true, '""', 0];
234+
235+
yield 'non-HTML, traditional' => ['application/json', false, '""', EXIT_UNKNOWN_FILE];
236+
237+
yield 'HTML, worker mode' => ['text/html', true, '<title>404 - Page Not Found</title>', 0];
238+
239+
yield 'HTML, traditional' => ['text/html', false, '<title>404 - Page Not Found</title>', EXIT_UNKNOWN_FILE];
240+
}
241+
171242
public function testMaskSensitiveData(): void
172243
{
173244
$maskSensitiveData = self::getPrivateMethodInvoker($this->handler, 'maskSensitiveData');

‎tests/system/Debug/ExceptionsTest.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,4 +205,17 @@ public function testMaskSensitiveDataTraceDataKey(): void
205205

206206
$this->assertSame('/var/www/CodeIgniter4/app/Controllers/Home.php', $newTrace[0]['file']);
207207
}
208+
209+
public function testResetForWorkerModeClearsPreviousRequestState(): void
210+
{
211+
$this->setPrivateProperty($this->exception, 'exceptionCaughtByExceptionHandler', new RuntimeException('Previous request'));
212+
$this->setPrivateProperty($this->exception, 'request', service('request'));
213+
$this->setPrivateProperty($this->exception, 'response', service('response'));
214+
215+
$this->exception->resetForWorkerMode();
216+
217+
$this->assertNull($this->getPrivateProperty($this->exception, 'exceptionCaughtByExceptionHandler'));
218+
$this->assertNull($this->getPrivateProperty($this->exception, 'request'));
219+
$this->assertNull($this->getPrivateProperty($this->exception, 'response'));
220+
}
208221
}

0 commit comments

Comments
 (0)