Skip to content

Commit 4048c15

Browse files
committed
Apply code suggestions
1 parent 144733b commit 4048c15

10 files changed

Lines changed: 196 additions & 59 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
/**
@@ -52,10 +54,12 @@ class Filters extends BaseFilters
5254
public array $required = [
5355
'before' => [
5456
'forcehttps', // Force Global Secure Requests
57+
// 'requestid', // Request ID for each request
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
/**
@@ -65,10 +67,12 @@ class Filters extends BaseConfig
6567
public array $required = [
6668
'before' => [
6769
'forcehttps', // Force Global Secure Requests
70+
// 'requestid', // Request ID for each request
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: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
/**
4+
* This file is part of CodeIgniter 4 framework.
5+
*
6+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
7+
*
8+
* For the full copyright and license information, please view
9+
* the LICENSE file that was distributed with this source code.
10+
*/
11+
12+
namespace CodeIgniter\Filters;
13+
14+
use CodeIgniter\HTTP\RequestInterface;
15+
use CodeIgniter\HTTP\ResponseInterface;
16+
17+
class RequestId implements FilterInterface
18+
{
19+
/**
20+
* Generates a unique request ID for each incoming request and adds it to the request context.
21+
* If the incoming request already has X-Request-ID header, then that header is used instead.
22+
*
23+
* {@inheritDoc}
24+
*/
25+
public function before(RequestInterface $request, $arguments = null): ?ResponseInterface
26+
{
27+
$requestId = trim($request->getHeaderLine('X-Request-ID'));
28+
29+
if (! $this->isValidRequestId($requestId)) {
30+
$requestId = bin2hex(random_bytes(16));
31+
}
32+
33+
context()->set('request_id', $requestId);
34+
35+
return null;
36+
}
37+
38+
/**
39+
* {@inheritDoc}
40+
*/
41+
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null): ?ResponseInterface
42+
{
43+
$response->setHeader('X-Request-ID', context()->get('request_id'));
44+
45+
return null;
46+
}
47+
48+
private function isValidRequestId(string $requestId): bool
49+
{
50+
if ($requestId === '') {
51+
return false;
52+
}
53+
54+
if (strlen($requestId) > 255) {
55+
return false;
56+
}
57+
58+
return preg_match('/^[A-Za-z0-9._:-]+$/', $requestId) === 1;
59+
}
60+
}

‎system/HTTP/IncomingRequest.php‎

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,6 @@
4949
*/
5050
class IncomingRequest extends Request
5151
{
52-
/**
53-
* The Request ID associated with this request useful for
54-
* debugging, traceability, and logging.
55-
*
56-
* Incoming request's X-Request-Id header will get priority
57-
* over automatically generated request ids.
58-
*/
59-
protected string $requestId;
60-
6152
/**
6253
* The URI for this request.
6354
*
@@ -167,7 +158,6 @@ public function __construct($config, ?URI $uri = null, $body = 'php://input', ?U
167158
$body = null;
168159
}
169160

170-
$this->requestId = $this->hasHeader('X-Request-ID') ? $this->getHeaderLine('X-Request-ID') : $this->generateRequestId();
171161
$this->uri = $uri;
172162
$this->body = $body;
173163
$this->userAgent = $userAgent;
@@ -189,11 +179,6 @@ public function __clone()
189179
$this->input = null;
190180
}
191181

192-
private function generateRequestId(): string
193-
{
194-
return bin2hex(random_bytes(16));
195-
}
196-
197182
private function getPostMaxSize(): int
198183
{
199184
$postMaxSize = ini_get('post_max_size');
@@ -206,11 +191,6 @@ private function getPostMaxSize(): int
206191
};
207192
}
208193

209-
public function getRequestId(): string
210-
{
211-
return $this->requestId;
212-
}
213-
214194
/**
215195
* Handles setting up the locale, perhaps auto-detecting through
216196
* content negotiation.
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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 RequestIdFilter 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+
$this->assertNotEmpty($requestId);
42+
$this->assertSame(32, strlen($requestId));
43+
$this->assertMatchesRegularExpression('/^[A-Za-z0-9._:-]+$/', $requestId);
44+
}
45+
46+
public function testBeforeWithExistingRequestId(): void
47+
{
48+
$filter = new RequestId();
49+
$request = service('request', null, false);
50+
51+
$existingRequestId = 'test-request-id-123';
52+
$request->setHeader('X-Request-ID', $existingRequestId);
53+
54+
$filter->before($request);
55+
56+
$requestId = context()->get('request_id');
57+
58+
$this->assertSame($existingRequestId, $requestId);
59+
$this->assertMatchesRegularExpression('/^[A-Za-z0-9._:-]+$/', $requestId);
60+
}
61+
62+
public function testBeforeWithExistingInvalidRequestId(): void
63+
{
64+
$filter = new RequestId();
65+
$request = service('request', null, false);
66+
67+
$existingRequestId = 'Abc@!#$';
68+
$request->setHeader('X-Request-ID', $existingRequestId);
69+
70+
$filter->before($request);
71+
72+
$requestId = context()->get('request_id');
73+
74+
$this->assertNotSame($existingRequestId, $requestId);
75+
$this->assertSame(32, strlen($requestId));
76+
$this->assertMatchesRegularExpression('/^[A-Za-z0-9._:-]+$/', $requestId);
77+
}
78+
}

‎tests/system/HTTP/IncomingRequestTest.php‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -62,23 +62,6 @@ private function createRequest(?App $config = null, $body = null, ?string $path
6262
return new IncomingRequest($config, $uri, $body, new UserAgent());
6363
}
6464

65-
public function testAutoGeneratedRequestId(): void
66-
{
67-
$this->assertInstanceOf(IncomingRequest::class, $this->request);
68-
$this->assertNotEmpty($this->request->getRequestId());
69-
$this->assertSame(32, strlen($this->request->getRequestId()));
70-
}
71-
72-
public function testPassedRequestIdDoesntGetReplaced(): void
73-
{
74-
service('superglobals')->setServer('HTTP_X_REQUEST_ID', 'custom-value');
75-
76-
$config = new App();
77-
$request = new IncomingRequest($config, new SiteURI($config), null, new UserAgent());
78-
79-
$this->assertSame('custom-value', $request->getRequestId());
80-
}
81-
8265
public function testCanGrabRequestVars(): void
8366
{
8467
service('superglobals')->setRequest('TEST', '5');

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,6 @@ HTTP
295295
Now you can simply do ``new URI($uri, true)``.
296296
- ``CLIRequest`` now supports parsing array options written multiple times (e.g., ``--option=value1 --option=value2``) into an array of values. This allows you to easily pass multiple values for the same option without needing to use a comma-separated string.
297297
When used with ``CLIRequest::getOption()``, an array option will return its last value (for example, in this case, ``value2``). To retrieve all values for an array option, use ``CLIRequest::getRawOption()``.
298-
- ``IncomingRequest`` now generates a unique request ID for each request and provides it via the new ``getRequestId()`` method. If the request includes an ``X-Request-ID`` header, that value will be used as the request ID instead of generating a new one. See :ref:`request-id` for details.
299298

300299
Validation
301300
==========
@@ -309,6 +308,7 @@ Others
309308
- **Float and Double Casting:** Added support for precision and rounding mode when casting to float or double in entities.
310309
- Added ``CodeIgniter\Input\InputData`` and ``InputDataFactory`` for reusable typed input data objects.
311310
- Float and Double casting now throws ``CastException::forInvalidFloatRoundingMode()`` if an rounding mode other than up, down, even or odd is provided.
311+
- **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.
312312
- **Environment:** Added ``CodeIgniter\EnvironmentDetector`` class and corresponding ``environment`` service as a mockable wrapper around the ``ENVIRONMENT`` constant.
313313
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`.
314314
- **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 unique 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+
This ID is generated by the framework and is unique to this request. It is added to the request's context
393+
and can be accessed via the ``request_id`` key.
394+
395+
The ID is generated via ``bin2hex(random_bytes(16))``, so it is a 32-character hexadecimal string.
396+
397+
To enable this filter, simply un-comment the ``requestid`` alias in the ``$required['before']`` and ``$required['after']`` array in **app/Config/Filters.php**:
398+
399+
.. literalinclude:: filters/014.php
400+
401+
.. note:: If the incoming request has a header named ``X-Request-ID``, the value of that header
402+
will be used as the request ID instead of generating a new one. This allows you to pass in
403+
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+
'forcehttps', // Force Global Secure Requests
13+
'requestid', // Request ID for each request
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/incoming/incomingrequest.rst‎

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -76,27 +76,6 @@ You can also check if the request was made through and HTTPS connection with the
7676

7777
.. literalinclude:: incomingrequest/006.php
7878

79-
.. _request-id:
80-
81-
Getting Request ID
82-
******************
83-
84-
.. versionadded:: 4.8.0
85-
86-
You can get the unique request ID for this request with the ``getRequestID()`` method.
87-
This ID is generated by the framework and is unique to this request.
88-
It can be used for logging or debugging purposes to track a specific request through the application.
89-
The ID is generated via ``bin2hex(random_bytes(16))``, so it is a 32-character hexadecimal string.
90-
91-
.. note:: If the incoming request has a header named ``X-Request-ID``, the value of that header
92-
will be used as the request ID instead of generating a new one. This allows you to pass in
93-
your own request ID if you have one available, such as from a client or a load balancer.
94-
95-
.. code-block:: php
96-
97-
// Returns the request ID, either from the header or generated by the framework
98-
$requestId = $request->getRequestID();
99-
10079
Retrieving Input
10180
****************
10281

0 commit comments

Comments
 (0)