Skip to content

Commit 34ed374

Browse files
authored
feat: Add RequestId filter (#10274)
1 parent 944b328 commit 34ed374

8 files changed

Lines changed: 295 additions & 0 deletions

File tree

‎app/Config/Filters.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use CodeIgniter\Filters\InvalidChars;
1212
use CodeIgniter\Filters\PageCache;
1313
use CodeIgniter\Filters\PerformanceMetrics;
14+
use CodeIgniter\Filters\RequestId;
1415
use CodeIgniter\Filters\SecureHeaders;
1516

1617
class Filters extends BaseFilters
@@ -34,6 +35,7 @@ class Filters extends BaseFilters
3435
'forcehttps' => ForceHTTPS::class,
3536
'pagecache' => PageCache::class,
3637
'performance' => PerformanceMetrics::class,
38+
'requestid' => RequestId::class,
3739
];
3840

3941
/**
@@ -51,11 +53,13 @@ class Filters extends BaseFilters
5153
*/
5254
public array $required = [
5355
'before' => [
56+
// 'requestid', // Request ID for each request
5457
'forcehttps', // Force Global Secure Requests
5558
'pagecache', // Web Page Caching
5659
],
5760
'after' => [
5861
'pagecache', // Web Page Caching
62+
// 'requestid', // Request ID for each request
5963
'performance', // Performance Metrics
6064
'toolbar', // Debug Toolbar
6165
],

‎system/Config/Filters.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
use CodeIgniter\Filters\InvalidChars;
2222
use CodeIgniter\Filters\PageCache;
2323
use CodeIgniter\Filters\PerformanceMetrics;
24+
use CodeIgniter\Filters\RequestId;
2425
use CodeIgniter\Filters\SecureHeaders;
2526

2627
/**
@@ -47,6 +48,7 @@ class Filters extends BaseConfig
4748
'forcehttps' => ForceHTTPS::class,
4849
'pagecache' => PageCache::class,
4950
'performance' => PerformanceMetrics::class,
51+
'requestid' => RequestId::class,
5052
];
5153

5254
/**
@@ -64,11 +66,13 @@ class Filters extends BaseConfig
6466
*/
6567
public array $required = [
6668
'before' => [
69+
// 'requestid', // Request ID for each request
6770
'forcehttps', // Force Global Secure Requests
6871
'pagecache', // Web Page Caching
6972
],
7073
'after' => [
7174
'pagecache', // Web Page Caching
75+
// 'requestid', // Request ID for each request
7276
'performance', // Performance Metrics
7377
'toolbar', // Debug Toolbar
7478
],

‎system/Filters/RequestId.php‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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\Filters;
15+
16+
use CodeIgniter\HTTP\RequestInterface;
17+
use CodeIgniter\HTTP\ResponseInterface;
18+
19+
class RequestId implements FilterInterface
20+
{
21+
/**
22+
* Generates a unique request ID for each incoming request and adds it to the request context.
23+
* If the incoming request already has X-Request-ID header, then that header is used instead.
24+
*
25+
* {@inheritDoc}
26+
*/
27+
public function before(RequestInterface $request, $arguments = null): ?ResponseInterface
28+
{
29+
$requestId = trim($request->getHeaderLine('X-Request-ID'));
30+
31+
if (! $this->isValidRequestId($requestId)) {
32+
$requestId = bin2hex(random_bytes(16));
33+
}
34+
35+
context()->set('request_id', $requestId);
36+
37+
$request->setHeader('X-Request-ID', $requestId);
38+
39+
return null;
40+
}
41+
42+
/**
43+
* {@inheritDoc}
44+
*/
45+
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null): ?ResponseInterface
46+
{
47+
if (context()->has('request_id')) {
48+
$response->setHeader('X-Request-ID', context()->get('request_id'));
49+
}
50+
51+
return null;
52+
}
53+
54+
private function isValidRequestId(string $requestId): bool
55+
{
56+
if ($requestId === '') {
57+
return false;
58+
}
59+
60+
if (strlen($requestId) > 64) {
61+
return false;
62+
}
63+
64+
return preg_match('/^[A-Za-z0-9._:-]+$/', $requestId) === 1;
65+
}
66+
}
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
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\Filters;
15+
16+
use CodeIgniter\Test\CIUnitTestCase;
17+
use PHPUnit\Framework\Attributes\Group;
18+
19+
/**
20+
* @internal
21+
*/
22+
#[Group('Others')]
23+
final class RequestIdTest extends CIUnitTestCase
24+
{
25+
protected function setUp(): void
26+
{
27+
parent::setUp();
28+
29+
context()->clearAll();
30+
}
31+
32+
public function testBefore(): void
33+
{
34+
$filter = new RequestId();
35+
$request = service('request', null, false);
36+
37+
$filter->before($request);
38+
39+
$requestId = context()->get('request_id');
40+
41+
$requestIdFromHeader = $request->getHeaderLine('X-Request-ID');
42+
43+
$this->assertNotEmpty($requestId);
44+
$this->assertSame($requestId, $requestIdFromHeader);
45+
$this->assertSame(32, strlen($requestId));
46+
$this->assertMatchesRegularExpression('/^[A-Za-z0-9._:-]+$/', $requestId);
47+
}
48+
49+
public function testBeforeWithExistingRequestId(): void
50+
{
51+
$filter = new RequestId();
52+
$request = service('request', null, false);
53+
54+
$existingRequestId = 'test-request-id-123';
55+
$request->setHeader('X-Request-ID', $existingRequestId);
56+
57+
$filter->before($request);
58+
59+
$requestId = context()->get('request_id');
60+
61+
$requestIdFromHeader = $request->getHeaderLine('X-Request-ID');
62+
63+
$this->assertSame($existingRequestId, $requestId);
64+
$this->assertSame($existingRequestId, $requestIdFromHeader);
65+
$this->assertMatchesRegularExpression('/^[A-Za-z0-9._:-]+$/', $requestId);
66+
}
67+
68+
public function testBeforeWithExistingInvalidRequestId(): void
69+
{
70+
$filter = new RequestId();
71+
$request = service('request', null, false);
72+
73+
$existingRequestId = 'Abc@!#$';
74+
$request->setHeader('X-Request-ID', $existingRequestId);
75+
76+
$filter->before($request);
77+
78+
$requestId = context()->get('request_id');
79+
80+
$requestIdFromHeader = $request->getHeaderLine('X-Request-ID');
81+
82+
$this->assertNotSame($existingRequestId, $requestId);
83+
$this->assertSame($requestId, $requestIdFromHeader);
84+
$this->assertSame(32, strlen($requestId));
85+
$this->assertMatchesRegularExpression('/^[A-Za-z0-9._:-]+$/', $requestId);
86+
}
87+
88+
public function testBeforeWithExistingLongRequestId(): void
89+
{
90+
$filter = new RequestId();
91+
$request = service('request', null, false);
92+
93+
$existingRequestId = str_repeat('a', 65);
94+
$request->setHeader('X-Request-ID', $existingRequestId);
95+
96+
$filter->before($request);
97+
98+
$requestId = context()->get('request_id');
99+
100+
$requestIdFromHeader = $request->getHeaderLine('X-Request-ID');
101+
102+
$this->assertNotSame($existingRequestId, $requestId);
103+
$this->assertSame($requestId, $requestIdFromHeader);
104+
$this->assertSame(32, strlen($requestId));
105+
$this->assertMatchesRegularExpression('/^[A-Za-z0-9._:-]+$/', $requestId);
106+
}
107+
108+
public function testAfter(): void
109+
{
110+
$filter = new RequestId();
111+
$request = service('request', null, false);
112+
$response = service('response', null, false);
113+
114+
context()->set('request_id', 'test-request-id-123');
115+
116+
$filter->after($request, $response);
117+
118+
$this->assertTrue($response->hasHeader('X-Request-ID'));
119+
$this->assertSame('test-request-id-123', $response->getHeaderLine('X-Request-ID'));
120+
}
121+
122+
public function testAfterWithoutRequestId(): void
123+
{
124+
$filter = new RequestId();
125+
$request = service('request', null, false);
126+
$response = service('response', null, false);
127+
128+
context()->remove('request_id');
129+
130+
$filter->after($request, $response);
131+
132+
$this->assertFalse($response->hasHeader('X-Request-ID'));
133+
}
134+
135+
public function testResponseOutputsRequestIdFromRequestHeader(): void
136+
{
137+
$filter = new RequestId();
138+
$request = service('request', null, false);
139+
$response = service('response', null, false);
140+
141+
$existingRequestId = 'test-request-id-123';
142+
$request->setHeader('X-Request-ID', $existingRequestId);
143+
144+
$filter->before($request);
145+
146+
$filter->after($request, $response);
147+
148+
$this->assertTrue($response->hasHeader('X-Request-ID'));
149+
$this->assertSame($existingRequestId, $response->getHeaderLine('X-Request-ID'));
150+
}
151+
152+
public function testResponseOutputsGeneratedRequestId(): void
153+
{
154+
$filter = new RequestId();
155+
$request = service('request', null, false);
156+
$response = service('response', null, false);
157+
158+
context()->remove('request_id');
159+
160+
$filter->before($request);
161+
162+
$generatedRequestId = context()->get('request_id');
163+
164+
$filter->after($request, $response);
165+
166+
$this->assertTrue($response->hasHeader('X-Request-ID'));
167+
$this->assertSame($generatedRequestId, $response->getHeaderLine('X-Request-ID'));
168+
}
169+
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ Others
312312
- **Float and Double Casting:** Added support for precision and rounding mode when casting to float or double in entities.
313313
- Added ``CodeIgniter\Input\InputData`` and ``InputDataFactory`` for reusable typed input data objects.
314314
- Float and Double casting now throws ``CastException::forInvalidFloatRoundingMode()`` if an rounding mode other than up, down, even or odd is provided.
315+
- **Filters:** Added ``RequestId`` filter for request tracing and correlation logging. The filter stores the request ID in the request context and automatically adds the ``X-Request-ID`` response header. Incoming ``X-Request-ID`` headers are used when valid. See :ref:`requestid` for details.
315316
- **Environment:** Added ``CodeIgniter\EnvironmentDetector`` class and corresponding ``environment`` service as a mockable wrapper around the ``ENVIRONMENT`` constant.
316317
Framework internals that previously compared ``ENVIRONMENT`` directly now go through this service, making environment-specific branches reachable in tests via ``Services::injectMock()``. See :ref:`environment-detector-service`.
317318
- **Time:** Added ``Time::between()``, ``Time::min()``, and ``Time::max()`` comparison helpers. See :ref:`between <time-comparing-two-times-between>`, :ref:`min <time-comparing-two-times-min>`, and :ref:`max <time-comparing-two-times-max>`.

‎user_guide_src/source/incoming/filters.rst‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,7 @@ The filters bundled with CodeIgniter4 are:
315315
- ``forcehttps`` => :ref:`forcehttps`
316316
- ``pagecache`` => :doc:`PageCache <../general/caching>`
317317
- ``performance`` => :ref:`performancemetrics`
318+
- ``requestid`` => :ref:`requestid`
318319

319320
.. note:: The filters are executed in the order defined in the config file. However, if enabled, ``DebugToolbar`` is always executed last because it should be able to capture everything that happens in the other filters.
320321

@@ -377,3 +378,26 @@ If you want to customize the headers, extend ``CodeIgniter\Filters\SecureHeaders
377378
.. literalinclude:: filters/011.php
378379

379380
If you want to know about secure headers, see `OWASP Secure Headers Project <https://owasp.org/www-project-secure-headers/>`_.
381+
382+
.. _requestid:
383+
384+
Request ID
385+
==========
386+
387+
.. versionadded:: 4.8.0
388+
389+
This filter adds a request ID to each request in context of the application. This can be useful for
390+
debugging and logging purposes, as it allows you to trace a specific request through the application.
391+
392+
Framework-generated IDs are 32-character hexadecimal strings and are unique for practical purposes, however valid incoming IDs are reused.
393+
It is added to the request's context and can be accessed via the ``request_id`` key.
394+
395+
To enable this filter, simply add/uncomment the ``requestid`` alias in the ``$required['before']`` and ``$required['after']`` array in **app/Config/Filters.php**:
396+
397+
.. literalinclude:: filters/014.php
398+
399+
.. note:: If the incoming request has a header named ``X-Request-ID``, the value of that header
400+
will be used as the request ID instead of generating a new one or checking for uniqueness.
401+
The framework does basic validation to ensure that the incoming request ID is a non-empty string,
402+
has at most 64 characters, and contains only valid characters (alphanumeric, dot, underscore, colon, and hyphen).
403+
If the validation fails, a new request ID will be generated as normal. This allows you to pass in your own request ID if you have one available, such as from a client or a load balancer.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace Config;
4+
5+
use CodeIgniter\Config\BaseConfig;
6+
7+
class Filters extends BaseConfig
8+
{
9+
// ...
10+
public array $required = [
11+
'before' => [
12+
'requestid', // Request ID for each request
13+
'forcehttps', // Force Global Secure Requests
14+
'pagecache', // Web Page Caching
15+
],
16+
'after' => [
17+
'pagecache', // Web Page Caching
18+
'requestid', // Request ID for each request
19+
'performance', // Performance Metrics
20+
'toolbar', // Debug Toolbar
21+
],
22+
];
23+
24+
// ...
25+
}

‎user_guide_src/source/installation/upgrade_480.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ and it is recommended that you merge the updated versions with your application:
7373
Config
7474
------
7575

76+
- app/Config/Filters.php
77+
- Added a new filter named ``requestid`` that adds a unique request ID to each request in the application's context.
7678
- app/Config/Mimes.php
7779
- ``Config\Mimes::$mimes`` added a new key ``md`` for Markdown files.
7880
- app/Config/Routing.php

0 commit comments

Comments
 (0)