Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Deprecated

- **`KeyExtractors::clientIp(TrustedProxyResolver)`** - the resolved client IP is now the default discriminator for every rule via the `Config` IP resolver, so a dedicated key extractor is no longer needed. Configure proxy trust once with `$config->setIpResolver($trustedProxyResolver->resolve(...))` and omit the rule's key (or use `PortableConfig::keyIp()`); both resolve the client IP. For the raw connecting peer address, `KeyExtractors::ip()` (REMOTE_ADDR) remains the explicit escape hatch.
- **`KeyExtractors::clientIp(TrustedProxyResolver)`** - the resolved client IP is now the default discriminator for every rule via the `Config` IP resolver, so a dedicated key extractor is no longer needed. Configure proxy trust once with `$config->setIpResolver($trustedProxyResolver->resolve(...))` and omit the rule's key (or use `PortableConfig::keyIp()`); both resolve the client IP.
- **`KeyExtractors::ip()`** - the name is ambiguous (it reads like "the client IP" but returns the raw `REMOTE_ADDR` peer, which behind a proxy is the proxy itself) and it bypasses the `Config` IP resolver. To key on the client IP, omit the rule's key (or use `PortableConfig::keyIp()`) so it resolves through the resolver. For the raw connecting peer, read `$request->getServerParams()['REMOTE_ADDR']` directly.

## 0.6.0 - 2026-06-17

Expand Down
14 changes: 5 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ composer require flowd/phirewall
```php
use Flowd\Phirewall\Config;
use Flowd\Phirewall\Middleware;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Store\InMemoryCache;

// Create the firewall
Expand All @@ -38,14 +37,13 @@ $config->safelists->add('health', fn($req) => $req->getUri()->getPath() === '/he
$config->blocklists->add('scanners', fn($req) => str_starts_with($req->getUri()->getPath(), '/wp-admin'));

// Rate limit: 100 requests per minute per IP
$config->throttles->add('api', limit: 100, period: 60 /* seconds */, key: KeyExtractors::ip());
$config->throttles->add('api', limit: 100, period: 60 /* seconds */);

// Ban IP after 5 failed logins in 5 minutes. The filter never matches at
// request time — failures are signaled from the handler via RequestContext
// (see "Login Protection" below for the handler-side snippet).
$config->fail2ban->add('login', threshold: 5, period: 300 /* seconds */, ban: 3600 /* seconds */,
filter: fn($req) => false,
key: KeyExtractors::ip()
);

// Add to your middleware stack
Expand Down Expand Up @@ -221,7 +219,8 @@ $config->throttles->add('api', limit: 100, period: 60);
```

When no resolver is set the client IP is `REMOTE_ADDR`. For the raw connecting peer
address regardless of proxy configuration, use `KeyExtractors::ip()`.
address regardless of proxy configuration, read `$request->getServerParams()['REMOTE_ADDR']`
directly.
Comment thread
sascha-egerer marked this conversation as resolved.
Comment on lines 221 to +223

## Custom Responses

Expand Down Expand Up @@ -412,13 +411,13 @@ See [31-presets.php](examples/31-presets.php) for standalone use, portable inspe
use Flowd\Phirewall\KeyExtractors;

// Global limit
$config->throttles->add('global', limit: 1000, period: 60, key: KeyExtractors::ip());
$config->throttles->add('global', limit: 1000, period: 60);

// Burst + sustained rate limiting with multiThrottle
$config->throttles->multi('api', [
1 => 5, // 5 req/s burst
60 => 200, // 200 req/min sustained
], KeyExtractors::ip());
]);

// Dynamic limits based on user role
// Note: a header-keyed rule is skipped when the header is absent, so a client can avoid the
Expand All @@ -431,8 +430,6 @@ $config->throttles->add('user', fn($req) => $req->getHeaderLine('X-Plan') === 'p
### Login Protection

```php
use Flowd\Phirewall\KeyExtractors;

// Throttle login attempts
$config->throttles->add('login', limit: 10, period: 60, key: function($req) {
return $req->getUri()->getPath() === '/login'
Expand All @@ -443,7 +440,6 @@ $config->throttles->add('login', limit: 10, period: 60, key: function($req) {
// Ban after failures — signaled via RequestContext from your handler
$config->fail2ban->add('login-ban', threshold: 5, period: 300, ban: 3600,
filter: fn($request): bool => false,
key: KeyExtractors::ip()
);
```

Expand Down
4 changes: 1 addition & 3 deletions examples/01-basic-setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
require __DIR__ . '/../vendor/autoload.php';

use Flowd\Phirewall\Config;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Middleware;
use Flowd\Phirewall\Store\InMemoryCache;
use Nyholm\Psr7\Factory\Psr17Factory;
Expand Down Expand Up @@ -71,8 +70,7 @@
$config->throttles->add(
name: 'ip-limit',
limit: 5,
period: 60,
key: KeyExtractors::ip()
period: 60
);
echo "3c. Throttle rule added: 5 requests/minute per IP\n";

Expand Down
4 changes: 1 addition & 3 deletions examples/02-brute-force-protection.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
use Flowd\Phirewall\Config\DiagnosticsCounters;
use Flowd\Phirewall\Config\DiagnosticsDispatcher;
use Flowd\Phirewall\Context\RequestContext;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Middleware;
use Flowd\Phirewall\Store\InMemoryCache;
use Nyholm\Psr7\Factory\Psr17Factory;
Expand Down Expand Up @@ -60,8 +59,7 @@
threshold: 5, // Number of failures before ban
period: 300, // Time window in seconds (5 minutes)
ban: 3600, // Ban duration in seconds (1 hour)
filter: fn(ServerRequestInterface $serverRequest): bool => false,
key: KeyExtractors::ip()
filter: fn(ServerRequestInterface $serverRequest): bool => false
);
echo "1. Fail2Ban configured: 5 failures in 5 min = 1 hour ban (handler signals failures)\n";

Expand Down
6 changes: 2 additions & 4 deletions examples/03-api-rate-limiting.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,7 @@
$config->throttles->add(
name: 'global-ip',
limit: 100, // 100 requests
period: 60, // per minute
key: KeyExtractors::ip()
period: 60 // per minute
);
echo "1. Global limit: 100 req/min per IP\n";

Expand All @@ -59,8 +58,7 @@
$config->throttles->add(
name: 'burst',
limit: 20, // 20 requests
period: 5, // in 5 seconds
key: KeyExtractors::ip()
period: 5 // in 5 seconds
);
echo "2. Burst limit: 20 req/5s per IP\n";

Expand Down
7 changes: 2 additions & 5 deletions examples/06-bot-detection.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
use Flowd\Phirewall\Config;
use Flowd\Phirewall\Config\DiagnosticsCounters;
use Flowd\Phirewall\Config\DiagnosticsDispatcher;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Middleware;
use Flowd\Phirewall\Store\InMemoryCache;
use Nyholm\Psr7\Factory\Psr17Factory;
Expand Down Expand Up @@ -225,8 +224,7 @@
filter: fn(ServerRequestInterface $serverRequest): bool =>
// This filter matches requests that hit our blocklist rules
// In practice, you'd track this via events
$serverRequest->getHeaderLine('X-Scanner-Detected') === '1',
key: KeyExtractors::ip()
$serverRequest->getHeaderLine('X-Scanner-Detected') === '1'
);
echo "5. Fail2Ban for persistent scanners configured\n";

Expand All @@ -237,8 +235,7 @@
$config->throttles->add(
name: 'rapid-requests',
limit: 30, // 30 requests
period: 10, // In 10 seconds
key: KeyExtractors::ip()
period: 10 // In 10 seconds
);
echo "6. Rapid request throttling configured (30/10s)\n\n";

Expand Down
4 changes: 1 addition & 3 deletions examples/09-observability-monolog.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
require __DIR__ . '/../vendor/autoload.php';

use Flowd\Phirewall\Config;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Middleware;
use Flowd\Phirewall\Store\InMemoryCache;
use Nyholm\Psr7\Factory\Psr17Factory;
Expand Down Expand Up @@ -140,8 +139,7 @@ public function clear(): void
$config->throttles->add(
name: 'ip-limit',
limit: 3,
period: 60,
key: KeyExtractors::ip()
period: 60
);
echo "Throttle rule configured: 3 requests/min per IP\n";

Expand Down
4 changes: 1 addition & 3 deletions examples/10-observability-opentelemetry.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
require __DIR__ . '/../vendor/autoload.php';

use Flowd\Phirewall\Config;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Middleware;
use Flowd\Phirewall\Store\InMemoryCache;
use Nyholm\Psr7\Factory\Psr17Factory;
Expand Down Expand Up @@ -157,8 +156,7 @@ public function dispatch(object $event): object
$config->throttles->add(
name: 'api-limit',
limit: 3,
period: 60,
key: KeyExtractors::ip()
period: 60
);
echo "Throttle rule: 3 requests/min per IP\n";

Expand Down
7 changes: 2 additions & 5 deletions examples/11-redis-storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
require __DIR__ . '/../vendor/autoload.php';

use Flowd\Phirewall\Config;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Middleware;
use Flowd\Phirewall\Store\RedisCache;
use Nyholm\Psr7\Factory\Psr17Factory;
Expand Down Expand Up @@ -95,8 +94,7 @@
$config->throttles->add(
name: 'ip-limit',
limit: 3, // Only 3 requests
period: 30, // Per 30 seconds
key: KeyExtractors::ip()
period: 30 // Per 30 seconds
);
echo "Throttle rule: 3 requests per 30 seconds per IP\n";

Expand All @@ -106,8 +104,7 @@
threshold: 2, // 2 blocked requests
period: 60, // In 1 minute
ban: 300, // 5 minute ban
filter: fn($req): bool => $req->getHeaderLine('X-Abuse') === '1',
key: KeyExtractors::ip()
filter: fn($req): bool => $req->getHeaderLine('X-Abuse') === '1'
);
echo "Fail2Ban rule: 2 abuse markers = 5 minute ban\n\n";

Expand Down
1 change: 0 additions & 1 deletion examples/16-allow2ban.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
threshold: 100,
period: 60,
banSeconds: 3600,
key: KeyExtractors::ip(),
);

// Multiple rules can coexist. E.g., also ban by API key for authenticated routes
Expand Down
2 changes: 0 additions & 2 deletions examples/21-sliding-window.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

use Flowd\Phirewall\Config;
use Flowd\Phirewall\Http\Firewall;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Store\InMemoryCache;
use Nyholm\Psr7\ServerRequest;

Expand All @@ -35,7 +34,6 @@
name: 'api-sliding',
limit: 10,
period: 60,
key: KeyExtractors::ip(),
);

echo "Sliding throttle configured: 10 req/60s per IP\n\n";
Expand Down
3 changes: 1 addition & 2 deletions examples/22-multi-throttle.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

use Flowd\Phirewall\Config;
use Flowd\Phirewall\Http\Firewall;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Store\InMemoryCache;
use Nyholm\Psr7\ServerRequest;

Expand All @@ -32,7 +31,7 @@
$config->throttles->multi('api', [
1 => 3, // 3 req/s burst limit
60 => 60, // 60 req/min sustained limit
], KeyExtractors::ip());
]);

echo "Rules registered:\n";
foreach ($config->throttles->rules() as $name => $rule) {
Expand Down
6 changes: 2 additions & 4 deletions examples/24-pdo-storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
use Flowd\Phirewall\BanType;
use Flowd\Phirewall\Config;
use Flowd\Phirewall\Http\Firewall;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Store\PdoCache;
use Nyholm\Psr7\ServerRequest;

Expand All @@ -34,11 +33,10 @@

// --- Configure rate limiting ---

$config->throttles->add('api', limit: 5, period: 60, key: KeyExtractors::ip());
$config->throttles->add('api', limit: 5, period: 60);

$config->fail2ban->add('login', threshold: 3, period: 300, ban: 600,
filter: fn($req): bool => $req->getHeaderLine('X-Login-Failed') === '1',
key: KeyExtractors::ip()
filter: fn($req): bool => $req->getHeaderLine('X-Login-Failed') === '1'
);

$firewall = new Firewall($config);
Expand Down
5 changes: 2 additions & 3 deletions examples/26-psr17-factories.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
use Flowd\Phirewall\Config;
use Flowd\Phirewall\Config\Response\Psr17BlocklistedResponseFactory;
use Flowd\Phirewall\Config\Response\Psr17ThrottledResponseFactory;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Middleware;
use Flowd\Phirewall\Store\InMemoryCache;
use Nyholm\Psr7\Factory\Psr17Factory;
Expand Down Expand Up @@ -75,7 +74,7 @@ public function handle(ServerRequestInterface $serverRequest): ResponseInterface
$config->enableResponseHeaders();
$config->usePsr17Responses($psr17Factory, $psr17Factory);
$config->blocklists->add('admin', fn(ServerRequestInterface $serverRequest): bool => str_starts_with($serverRequest->getUri()->getPath(), '/admin'));
$config->throttles->add('ip', 2, 60, KeyExtractors::ip());
$config->throttles->add('ip', 2, 60);

$middleware = new Middleware($config, $psr17Factory);

Expand Down Expand Up @@ -120,7 +119,7 @@ public function handle(ServerRequestInterface $serverRequest): ResponseInterface
'Rate limit exceeded. Please slow down.',
);
$config2->blocklists->add('blocked', fn(ServerRequestInterface $serverRequest): bool => $serverRequest->getUri()->getPath() === '/secret');
$config2->throttles->add('ip', 1, 30, KeyExtractors::ip());
$config2->throttles->add('ip', 1, 30);

$middleware2 = new Middleware($config2, $psr17Factory);

Expand Down
2 changes: 0 additions & 2 deletions examples/27-request-context.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@

use Flowd\Phirewall\Config;
use Flowd\Phirewall\Context\RequestContext;
use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Middleware;
use Flowd\Phirewall\Store\InMemoryCache;
use Nyholm\Psr7\Factory\Psr17Factory;
Expand Down Expand Up @@ -54,7 +53,6 @@
period: 300,
ban: 3600,
filter: fn(ServerRequestInterface $serverRequest): bool => false,
key: KeyExtractors::ip(),
);

echo " Fail2Ban rule 'login-failures': 3 failures in 5 min = 1 hour ban\n";
Expand Down
9 changes: 6 additions & 3 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -365,16 +365,19 @@ public function resolveKey(?KeyExtractorInterface $keyExtractor, ServerRequestIn
}

/**
* This Config's client-IP resolver, falling back to {@see KeyExtractors::ip()}
* (REMOTE_ADDR) when none is set. Supplied to {@see Matchers\ClientIpResolverAware}
* This Config's client-IP resolver, falling back to the raw REMOTE_ADDR peer
* address when none is set. Supplied to {@see Matchers\ClientIpResolverAware}
* matchers at evaluation time so an IP rule added without an explicit resolver
* reads the client IP through the Config it actually runs under.
*
* @return callable(ServerRequestInterface): ?string
*/
public function clientIpResolver(): callable
{
return $this->ipResolver ?? KeyExtractors::ip();
return $this->ipResolver ?? static function (ServerRequestInterface $serverRequest): ?string {
$remoteAddr = $serverRequest->getServerParams()['REMOTE_ADDR'] ?? null;
return is_string($remoteAddr) && $remoteAddr !== '' ? $remoteAddr : null;
};
Comment thread
sascha-egerer marked this conversation as resolved.
Comment on lines +377 to +380
}

// ── Discriminator normalizer ────────────────────────────────────────
Expand Down
10 changes: 6 additions & 4 deletions src/Config/FileIpBlocklistMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace Flowd\Phirewall\Config;

use Flowd\Phirewall\KeyExtractors;
use Flowd\Phirewall\Matchers\ClientIpResolverAware;
use Flowd\Phirewall\Matchers\Support\CidrMatcher;
use Psr\Http\Message\ServerRequestInterface;
Expand Down Expand Up @@ -37,8 +36,8 @@ final class FileIpBlocklistMatcher implements RequestMatcherInterface, ClientIpR
* How to extract the client IP from a request. When omitted
* ({@see ClientIpResolverAware}), the matcher late-binds to the
* resolver of the {@see \Flowd\Phirewall\Config} it is evaluated
* under, falling back to {@see KeyExtractors::ip()} (`REMOTE_ADDR`
* verbatim, no proxy headers) when used standalone or when that
* under, falling back to `REMOTE_ADDR` (the raw peer address,
* no proxy headers) when used standalone or when that
* Config sets none. Deployments behind a CDN, load balancer, or
* reverse proxy must configure a trusted client-IP resolver - set
* it on the Config via `setIpResolver((new TrustedProxyResolver([...]))->resolve(...))`,
Expand All @@ -65,7 +64,10 @@ public function __construct(

public function match(ServerRequestInterface $serverRequest): MatchResult
{
return $this->matchWithResolver($serverRequest, KeyExtractors::ip());
return $this->matchWithResolver($serverRequest, static function (ServerRequestInterface $serverRequest): ?string {
$remoteAddr = $serverRequest->getServerParams()['REMOTE_ADDR'] ?? null;
return is_string($remoteAddr) && $remoteAddr !== '' ? $remoteAddr : null;
});
}

public function matchWithResolver(ServerRequestInterface $serverRequest, callable $defaultResolver): MatchResult
Expand Down
Loading
Loading