RateLimitTest.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests\Integration\Public;
  4. use App\Domain\Auth\Role;
  5. use App\Domain\Auth\TokenKind;
  6. use App\Domain\Time\Clock;
  7. use App\Domain\Time\FixedClock;
  8. use App\Infrastructure\Http\Middleware\RateLimitMiddleware;
  9. use App\Infrastructure\Http\RateLimiter;
  10. use App\Tests\Integration\Support\AppTestCase;
  11. use Psr\Http\Message\ResponseFactoryInterface;
  12. /**
  13. * Override the AppTestCase to inject a tight rate limit and a fixed clock,
  14. * then run a burst that exceeds capacity (rate × 2).
  15. */
  16. final class RateLimitTest extends AppTestCase
  17. {
  18. protected function setUp(): void
  19. {
  20. parent::setUp();
  21. // Replace the clock + limiter with a tight, fixed-time pair: refill=2/s,
  22. // capacity=4. A burst of 20 must produce some 429s. We must also rebuild
  23. // the RateLimitMiddleware singleton — PHP-DI caches the constructed
  24. // instance, which already holds the wide-open limiter from setup.
  25. if (method_exists($this->container, 'set')) {
  26. /** @var \DI\Container $c */
  27. $c = $this->container;
  28. $clock = FixedClock::at('2026-04-29T00:00:00Z');
  29. $limiter = new RateLimiter($clock, 2.0, 4.0);
  30. $c->set(Clock::class, $clock);
  31. $c->set(RateLimiter::class, $limiter);
  32. /** @var ResponseFactoryInterface $rf */
  33. $rf = $c->get(ResponseFactoryInterface::class);
  34. $c->set(RateLimitMiddleware::class, new RateLimitMiddleware($limiter, $rf));
  35. $this->app = \App\App\AppFactory::build($this->container);
  36. }
  37. }
  38. public function testBurstExceedingCapacityProduces429s(): void
  39. {
  40. $reporterId = $this->createReporter('web-limited');
  41. $token = $this->createToken(TokenKind::Reporter, reporterId: $reporterId);
  42. $headers = ['Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json'];
  43. $body = json_encode(['ip' => '203.0.113.1', 'category' => 'brute_force']) ?: null;
  44. $statuses = [];
  45. for ($i = 0; $i < 20; $i++) {
  46. $statuses[] = $this->request('POST', '/api/v1/report', $headers, $body)->getStatusCode();
  47. }
  48. $accepted = count(array_filter($statuses, static fn (int $s): bool => $s === 202));
  49. $limited = count(array_filter($statuses, static fn (int $s): bool => $s === 429));
  50. // At fixed time + capacity=4 we expect exactly 4 successes and 16 throttles.
  51. self::assertSame(4, $accepted, 'capacity-bounded successes');
  52. self::assertSame(16, $limited, 'remainder rate-limited');
  53. }
  54. public function testRateLimit429IncludesRetryAfter(): void
  55. {
  56. $reporterId = $this->createReporter('web-retry');
  57. $token = $this->createToken(TokenKind::Reporter, reporterId: $reporterId);
  58. $headers = ['Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json'];
  59. $body = json_encode(['ip' => '203.0.113.1', 'category' => 'brute_force']) ?: null;
  60. // Drain capacity first.
  61. for ($i = 0; $i < 4; $i++) {
  62. $this->request('POST', '/api/v1/report', $headers, $body);
  63. }
  64. $resp = $this->request('POST', '/api/v1/report', $headers, $body);
  65. self::assertSame(429, $resp->getStatusCode());
  66. self::assertSame('1', $resp->getHeaderLine('Retry-After'));
  67. }
  68. public function testAdminRoutesNotRateLimited(): void
  69. {
  70. $admin = $this->createToken(TokenKind::Admin, role: Role::Admin);
  71. // Admin routes should never 429 even when smashed.
  72. for ($i = 0; $i < 50; $i++) {
  73. $resp = $this->request('GET', '/api/v1/admin/me', [
  74. 'Authorization' => 'Bearer ' . $admin,
  75. ]);
  76. self::assertNotSame(429, $resp->getStatusCode());
  77. }
  78. }
  79. /**
  80. * SEC_REVIEW F14. The /api/v1/auth/* group previously had only
  81. * TokenAuth, so a service-token holder could brute-force enumerate
  82. * users via /users/{id} (F17) at unbounded rate, or burn unbounded
  83. * upsert calls. RateLimitMiddleware is now attached; a burst against
  84. * the auth endpoints must produce 429s once the bucket drains.
  85. */
  86. public function testAuthGetUserRouteIsRateLimited(): void
  87. {
  88. $service = $this->createToken(TokenKind::Service);
  89. $headers = ['Authorization' => 'Bearer ' . $service];
  90. $statuses = [];
  91. for ($i = 0; $i < 20; $i++) {
  92. $statuses[] = $this->request('GET', '/api/v1/auth/users/1', $headers)->getStatusCode();
  93. }
  94. $limited = count(array_filter($statuses, static fn (int $s): bool => $s === 429));
  95. self::assertGreaterThan(
  96. 0,
  97. $limited,
  98. 'auth/users/{id} must hit the rate-limit ceiling on burst (SEC_REVIEW F14)'
  99. );
  100. // Capacity is 4 (refill=2, capacity=4 from setUp); the rest must 429.
  101. self::assertSame(16, $limited, 'remainder rate-limited');
  102. }
  103. /**
  104. * SEC_REVIEW F14. upsertLocal/upsertOidc are also gated by the same
  105. * rate limit — a leaked service token cannot pound them at unbounded
  106. * rate to amplify other findings (e.g. burning audit rows, retrying
  107. * upsert combinations).
  108. */
  109. public function testAuthUpsertLocalRouteIsRateLimited(): void
  110. {
  111. $service = $this->createToken(TokenKind::Service);
  112. $headers = [
  113. 'Authorization' => 'Bearer ' . $service,
  114. 'Content-Type' => 'application/json',
  115. ];
  116. $body = json_encode(['username' => 'admin']) ?: null;
  117. $statuses = [];
  118. for ($i = 0; $i < 20; $i++) {
  119. $statuses[] = $this->request('POST', '/api/v1/auth/users/upsert-local', $headers, $body)
  120. ->getStatusCode();
  121. }
  122. $limited = count(array_filter($statuses, static fn (int $s): bool => $s === 429));
  123. self::assertGreaterThan(0, $limited, 'upsert-local must rate-limit');
  124. }
  125. /**
  126. * SEC_REVIEW F27. Auth-failed paths (401 from
  127. * TokenAuthenticationMiddleware) used to bypass the rate limiter
  128. * because RateLimitMiddleware sat *inside* TokenAuth. The handler
  129. * now also runs as the outermost layer, keying on `ip:` when no
  130. * principal exists, so invalid-bearer-token floods are throttled
  131. * before the DB lookup.
  132. */
  133. public function testInvalidBearerTokenFloodIsRateLimitedBeforeAuth(): void
  134. {
  135. $headers = ['Authorization' => 'Bearer ' . str_repeat('a', 32)];
  136. $statuses = [];
  137. for ($i = 0; $i < 20; $i++) {
  138. $statuses[] = $this->request('POST', '/api/v1/report', $headers)->getStatusCode();
  139. }
  140. $unauthorized = count(array_filter($statuses, static fn (int $s): bool => $s === 401));
  141. $limited = count(array_filter($statuses, static fn (int $s): bool => $s === 429));
  142. // Capacity is 4, so the first 4 attempts incur a token-table lookup
  143. // and return 401; the rest drain the IP bucket and return 429.
  144. self::assertSame(4, $unauthorized, 'first 4 attempts hit the auth path');
  145. self::assertSame(16, $limited, 'remaining attempts must 429 before auth');
  146. }
  147. public function testMissingBearerHeaderIsAlsoRateLimitedByIp(): void
  148. {
  149. // No Authorization header at all — same protection applies, the
  150. // request must not reach TokenAuth on every retry.
  151. $statuses = [];
  152. for ($i = 0; $i < 10; $i++) {
  153. $statuses[] = $this->request('GET', '/api/v1/blocklist')->getStatusCode();
  154. }
  155. $limited = count(array_filter($statuses, static fn (int $s): bool => $s === 429));
  156. self::assertGreaterThan(0, $limited, 'pre-auth flood must hit 429');
  157. }
  158. }