Skip to content

Conversation

@terabytesoftw
Copy link
Member

@terabytesoftw terabytesoftw commented Aug 9, 2025

Q A
Is bugfix? ✔️
New feature?
Breaks BC?

Summary by CodeRabbit

  • Bug Fixes

    • Improved validation of remote IP addresses to ensure only valid IPv4 or IPv6 addresses are returned.
  • Chores

    • Updated system requirements to include the PHP Filter extension.
  • Tests

    • Added new tests to verify correct handling and validation of remote IP addresses.
    • Updated test data providers for comprehensive IP address scenarios.
    • Removed redundant tests related to remote IP retrieval.

…ote IP address and improve handling of server parameters. Add tests for retrieving remote IP from PSR-7 server parameters in `ServerParamsPsr7Test` class.
@coderabbitai
Copy link

coderabbitai bot commented Aug 9, 2025

Walkthrough

The changes introduce validation for remote IP addresses in the getRemoteIP() method, ensuring only valid IPv4 or IPv6 addresses are returned. The composer.json is updated to require the PHP Filter extension. Corresponding tests are added and reorganized to verify the new validation logic, and a data provider for IP address cases is introduced.

Changes

Cohort / File(s) Change Summary
Dependency Update
composer.json
Added "ext-filter": "*" to require the PHP Filter extension.
Remote IP Validation Logic
src/http/Request.php
Enhanced getRemoteIP() with IP validation using filter_var(), updated docblock, and import list.
Test Additions and Refactor
tests/adapter/ServerParamsPsr7Test.php
Added new tests for remote IP retrieval and validation from PSR-7 server params.
Test Removals
tests/adapter/ServerRequestAdapterTest.php
Removed two tests now covered elsewhere, related to remote IP retrieval from PSR-7 server params.
Test Data Provider
tests/provider/RequestProvider.php
Added remoteIPCases() static method to supply various input cases for IP validation tests.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Case
    participant Request as Request Object
    participant PSR7 as PSR-7 Adapter

    Test->>Request: call getRemoteIP()
    Request->>PSR7: get 'REMOTE_ADDR' server param
    PSR7-->>Request: return value (string or other)
    Request->>Request: validate with filter_var()
    alt Valid IP
        Request-->>Test: return IP string
    else Invalid IP
        Request-->>Test: return null
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Poem

A hop and a skip, the code checks the IP,
With filters in place, no fakes slip by me.
The tests all align, like carrots in rows,
Only real addresses—no imposters or woes!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c75e324 and e60646a.

📒 Files selected for processing (1)
  • tests/provider/RequestProvider.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/provider/RequestProvider.php
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix_mini_64

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov
Copy link

codecov bot commented Aug 9, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (e3f3095) to head (e60646a).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff             @@
##                main       #77   +/-   ##
===========================================
  Coverage     100.00%   100.00%           
- Complexity       312       313    +1     
===========================================
  Files             12        12           
  Lines            786       790    +4     
===========================================
+ Hits             786       790    +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@terabytesoftw terabytesoftw added the bug Something isn't working label Aug 9, 2025
@terabytesoftw
Copy link
Member Author

@coderabbitai I wonder if we could replace the getRemoteIP() method tests with tests like testReturnServerParamFromPsr7RequestCases and testReturnServerNameFromServerParamsCases.

@coderabbitai
Copy link

coderabbitai bot commented Aug 9, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find test files related to getRemoteIP
echo "=== Finding test files with getRemoteIP ==="
rg "getRemoteIP" --type php -A 5 -B 2

echo -e "\n=== Finding the mentioned test methods ==="
# Look for testReturnServerParamFromPsr7RequestCases
rg "testReturnServerParamFromPsr7RequestCases" --type php -A 10 -B 2

echo -e "\n=== Finding testReturnServerNameFromServerParamsCases ==="
rg "testReturnServerNameFromServerParamsCases" --type php -A 10 -B 2

echo -e "\n=== Looking for ServerParamsPsr7Test file ==="
fd "ServerParamsPsr7Test.php" --exec cat {}

Length of output: 18777


🏁 Script executed:

#!/bin/bash
# Find the RequestProvider class
echo "=== Finding RequestProvider class ==="
fd "RequestProvider.php" --exec cat {}

echo -e "\n=== Check if there are remoteIPCases or similar data providers ==="
rg "remoteIP|REMOTE_ADDR" tests/provider/ --type php -A 5 -B 2

Length of output: 53081


@terabytesoftw, yes, that's a great idea! The data provider pattern would make the tests more consistent and comprehensive. Here's how you could refactor the getRemoteIP() tests to follow the same pattern:

1. Add a new data provider in RequestProvider.php:

/**
 * @phpstan-return array<array-key, array{mixed, string|null}>
 */
public static function remoteIPCases(): array
{
    return [
        'boolean-false' => [
            false,
            null,
        ],
        'boolean-true' => [
            true,
            null,
        ],
        'empty-array' => [
            [],
            null,
        ],
        'empty-string' => [
            '',
            '',
        ],
        'float' => [
            123.45,
            null,
        ],
        'integer' => [
            12345,
            null,
        ],
        'integer-zero' => [
            0,
            null,
        ],
        'IPv4' => [
            '192.168.1.100',
            '192.168.1.100',
        ],
        'IPv4-local' => [
            '127.0.0.1',
            '127.0.0.1',
        ],
        'IPv6' => [
            '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
            '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
        ],
        'IPv6-compressed' => [
            '::1',
            '::1',
        ],
        'localhost' => [
            'localhost',
            'localhost',
        ],
        'null' => [
            null,
            null,
        ],
        'numeric-string' => [
            '123',
            '123',
        ],
        'object' => [
            (object) ['foo' => 'bar'],
            null,
        ],
        'string-zero' => [
            '0',
            '0',
        ],
    ];
}

2. Replace the existing tests in ServerParamsPsr7Test.php:

#[DataProviderExternal(RequestProvider::class, 'remoteIPCases')]
#[Group('remote-ip')]
public function testReturnRemoteIPFromServerParamsCases(mixed $serverValue, string|null $expected): void
{
    $request = new Request();

    $request->setPsr7Request(
        FactoryHelper::createRequest('GET', '/test', serverParams: ['REMOTE_ADDR' => $serverValue]),
    );

    $actual = $request->getRemoteIP();

    self::assertSame(
        $expected,
        $actual,
        sprintf(
            "'getRemoteIP()' should return '%s' when 'REMOTE_ADDR' is '%s' in PSR-7 'serverParams'. Got: '%s'",
            var_export($expected, true),
            var_export($serverValue, true),
            var_export($actual, true),
        ),
    );
}

#[Group('remote-ip')]
public function testReturnRemoteIPFromPsr7ServerParamsOverridesGlobalServer(): void
{
    $_SERVER['REMOTE_ADDR'] = '192.168.1.100';

    $request = new Request();

    $request->setPsr7Request(
        FactoryHelper::createRequest(
            'GET',
            'https://old.example.com/api',
            serverParams: ['REMOTE_ADDR' => '10.0.0.1'],
        ),
    );

    self::assertSame(
        '10.0.0.1',
        $request->getRemoteIP(),
        "'getRemoteIP()' should return the 'REMOTE_ADDR' value from PSR-7 'serverParams', not from global " .
        '$_SERVER.',
    );
}

This refactoring provides:

  • Better test coverage: Tests various data types and edge cases systematically
  • Consistency: Follows the same pattern as testReturnServerNameFromServerParamsCases and testReturnRemoteHostFromServerParamsCases
  • Maintainability: Easy to add new test cases by extending the data provider
  • Clear test names: Each test case in the data provider has a descriptive name

The override test remains separate as it tests a specific behavior (PSR-7 precedence over global $_SERVER) rather than data type handling.


🧠 Learnings used
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#6
File: tests/http/RequestTest.php:1564-1578
Timestamp: 2025-07-20T16:33:57.495Z
Learning: The TestCase class in yii2-extensions/psr-bridge automatically handles $_SERVER superglobal cleanup by saving its original state before each test and restoring it afterward in setUp() and tearDown() methods. Manual $_SERVER cleanup in individual test methods is unnecessary when extending this TestCase.

Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#6
File: tests/http/RequestTest.php:1536-1552
Timestamp: 2025-07-20T16:35:15.341Z
Learning: In the yii2-extensions/psr-bridge project, the base TestCase class already handles $_SERVER cleanup in setUp() and tearDown() methods (lines 28 and 32), so individual test methods that extend TestCase don't need manual $_SERVER restoration.

Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#6
File: tests/http/RequestTest.php:1536-1552
Timestamp: 2025-07-20T16:35:15.341Z
Learning: In the yii2-extensions/psr-bridge project, the base TestCase class already handles $_SERVER cleanup in setUp() and tearDown() methods, so individual test methods that extend TestCase don't need manual $_SERVER restoration.

Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#71
File: tests/TestCase.php:23-27
Timestamp: 2025-08-08T15:24:06.045Z
Learning: In yii2-extensions/psr-bridge (tests/TestCase.php), maintainer preference: it’s acceptable to use random-looking strings for test-only constants like COOKIE_VALIDATION_KEY; no need to replace with an obviously non-secret value unless CI/secret scanners become problematic.

Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#71
File: tests/adapter/ServerRequestAdapterTest.php:2215-2215
Timestamp: 2025-08-08T15:28:00.137Z
Learning: In yii2-extensions/psr-bridge tests, prefer using self::COOKIE_VALIDATION_KEY from tests/TestCase over hardcoded 'cookieValidationKey' strings to avoid secret scanners FP and improve maintainability.

…verage for `getRemoteIP()` method with various input scenarios.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
tests/provider/RequestProvider.php (2)

880-883: Unify data provider key naming style (nitpick)

Other providers use "numeric string" (with space). Consider aligning this key to keep naming consistent.

-            'numeric-string' => [
+            'numeric string' => [
                 '123',
                 null,
             ],

822-893: Consider adding edge-form cases (ports, brackets, whitespace) to harden coverage

These forms are commonly seen in headers but should be rejected for REMOTE_ADDR; adding them makes intent explicit and avoids regressions.

         return [
+            'invalid-ip' => [
+                '999.999.999.999',
+                null,
+            ],
+            'ipv4-with-port' => [
+                '10.0.0.1:8080',
+                null,
+            ],
+            'ipv6-bracketed' => [
+                '[::1]',
+                null,
+            ],
+            'ipv6-with-port' => [
+                '[::1]:443',
+                null,
+            ],
+            'spaces-around' => [
+                ' 127.0.0.1 ',
+                null,
+            ],
+            'spaces-only' => [
+                '   ',
+                null,
+            ],
+            'zero-address' => [
+                '0.0.0.0',
+                '0.0.0.0',
+            ],
         ];

If you prefer to be lenient and accept whitespace-wrapped IPs, we can instead trim in getRemoteIP() and adjust expectations—let me know.

src/http/Request.php (1)

500-509: Simplify validation and drop redundant flags

FILTER_VALIDATE_IP validates both IPv4 and IPv6 by default. You can streamline the logic and return the validated value directly.

-            if (is_string($remoteIP) === false) {
-                return null;
-            }
-
-            if (filter_var($remoteIP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6) === false) {
-                return null;
-            }
-
-            return $remoteIP;
+            $validated = is_string($remoteIP) ? filter_var($remoteIP, FILTER_VALIDATE_IP) : false;
+            return $validated !== false ? $validated : null;
tests/adapter/ServerParamsPsr7Test.php (1)

163-186: Data-driven test aligns with provider and new validation

Covers many shapes via RequestProvider::remoteIPCases and clear assertion messages. Once you add edge-form cases to the provider (ports/brackets/whitespace), this test will cover them automatically.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e3f3095 and c75e324.

📒 Files selected for processing (5)
  • composer.json (1 hunks)
  • src/http/Request.php (3 hunks)
  • tests/adapter/ServerParamsPsr7Test.php (1 hunks)
  • tests/adapter/ServerRequestAdapterTest.php (0 hunks)
  • tests/provider/RequestProvider.php (1 hunks)
💤 Files with no reviewable changes (1)
  • tests/adapter/ServerRequestAdapterTest.php
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#6
File: tests/http/RequestTest.php:1536-1552
Timestamp: 2025-07-20T16:35:15.341Z
Learning: In the yii2-extensions/psr-bridge project, the base TestCase class already handles $_SERVER cleanup in setUp() and tearDown() methods (lines 28 and 32), so individual test methods that extend TestCase don't need manual $_SERVER restoration.
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#6
File: tests/http/RequestTest.php:1536-1552
Timestamp: 2025-07-20T16:35:15.341Z
Learning: In the yii2-extensions/psr-bridge project, the base TestCase class already handles $_SERVER cleanup in setUp() and tearDown() methods, so individual test methods that extend TestCase don't need manual $_SERVER restoration.
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#6
File: tests/http/RequestTest.php:1564-1578
Timestamp: 2025-07-20T16:33:57.495Z
Learning: The TestCase class in yii2-extensions/psr-bridge automatically handles $_SERVER superglobal cleanup by saving its original state before each test and restoring it afterward in setUp() and tearDown() methods. Manual $_SERVER cleanup in individual test methods is unnecessary when extending this TestCase.
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#71
File: tests/TestCase.php:23-27
Timestamp: 2025-08-08T15:24:06.045Z
Learning: In yii2-extensions/psr-bridge (tests/TestCase.php), maintainer preference: it’s acceptable to use random-looking strings for test-only constants like COOKIE_VALIDATION_KEY; no need to replace with an obviously non-secret value unless CI/secret scanners become problematic.
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#71
File: tests/adapter/ServerRequestAdapterTest.php:2215-2215
Timestamp: 2025-08-08T15:28:00.137Z
Learning: In yii2-extensions/psr-bridge tests, prefer using self::COOKIE_VALIDATION_KEY from tests/TestCase over hardcoded 'cookieValidationKey' strings to avoid secret scanners FP and improve maintainability.
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#71
File: tests/adapter/ServerRequestAdapterTest.php:2215-2215
Timestamp: 2025-08-08T15:28:00.137Z
Learning: In yii2-extensions/psr-bridge, tests extend tests/TestCase which defines a protected const COOKIE_VALIDATION_KEY. Test code should use self::COOKIE_VALIDATION_KEY instead of hardcoded cookieValidationKey literals.
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#64
File: tests/http/StatelessApplicationTest.php:1939-1967
Timestamp: 2025-08-06T22:52:05.608Z
Learning: In yii2-extensions/psr-bridge tests, when testing specific component methods like Request::resolve(), it's necessary to call $app->handle($request) first to initialize all application components before testing the method in isolation. This ensures proper component lifecycle initialization.
📚 Learning: 2025-07-20T16:33:57.495Z
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#6
File: tests/http/RequestTest.php:1564-1578
Timestamp: 2025-07-20T16:33:57.495Z
Learning: The TestCase class in yii2-extensions/psr-bridge automatically handles $_SERVER superglobal cleanup by saving its original state before each test and restoring it afterward in setUp() and tearDown() methods. Manual $_SERVER cleanup in individual test methods is unnecessary when extending this TestCase.

Applied to files:

  • tests/adapter/ServerParamsPsr7Test.php
📚 Learning: 2025-07-20T16:35:15.341Z
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#6
File: tests/http/RequestTest.php:1536-1552
Timestamp: 2025-07-20T16:35:15.341Z
Learning: In the yii2-extensions/psr-bridge project, the base TestCase class already handles $_SERVER cleanup in setUp() and tearDown() methods (lines 28 and 32), so individual test methods that extend TestCase don't need manual $_SERVER restoration.

Applied to files:

  • tests/adapter/ServerParamsPsr7Test.php
📚 Learning: 2025-07-20T16:35:15.341Z
Learnt from: terabytesoftw
PR: yii2-extensions/psr-bridge#6
File: tests/http/RequestTest.php:1536-1552
Timestamp: 2025-07-20T16:35:15.341Z
Learning: In the yii2-extensions/psr-bridge project, the base TestCase class already handles $_SERVER cleanup in setUp() and tearDown() methods, so individual test methods that extend TestCase don't need manual $_SERVER restoration.

Applied to files:

  • tests/adapter/ServerParamsPsr7Test.php
🧬 Code Graph Analysis (1)
tests/adapter/ServerParamsPsr7Test.php (3)
src/http/Request.php (2)
  • Request (54-823)
  • getRemoteIP (495-512)
tests/support/FactoryHelper.php (2)
  • FactoryHelper (46-268)
  • createRequest (68-89)
tests/provider/RequestProvider.php (1)
  • RequestProvider (7-1281)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: mutation / PHP 8.3-ubuntu-latest
  • GitHub Check: mutation / PHP 8.3-ubuntu-latest
🔇 Additional comments (5)
composer.json (1)

14-14: Explicitly requiring ext-filter is appropriate given filter_var usage

Good addition. It aligns composer requirements with the runtime need introduced in Request::getRemoteIP().

tests/provider/RequestProvider.php (1)

822-893: Comprehensive IP input coverage matches getRemoteIP() validation

The provider cases align well with strict filter_var(FILTER_VALIDATE_IP) behavior, including IPv4/IPv6 and invalid types/values. LGTM.

src/http/Request.php (2)

18-18: Importing filter_var function is correct

Matches the new validation logic and keeps the call unqualified and clear.


480-489: Docblock accurately reflects behavior change

Clarifies source (PSR-7 server params) and null on invalid—good update.

tests/adapter/ServerParamsPsr7Test.php (1)

140-161: Override behavior test is solid

Confirms PSR-7 server params take precedence over global $_SERVER. Base TestCase auto-restores $_SERVER, so no extra cleanup needed.

…l test scenarios for `IP` validation, including invalid `IP`, `IPv4` with port, and `IPv6` formats.
@terabytesoftw
Copy link
Member Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Aug 9, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@terabytesoftw
Copy link
Member Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Aug 9, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants