Automatic Cloudflare detection for rate limiting (trusts CF-Connecting-IP only from Cloudflare ranges)
Test and Release / test (push) Successful in 1m19s
Test and Release / release (push) Failing after 5s

- Core\CidrMatcher (IPv4/IPv6), Core\CloudflareRanges (published ranges, filterable)
- ClientIp 'auto' mode, default for new installs; diagnostics show whether the connection is from Cloudflare

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-15 12:54:10 -08:00
1 parent 5ea1e1d273
commit 43106d9edc
8 files changed
+171 -6

No files matched your search

+5 -3
View File
@@ -56,7 +56,7 @@ final class SettingsPage {
foreach ( \StreamGoals\Core\ClientIp::MODES as $k => $l ) {
echo '<option value="' . esc_attr( $k ) . '"' . selected( (string) $s['visitor_ip_header'], $k, false ) . '>' . esc_html( $l ) . '</option>';
}
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). If your site is behind Cloudflare or another proxy, choose it here so each visitor is counted separately; otherwise everyone looks like the same visitor and a busy moment, like a raid, could block donations. Only choose a proxy option if <em>all</em> traffic to your site really goes through it.</p>';
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). Behind a proxy, every visitor can look like the same address, and a busy moment, like a raid, could block donations. <strong>Automatic</strong> recognises Cloudflare by its published addresses and counts each visitor separately; it ignores forged headers from anywhere else. For another kind of proxy, choose its option here, but only if <em>all</em> traffic to your site really goes through it.</p>';
self::ipDiagnostics( (string) $s['visitor_ip_header'] );
echo '</td></tr></table></div>';
@@ -80,7 +80,7 @@ final class SettingsPage {
/** Shows the owner what their server passes to the plugin right now, to help pick the right option. */
private static function ipDiagnostics( string $mode ): void {
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_CF_RAY' => 'CF-Ray', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
$server = array();
foreach ( $keys as $k => $_ ) {
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
@@ -91,8 +91,10 @@ final class SettingsPage {
foreach ( $keys as $k => $label ) {
echo '<tr><td>' . esc_html( $label ) . '</td><td><code>' . ( isset( $server[ $k ] ) ? esc_html( $server[ $k ] ) : '(not sent)' ) . '</code></td></tr>';
}
$viaCf = isset( $server['REMOTE_ADDR'] ) && \StreamGoals\Core\CloudflareRanges::isCloudflare( $server['REMOTE_ADDR'], (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
echo '<tr><td>Is this connection from Cloudflare?</td><td>' . ( $viaCf ? '<strong>Yes</strong> - the connection comes from a Cloudflare address' : 'No' ) . '</td></tr>';
echo '<tr><td><strong>Visitor address used with the saved option</strong></td><td><code>' . esc_html( \StreamGoals\Core\ClientIp::resolve( $server, $mode ) ) . '</code></td></tr>';
echo '</tbody></table><p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
echo '</tbody></table>' . ( ! $viaCf && ( isset( $server['HTTP_CF_RAY'] ) || isset( $server['HTTP_CF_CONNECTING_IP'] ) ) ? '<p class="sg-warn">Cloudflare headers were sent, but the connection is not from a known Cloudflare address, so "Automatic" ignores them. If your site really is behind Cloudflare, choose "Cloudflare" above (or update the plugin, as Cloudflare may have added new addresses).</p>' : '' ) . '<p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
}
public static function handleSave(): void {
+47
View File
@@ -0,0 +1,47 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/** Pure IPv4/IPv6 CIDR membership test (no WordPress, no network). Malformed input never matches. */
final class CidrMatcher {
/** @param string[] $cidrs e.g. ['173.245.48.0/20', '2606:4700::/32'] */
public static function contains( string $ip, array $cidrs ): bool {
$ipBin = @inet_pton( trim( $ip ) );
if ( false === $ipBin ) {
return false;
}
foreach ( $cidrs as $cidr ) {
if ( self::inRange( $ipBin, (string) $cidr ) ) {
return true;
}
}
return false;
}
private static function inRange( string $ipBin, string $cidr ): bool {
$parts = explode( '/', trim( $cidr ), 2 );
if ( 2 !== count( $parts ) || ! ctype_digit( $parts[1] ) ) {
return false;
}
$netBin = @inet_pton( $parts[0] );
if ( false === $netBin || strlen( $netBin ) !== strlen( $ipBin ) ) { // different address families never match
return false;
}
$bits = (int) $parts[1];
if ( $bits < 0 || $bits > strlen( $netBin ) * 8 ) {
return false;
}
$fullBytes = intdiv( $bits, 8 );
if ( $fullBytes > 0 && substr( $ipBin, 0, $fullBytes ) !== substr( $netBin, 0, $fullBytes ) ) {
return false;
}
$rest = $bits % 8;
if ( 0 === $rest ) {
return true;
}
$mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF;
return ( ord( $ipBin[ $fullBytes ] ) & $mask ) === ( ord( $netBin[ $fullBytes ] ) & $mask );
}
}
+9 -1
View File
@@ -12,12 +12,14 @@ namespace StreamGoals\Core;
*/
final class ClientIp {
public const MODE_AUTO = 'auto'; // detect Cloudflare automatically (recommended)
public const MODE_DIRECT = ''; // no proxy: use REMOTE_ADDR
public const MODE_CLOUDFLARE = 'cloudflare'; // CF-Connecting-IP
public const MODE_REAL_IP = 'real_ip'; // X-Real-IP (nginx and many hosts)
public const MODE_FORWARDED = 'forwarded'; // last address in X-Forwarded-For (exactly one proxy in front)
public const MODES = array(
self::MODE_AUTO => 'Automatic (recommended): detects Cloudflare',
self::MODE_DIRECT => 'Not behind a proxy or CDN (most sites)',
self::MODE_CLOUDFLARE => 'Cloudflare (CF-Connecting-IP)',
self::MODE_REAL_IP => 'X-Real-IP header',
@@ -25,10 +27,16 @@ final class ClientIp {
);
/** @param array<string,mixed> $server $_SERVER-style values (already unslashed). */
public static function resolve( array $server, string $mode = self::MODE_DIRECT ): string {
public static function resolve( array $server, string $mode = self::MODE_DIRECT, ?array $extraCloudflareRanges = null ): string {
$remote = self::valid( $server['REMOTE_ADDR'] ?? null );
$fromHeader = null;
switch ( $mode ) {
case self::MODE_AUTO:
// Trust CF-Connecting-IP only when the connection itself comes from a Cloudflare address.
if ( null !== $remote && CloudflareRanges::isCloudflare( $remote, $extraCloudflareRanges ) ) {
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
}
break;
case self::MODE_CLOUDFLARE:
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
break;
+25
View File
@@ -0,0 +1,25 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/**
* Cloudflare's published proxy address ranges (https://www.cloudflare.com/ips-v4 and /ips-v6), fetched 2026-11-15.
* They change very rarely. Sites can extend them with the `streamgoals_cloudflare_ranges` filter.
* Used ONLY to decide whether a connection really comes from Cloudflare, so a forged CF-Connecting-IP header
* from anywhere else is ignored.
*/
final class CloudflareRanges {
public const RANGES = array(
'173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18',
'190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
'104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22',
'2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32',
);
/** @param string[]|null $extra additional ranges (from the filter) */
public static function isCloudflare( string $ip, ?array $extra = null ): bool {
return CidrMatcher::contains( $ip, array_merge( self::RANGES, $extra ?? array() ) );
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ final class Settings {
'message_max_length' => 200,
'min_donation_minor' => 100,
'overlay_token' => '',
'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp)
'visitor_ip_header' => 'auto', // auto | '' (direct) | cloudflare | real_ip | forwarded (see Core\ClientIp)
'funding_paylater' => false, // show PayPal "Pay Later" button
'update_token' => '', // optional Gitea read token (only while the update repo is private)
'funding_card' => true, // show the Debit/Credit Card button
+1 -1
View File
@@ -284,7 +284,7 @@ final class DonateController {
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
}
}
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', '' ) );
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', 'auto' ), (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
return null;
}
+59
View File
@@ -0,0 +1,59 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\CidrMatcher;
use StreamGoals\Core\CloudflareRanges;
final class CidrMatcherTest extends TestCase {
public function test_ipv4_boundaries(): void {
$r = array( '173.245.48.0/20' ); // 173.245.48.0 - 173.245.63.255
$this->assertTrue( CidrMatcher::contains( '173.245.48.0', $r ) );
$this->assertTrue( CidrMatcher::contains( '173.245.63.255', $r ) );
$this->assertFalse( CidrMatcher::contains( '173.245.47.255', $r ) );
$this->assertFalse( CidrMatcher::contains( '173.245.64.0', $r ) );
}
public function test_non_byte_aligned_and_wide_masks(): void {
$this->assertTrue( CidrMatcher::contains( '104.27.255.255', array( '104.24.0.0/14' ) ) ); // /14 spans 104.24 - 104.27
$this->assertFalse( CidrMatcher::contains( '104.28.0.0', array( '104.24.0.0/14' ) ) );
$this->assertFalse( CidrMatcher::contains( '104.23.255.255', array( '104.24.0.0/14' ) ) );
$this->assertTrue( CidrMatcher::contains( '8.8.8.8', array( '0.0.0.0/0' ) ) );
$this->assertTrue( CidrMatcher::contains( '1.2.3.4', array( '1.2.3.4/32' ) ) );
$this->assertFalse( CidrMatcher::contains( '1.2.3.5', array( '1.2.3.4/32' ) ) );
}
public function test_ipv6(): void {
$this->assertTrue( CidrMatcher::contains( '2606:4700::1', array( '2606:4700::/32' ) ) );
$this->assertTrue( CidrMatcher::contains( '2a06:98c7:ffff::1', array( '2a06:98c0::/29' ) ) );
$this->assertFalse( CidrMatcher::contains( '2a06:98c8::1', array( '2a06:98c0::/29' ) ) );
$this->assertFalse( CidrMatcher::contains( '2606:4701::1', array( '2606:4700::/32' ) ) );
}
public function test_families_never_cross_match_and_bad_input_is_false(): void {
$this->assertFalse( CidrMatcher::contains( '1.2.3.4', array( '2606:4700::/32' ) ) );
$this->assertFalse( CidrMatcher::contains( '2606:4700::1', array( '173.245.48.0/20' ) ) );
foreach ( array( 'garbage', '', '999.1.1.1', "1.2.3.4\nX: y", '1.2.3.4, 5.6.7.8' ) as $bad ) {
$this->assertFalse( CidrMatcher::contains( $bad, array( '0.0.0.0/0' ) ), "matched bad ip: $bad" );
}
foreach ( array( '1.2.3.4', '1.2.3.4/x', '1.2.3.4/33', '1.2.3.4/-1', 'nope/8', '' ) as $badCidr ) {
$this->assertFalse( CidrMatcher::contains( '1.2.3.4', array( $badCidr ) ), "matched bad cidr: $badCidr" );
}
}
public function test_surrounding_whitespace_is_tolerated(): void {
$this->assertTrue( CidrMatcher::contains( ' 173.245.48.1 ', array( '173.245.48.0/20' ) ) );
}
public function test_cloudflare_ranges(): void {
$this->assertTrue( CloudflareRanges::isCloudflare( '172.70.1.1' ) );
$this->assertTrue( CloudflareRanges::isCloudflare( '104.16.0.1' ) );
$this->assertTrue( CloudflareRanges::isCloudflare( '2606:4700:3030::1' ) );
$this->assertFalse( CloudflareRanges::isCloudflare( '203.0.113.9' ) );
$this->assertFalse( CloudflareRanges::isCloudflare( '47.151.185.180' ) );
$this->assertTrue( CloudflareRanges::isCloudflare( '203.0.113.9', array( '203.0.113.0/24' ) ), 'filter-supplied ranges extend the list' );
}
}
+24
View File
@@ -56,4 +56,28 @@ final class ClientIpTest extends TestCase {
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4' );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, 'something_else' ) );
}
public function test_auto_mode_trusts_cf_header_only_from_a_cloudflare_connection(): void {
$srv = array( 'REMOTE_ADDR' => '172.70.1.1', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
$v6 = array( 'REMOTE_ADDR' => '2606:4700:3030::1', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
$this->assertSame( self::CLIENT, ClientIp::resolve( $v6, ClientIp::MODE_AUTO ) );
}
public function test_auto_mode_ignores_a_forged_header_from_a_non_cloudflare_connection(): void {
$srv = array( 'REMOTE_ADDR' => '47.151.185.180', 'HTTP_CF_CONNECTING_IP' => '6.6.6.6', 'HTTP_X_FORWARDED_FOR' => '7.7.7.7' );
$this->assertSame( '47.151.185.180', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
}
public function test_auto_mode_falls_back_when_header_missing_or_invalid(): void {
$this->assertSame( '172.70.1.1', ClientIp::resolve( array( 'REMOTE_ADDR' => '172.70.1.1' ), ClientIp::MODE_AUTO ) );
$this->assertSame( '172.70.1.1', ClientIp::resolve( array( 'REMOTE_ADDR' => '172.70.1.1', 'HTTP_CF_CONNECTING_IP' => 'nope' ), ClientIp::MODE_AUTO ) );
}
public function test_auto_mode_extra_ranges_from_the_filter(): void {
$srv = array( 'REMOTE_ADDR' => '198.18.0.5', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
$this->assertSame( '198.18.0.5', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO, array( '198.18.0.0/15' ) ) );
}
}