-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path03-api-rate-limiting.php
More file actions
259 lines (215 loc) · 8.64 KB
/
Copy path03-api-rate-limiting.php
File metadata and controls
259 lines (215 loc) · 8.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
<?php
/**
* Example 03: API Rate Limiting
*
* This example demonstrates tiered rate limiting for APIs with:
* - Global rate limits per IP
* - Endpoint-specific limits
* - Authenticated user higher quotas
* - API key based limiting
* - Burst detection
*
* Run: php examples/03-api-rate-limiting.php
*/
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
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;
use Nyholm\Psr7\Response;
use Nyholm\Psr7\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
echo "=== API Rate Limiting Example ===\n\n";
// =============================================================================
// CONFIGURATION
// =============================================================================
$cache = new InMemoryCache();
$diagnostics = new DiagnosticsCounters();
$config = new Config($cache, new DiagnosticsDispatcher($diagnostics));
$config->enableRateLimitHeaders(); // Send X-RateLimit-* headers
$config->enableResponseHeaders(); // Send X-Phirewall headers
// -----------------------------------------------------------------------------
// Tier 1: Global IP-based limit (baseline protection)
// -----------------------------------------------------------------------------
$config->throttles->add(
name: 'global-ip',
limit: 100, // 100 requests
period: 60 // per minute
);
echo "1. Global limit: 100 req/min per IP\n";
// -----------------------------------------------------------------------------
// Tier 2: Burst detection (prevent rapid-fire requests)
// -----------------------------------------------------------------------------
$config->throttles->add(
name: 'burst',
limit: 20, // 20 requests
period: 5 // in 5 seconds
);
echo "2. Burst limit: 20 req/5s per IP\n";
// -----------------------------------------------------------------------------
// Tier 3: Write operation limits (POST/PUT/DELETE)
// -----------------------------------------------------------------------------
$config->throttles->add(
name: 'write-ops',
limit: 30,
period: 60,
key: function (ServerRequestInterface $serverRequest): ?string {
if (in_array($serverRequest->getMethod(), ['POST', 'PUT', 'PATCH', 'DELETE'])) {
return $serverRequest->getServerParams()['REMOTE_ADDR'] ?? null;
}
return null; // Skip for GET requests
}
);
echo "3. Write ops limit: 30 req/min per IP\n";
// -----------------------------------------------------------------------------
// Tier 4: Endpoint-specific limits
// -----------------------------------------------------------------------------
// Search endpoint (expensive operation)
$config->throttles->add(
name: 'search',
limit: 10,
period: 60,
key: function (ServerRequestInterface $serverRequest): ?string {
if ($serverRequest->getUri()->getPath() === '/api/search') {
return $serverRequest->getServerParams()['REMOTE_ADDR'] ?? null;
}
return null;
}
);
echo "4. Search endpoint: 10 req/min per IP\n";
// Export endpoint (very expensive)
$config->throttles->add(
name: 'export',
limit: 2,
period: 300, // 5 minutes
key: function (ServerRequestInterface $serverRequest): ?string {
if (str_starts_with($serverRequest->getUri()->getPath(), '/api/export')) {
return $serverRequest->getServerParams()['REMOTE_ADDR'] ?? null;
}
return null;
}
);
echo "5. Export endpoint: 2 req/5min per IP\n";
// -----------------------------------------------------------------------------
// Tier 5: Authenticated user limits (higher quota)
// -----------------------------------------------------------------------------
$config->throttles->add(
name: 'authenticated',
limit: 1000,
period: 60,
key: KeyExtractors::header('X-User-Id')
);
echo "6. Authenticated users: 1000 req/min per user\n";
// -----------------------------------------------------------------------------
// Tier 6: API key limits
// -----------------------------------------------------------------------------
// X-API-Key carries a credential — use hashedHeader() so the cache backend
// and ban registry store a sha256 fingerprint rather than the raw secret.
$config->throttles->add(
name: 'api-key',
limit: 500,
period: 60,
key: KeyExtractors::hashedHeader('X-API-Key')
);
echo "7. API key: 500 req/min per key\n";
// -----------------------------------------------------------------------------
// Custom response for rate limiting
// -----------------------------------------------------------------------------
$config->throttledResponseFactory = new \Flowd\Phirewall\Config\Response\ClosureThrottledResponseFactory(
fn(string $rule, int $retryAfter, $request): ResponseInterface => new Response(429, [
'Content-Type' => 'application/json',
'Retry-After' => (string) $retryAfter,
], json_encode([
'error' => 'rate_limit_exceeded',
'message' => sprintf("You've exceeded the rate limit. Please try again in %d seconds.", $retryAfter),
'rule' => $rule,
'retry_after' => $retryAfter,
], JSON_THROW_ON_ERROR))
);
echo "\n";
// =============================================================================
// SIMULATION
// =============================================================================
$middleware = new Middleware($config, new Psr17Factory());
$handler = new class implements RequestHandlerInterface {
public function handle(ServerRequestInterface $serverRequest): ResponseInterface
{
return new Response(200, ['Content-Type' => 'application/json'],
json_encode(['status' => 'ok'], JSON_THROW_ON_ERROR));
}
};
$test = function (
string $desc,
string $method,
string $path,
array $headers = [],
string $ip = '10.0.0.1'
) use ($middleware, $handler): void {
$request = new ServerRequest($method, $path, $headers, null, '1.1', ['REMOTE_ADDR' => $ip]);
$response = $middleware->process($request, $handler);
$status = $response->getStatusCode();
echo sprintf(" %-55s => %d", $desc, $status);
// Show rate limit headers
$remaining = $response->getHeaderLine('X-RateLimit-Remaining');
$rule = $response->getHeaderLine('X-Phirewall-Matched');
if ($remaining !== '') {
echo sprintf(' [remaining: %s]', $remaining);
}
if ($status === 429 && $rule !== '') {
echo sprintf(' [rule: %s]', $rule);
}
echo "\n";
};
echo "=== Test 1: Burst Detection ===\n";
echo "25 rapid requests should trigger burst limit after 20...\n\n";
$burstIp = '10.0.0.10';
for ($i = 1; $i <= 25; ++$i) {
$test('Burst request ' . $i, 'GET', '/api/users', [], $burstIp);
}
echo "\n=== Test 2: Endpoint-Specific Limits ===\n";
echo "Testing search endpoint (10/min limit)...\n\n";
$searchIp = '10.0.0.20';
for ($i = 1; $i <= 12; ++$i) {
$test('Search request ' . $i, 'GET', '/api/search', [], $searchIp);
}
echo "\nTesting export endpoint (2/5min limit)...\n\n";
$exportIp = '10.0.0.30';
for ($i = 1; $i <= 4; ++$i) {
$test('Export request ' . $i, 'GET', '/api/export/csv', [], $exportIp);
}
echo "\n=== Test 3: Write Operations ===\n";
echo "Testing write operation limits...\n\n";
$writeIp = '10.0.0.40';
// Mix of write operations
for ($i = 1; $i <= 5; ++$i) {
$test("POST /api/items (create)", 'POST', '/api/items', [], $writeIp);
$test(sprintf('PUT /api/items/%d (update)', $i), 'PUT', '/api/items/' . $i, [], $writeIp);
$test(sprintf('DELETE /api/items/%d (delete)', $i), 'DELETE', '/api/items/' . $i, [], $writeIp);
}
echo "\n=== Test 4: Authenticated User (Higher Quota) ===\n";
echo "User with X-User-Id gets 1000/min instead of 100/min...\n\n";
// First, exhaust IP limit from an IP
$authIp = '10.0.0.50';
$userId = 'user-12345';
for ($i = 1; $i <= 5; ++$i) {
$test('Authenticated request ' . $i, 'GET', '/api/profile', ['X-User-Id' => $userId], $authIp);
}
echo "\n=== Test 5: API Key Based Limiting ===\n\n";
$apiKey = 'key-abc123';
for ($i = 1; $i <= 5; ++$i) {
$test('API key request ' . $i, 'GET', '/api/data', ['X-API-Key' => $apiKey], '10.0.0.60');
}
echo "\n=== Diagnostics ===\n";
$counters = $diagnostics->all();
echo "Throttled requests: " . ($counters['throttle_exceeded']['total'] ?? 0) . "\n";
echo "Breakdown by rule:\n";
foreach ($counters['throttle_exceeded']['by_rule'] ?? [] as $rule => $count) {
echo sprintf(' - %s: %d%s', $rule, $count, PHP_EOL);
}
echo "\n=== Example Complete ===\n";