Skip to content

Fix #82: IpHelper validators accept an address with a trailing newline - #83

Merged
samdark merged 2 commits into
yiisoft:masterfrom
iefken:fix/ip-regexp-trailing-newline
Dec 4, 2026
Merged

samdark merged 2 commits into
yiisoft:masterfrom
iefken:fix/ip-regexp-trailing-newline

Conversation

@iefken

@iefken iefken commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor
Q A
Is bugfix? ✔️
New feature? ❌
Breaks BC? ❌
Fixed issues #82

isIpv4(), isIpv6(), isIp() and the IPv6 fallback in getIpVersion() matched with regexps
ending in $ without D, so "1.2.3.4\n" was a valid IP while inRange() / IpRanges::isAllowed()
threw on it.

  • src/IpHelper.php: private *_REGEXP_STRICT constants (self::*_REGEXP . 'D') used in those four
    places; the public constants are unchanged (documented as JavaScript compatible).
  • tests/IpHelperTest.php: trailing-newline cases for isIpv4(), isIpv6(), isIp() and
    getIpVersion() with validation.
  • CHANGELOG.md: Bug #82 line under 1.2.3.

Tests run locally on master @ d7ed96f (PHP 8.3.37, PHPUnit 9.6):

  • new tests on the unfixed code: Tests: 157, Assertions: 160, Errors: 3, Failures: 5. - the 5 failures are the new trailing-newline rows (isIpv4, isIpv6, isIp x2: Failed asserting that true is identical to false; getIpVersion IPv6: Failed asserting that exception of type "InvalidArgumentException" is thrown)
  • full suite with the fix: Tests: 157, Assertions: 160, Errors: 3. - 0 failures; the 3 errors are DnsHelperTest::testMx/testA/testAcceptsEmail (dns_get_record(): A temporary server error), which need network and error identically without the fix (our test container has no network)
  • PHPStan (phpstan.neon, level max): [OK] No errors
  • PHP CS Fixer (dry run): Found 0 of 6 files that can be fixed
  • Rector --dry-run: [OK] Rector is done!

Not run locally: the PHP 7.4-8.6 x ubuntu/windows matrix (one PHP in our image), Infection,
Roave BC check, composer-dependency-analyser (no dependency changed). Private constants and string
concatenation in constant expressions work on PHP 7.4.

GPG-signed and DCO signed-off.



Issue found and fixed by Claude, reproduced issue in an isolated container, then reviewed and confirmed by Ief (GitHub: iefken).

Summary by Sourcery

Reject IP and CIDR values with trailing newlines and clarify which regular-expression constants to use for PHP and JavaScript.

New Features:

  • Add separate PHP- and JavaScript-compatible IPv4, IPv6, and general IP regular-expression constants.

Bug Fixes:

  • Reject IP addresses and CIDR inputs with trailing newlines across validation and address-version parsing.

Enhancements:

  • Deprecate the existing IP regular-expression constants while retaining their current values.

Tests:

  • Add coverage for trailing-newline validation and both PHP and JavaScript regular-expression constants.

Chores:

  • Update the 1.2.3 changelog with the validation fix, new constants, and deprecations.

isIpv4(), isIpv6() and isIp() matched against IPV4_REGEXP, IPV6_REGEXP
and IP_REGEXP, which end in `$` without the D modifier. In PHP `$` also
matches before a final newline, so "1.2.3.4\n" and "::1\n" were valid
IPs, while inRange() / IpRanges::isAllowed() then failed on the same
value (InvalidArgumentException for IPv4, a TypeError/AssertionError
from ip2bin() for IPv6). getIpVersion() had the same gap in its IPv6
regexp fallback.

Use the regexps with the D modifier in these four places. The public
*_REGEXP constants are unchanged, as they are documented as JavaScript
compatible and JavaScript has no D flag.

Tests: trailing-newline cases for isIpv4(), isIpv6(), isIp() and
getIpVersion() with validation.

Signed-off-by: Iefken <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Introduce engine-specific public regexp constants, deprecate the legacy constants without changing their values, and document the PHP-versus-JavaScript distinction.

  • src/IpHelper.php L30-45, L52-67, L82-97

Implementation

Use the strict PCRE regexps in the IP validators and IPv6 fallback, and reject trailing newlines when parsing CIDR input.

  • src/IpHelper.php L101-268 (5 small edits)

Documentation

Record the validator fix and the new regexp constants in the 1.2.3 changelog.

  • CHANGELOG.md L5-9

Tests

Cover trailing-newline rejection in validators and parsing, test the PCRE and ECMA regexp constants, and preserve legacy constant values.

  • tests/IpHelperTest.php L259-278, L302-367 (+5 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.82%. Comparing base (e6d1430) to head (0e2abe5).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##             master      #83   +/-   ##
=========================================
  Coverage     96.82%   96.82%           
  Complexity       54       54           
=========================================
  Files             3        3           
  Lines           126      126           
=========================================
  Hits            122      122           
  Misses            4        4           

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/IpHelper.php" line_range="62" />
<code_context>

+    /**
+     * The regexps above with the `D` modifier, used by the validation methods. Without it, PHP's `$` also matches
+     * before a final newline, so `"1.2.3.4\n"` would pass. The public constants stay JavaScript compatible (no `D`).
+     */
+    private const IPV4_REGEXP_STRICT = self::IPV4_REGEXP . 'D';
</code_context>
<issue_to_address>
**Public regex accepts trailing newlines**

When a consumer validates newline-terminated input directly with one of the public regex constants, pHP `preg_match()` with the public `IPV4_REGEXP`, `IPV6_REGEXP`, or `IP_REGEXP` still treats a final newline as matching the end of the address, so consumers using these exported validators accept inputs the helper methods now reject.

Use an end-of-input assertion compatible with the documented PHP/JavaScript use in the public regex constants, and add trailing-newline tests for them.
</issue_to_address>

Sourcery assessment

Approval pending. 1 finding to address first.

Blocking findings: src/IpHelper.php:62


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/IpHelper.php Resolved
Comment thread src/IpHelper.php Resolved
Comment thread src/IpHelper.php Resolved
As requested in review: make the engine distinction explicit in the
public API instead of private *_STRICT constants.

- Add PCRE_IPV4_REGEXP, PCRE_IPV6_REGEXP and PCRE_IP_REGEXP ('/^...$/D',
  strict end of string) for PHP's preg_*() functions.
- Add ECMA_IPV4_REGEXP, ECMA_IPV6_REGEXP and ECMA_IP_REGEXP ('/^...$/')
  for JavaScript; their docblocks say they are not strict in PHP.
- Deprecate IPV4_REGEXP, IPV6_REGEXP and IP_REGEXP; their values do not
  change.
- isIpv4(), isIpv6(), isIp() and the IPv6 fallback in getIpVersion() use
  the PCRE_* constants.
- getCidrBits(): add the D modifier, so "127.0.0.1\n" and
  "127.0.0.1/24\n" are rejected instead of returning 32 and 24.

Tests: trailing newline, CRLF and leading newline rows for the PCRE_*
constants; ECMA_* with the regular valid/invalid rows; trailing-newline
rows for getCidrBits(); the deprecated constants keep their values.

Signed-off-by: Iefken <[email protected]>
@iefken

iefken commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Hi @vjik, thanks for the review!

Reworked it the way you described, in a second commit on top of the first one:

  • 'PCRE_IPV4_REGEXP', 'PCRE_IPV6_REGEXP', 'PCRE_IP_REGEXP' ('/^...$/D') for 'preg_*()', and 'ECMA_IPV4_REGEXP', 'ECMA_IPV6_REGEXP', 'ECMA_IP_REGEXP' ('/^...$/') for JavaScript, with "for JavaScript" and the non-strict-in-PHP note in their docblocks
  • 'IPV4_REGEXP', 'IPV6_REGEXP', 'IP_REGEXP' deprecated with your wording, values unchanged (plus a small test that they keep them)
  • 'isIpv4()', 'isIpv6()', 'isIp()' and the IPv6 fallback in 'getIpVersion()' now use the 'PCRE_' constants; the private '_STRICT' ones are gone
  • 'getCidrBits()' got the 'D' modifier too: before, "127.0.0.1\n" returned 32 and "127.0.0.1/24\n" returned 24, now both throw
  • Tests: trailing newline / CRLF / leading newline rows for the 'PCRE_' constants, 'ECMA_' with the regular valid/invalid rows only, and three trailing-newline rows for 'getCidrBits()' (those three fail on the previous code)
  • CHANGELOG: the Bug line now names 'getCidrBits()', plus a New and a Chg line for the constants

This should also cover the Sourcery note: the strict 'PCRE_' constants are the PHP ones now, and the 'ECMA_' ones stay without 'D' on purpose.

Locally (PHP 8.3, offline container): phpunit all green except the three DnsHelper tests that need network, phpstan, php-cs-fixer, rector and composer-dependency-analyser clean. Not run locally: the PHP 7.4 to 8.6 matrix, the mutation job and roave BC check, so those are up to CI.



Review proposed by Claude, checked and sent by Ief (GitHub: iefken).

@vjik
vjik requested a review from a team December 3, 2026 11:06
@vjik vjik added the status:code review The pull request needs review. label Dec 3, 2026
@samdark
samdark merged commit f421c96 into yiisoft:master Dec 4, 2026
40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status:code review The pull request needs review.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants