1
0

LoginThrottleTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests\Unit\Auth;
  4. use App\Auth\LoginThrottle;
  5. use Monolog\Handler\NullHandler;
  6. use Monolog\Handler\TestHandler;
  7. use Monolog\Logger;
  8. use PHPUnit\Framework\TestCase;
  9. use Psr\Log\LoggerInterface;
  10. /**
  11. * Brute-force lockout progression: 5/10/15 attempts trigger 60/300/1800-second
  12. * locks. The (username, ip) tuple gates the bucket so the legit admin from
  13. * another IP isn't locked out by an attacker spraying one address.
  14. */
  15. final class LoginThrottleTest extends TestCase
  16. {
  17. public function testFastRetryUnderFive(): void
  18. {
  19. $t = $this->throttle();
  20. for ($i = 0; $i < 4; ++$i) {
  21. $t->recordFailure('admin', '10.0.0.1');
  22. }
  23. self::assertFalse($t->isLocked('admin', '10.0.0.1'));
  24. }
  25. public function testFifthFailureLocksForOneMinute(): void
  26. {
  27. $t = $this->throttle();
  28. for ($i = 0; $i < 5; ++$i) {
  29. $t->recordFailure('admin', '10.0.0.1');
  30. }
  31. self::assertTrue($t->isLocked('admin', '10.0.0.1'));
  32. self::assertGreaterThanOrEqual(60, $t->lockoutSecondsRemaining('admin', '10.0.0.1'));
  33. self::assertLessThanOrEqual(60, $t->lockoutSecondsRemaining('admin', '10.0.0.1'));
  34. }
  35. public function testTenthFailureLocksForFiveMinutes(): void
  36. {
  37. $now = 1000000;
  38. $t = $this->throttle($now);
  39. for ($i = 0; $i < 10; ++$i) {
  40. $t->recordFailure('admin', '10.0.0.1');
  41. }
  42. self::assertSame(300, $t->lockoutSecondsRemaining('admin', '10.0.0.1'));
  43. }
  44. public function testFifteenthFailureLocksForThirtyMinutes(): void
  45. {
  46. $now = 1000000;
  47. $t = $this->throttle($now);
  48. for ($i = 0; $i < 15; ++$i) {
  49. $t->recordFailure('admin', '10.0.0.1');
  50. }
  51. self::assertSame(1800, $t->lockoutSecondsRemaining('admin', '10.0.0.1'));
  52. }
  53. public function testLockoutExpiresAfterTimeAdvance(): void
  54. {
  55. $now = 1000000;
  56. $t = new LoginThrottle($this->logger(), function () use (&$now): int {
  57. return $now;
  58. });
  59. for ($i = 0; $i < 5; ++$i) {
  60. $t->recordFailure('admin', '10.0.0.1');
  61. }
  62. self::assertTrue($t->isLocked('admin', '10.0.0.1'));
  63. $now += 61;
  64. self::assertFalse($t->isLocked('admin', '10.0.0.1'));
  65. }
  66. public function testDifferentIpHasIndependentBucket(): void
  67. {
  68. $t = $this->throttle();
  69. for ($i = 0; $i < 5; ++$i) {
  70. $t->recordFailure('admin', '10.0.0.1');
  71. }
  72. self::assertTrue($t->isLocked('admin', '10.0.0.1'));
  73. self::assertFalse($t->isLocked('admin', '10.0.0.2'));
  74. }
  75. public function testClearResetsBucket(): void
  76. {
  77. $t = $this->throttle();
  78. for ($i = 0; $i < 5; ++$i) {
  79. $t->recordFailure('admin', '10.0.0.1');
  80. }
  81. $t->clear('admin', '10.0.0.1');
  82. self::assertFalse($t->isLocked('admin', '10.0.0.1'));
  83. self::assertSame(0, $t->lockoutSecondsRemaining('admin', '10.0.0.1'));
  84. }
  85. public function testUsernameCaseDoesNotMultiplyBuckets(): void
  86. {
  87. $t = $this->throttle();
  88. for ($i = 0; $i < 3; ++$i) {
  89. $t->recordFailure('admin', '10.0.0.1');
  90. }
  91. for ($i = 0; $i < 2; ++$i) {
  92. $t->recordFailure('ADMIN', '10.0.0.1');
  93. }
  94. self::assertTrue($t->isLocked('Admin', '10.0.0.1'));
  95. }
  96. public function testPerUsernameBucketLocksOutAcrossDistinctIps(): void
  97. {
  98. $t = $this->throttle();
  99. // 24 failures from 24 distinct IPs — each is a fresh per-IP bucket
  100. // (only 1 attempt apiece), but the per-username counter accumulates.
  101. for ($i = 0; $i < 24; ++$i) {
  102. $t->recordFailure('admin', '10.0.0.' . $i);
  103. }
  104. self::assertFalse($t->isLocked('admin', '10.0.0.99'));
  105. // 25th attempt from yet another IP trips the per-username lockout.
  106. $t->recordFailure('admin', '10.0.0.99');
  107. self::assertTrue($t->isLocked('admin', '10.0.1.1'));
  108. }
  109. public function testPerUsernameLadderProgresses(): void
  110. {
  111. $now = 1000000;
  112. $t = $this->throttle($now);
  113. for ($i = 0; $i < 25; ++$i) {
  114. $t->recordFailure('admin', '10.0.0.' . $i);
  115. }
  116. self::assertSame(60, $t->lockoutSecondsRemaining('admin', '10.99.0.1'));
  117. for ($i = 25; $i < 50; ++$i) {
  118. $t->recordFailure('admin', '10.0.0.' . $i);
  119. }
  120. self::assertSame(300, $t->lockoutSecondsRemaining('admin', '10.99.0.1'));
  121. for ($i = 50; $i < 100; ++$i) {
  122. $t->recordFailure('admin', '10.0.0.' . $i);
  123. }
  124. self::assertSame(1800, $t->lockoutSecondsRemaining('admin', '10.99.0.1'));
  125. }
  126. public function testLockoutSecondsRemainingReturnsLargerOfBuckets(): void
  127. {
  128. $now = 1000000;
  129. $t = $this->throttle($now);
  130. // 5 failures from one IP → per-IP locked for 60s.
  131. for ($i = 0; $i < 5; ++$i) {
  132. $t->recordFailure('admin', '10.0.0.1');
  133. }
  134. // Plus 45 more from distinct IPs → per-username at count=50 → 300s.
  135. for ($i = 0; $i < 45; ++$i) {
  136. $t->recordFailure('admin', '10.1.0.' . $i);
  137. }
  138. // Asked from yet-another-IP, only the per-username lock applies — 300s.
  139. self::assertSame(300, $t->lockoutSecondsRemaining('admin', '10.99.0.1'));
  140. // Asked from the per-IP bucket's IP, 300s still wins (max of 60/300).
  141. self::assertSame(300, $t->lockoutSecondsRemaining('admin', '10.0.0.1'));
  142. }
  143. public function testClearResetsBothBuckets(): void
  144. {
  145. $t = $this->throttle();
  146. // Build per-username pressure.
  147. for ($i = 0; $i < 25; ++$i) {
  148. $t->recordFailure('admin', '10.0.0.' . $i);
  149. }
  150. self::assertTrue($t->isLocked('admin', '10.99.0.1'));
  151. $t->clear('admin', '10.0.0.0');
  152. self::assertFalse($t->isLocked('admin', '10.99.0.1'));
  153. self::assertSame(0, $t->lockoutSecondsRemaining('admin', '10.99.0.1'));
  154. }
  155. public function testEmptyUsernameStillBucketsPerUsername(): void
  156. {
  157. $t = $this->throttle();
  158. for ($i = 0; $i < 25; ++$i) {
  159. $t->recordFailure('', '10.0.0.' . $i);
  160. }
  161. self::assertTrue($t->isLocked('', '10.99.0.1'));
  162. }
  163. public function testRecordFailureLogRateIsCappedToFirstWarningPerBucket(): void
  164. {
  165. // SEC_REVIEW F74: a sustained brute-force attack must not
  166. // pour one structured log line per failed attempt into the
  167. // disk/SIEM pipeline. The throttle now emits a single
  168. // `warning` per (username, ip) bucket — at the first
  169. // failure — and stays silent until a lockout fires (which
  170. // emits an `error`). The lockout's `failure_count` field
  171. // captures the burst size, so total visibility is preserved
  172. // without per-attempt spam.
  173. $handler = new TestHandler();
  174. $logger = new Logger('test');
  175. $logger->pushHandler($handler);
  176. $t = new LoginThrottle($logger);
  177. // Drive 5 failures: counts 1, 2, 3, 4, 5. Lockout fires at
  178. // 5. Expected log emissions: 1 warning (count=1) + 1 error
  179. // (count=5 lockout) = 2 lines, NOT 5.
  180. for ($i = 0; $i < 5; ++$i) {
  181. $t->recordFailure('admin', '10.0.0.1');
  182. }
  183. $warnings = array_filter(
  184. $handler->getRecords(),
  185. static fn ($r) => $r->level->name === 'Warning',
  186. );
  187. $errors = array_filter(
  188. $handler->getRecords(),
  189. static fn ($r) => $r->level->name === 'Error',
  190. );
  191. self::assertCount(1, $warnings, 'expected a single warning at the first failure');
  192. self::assertGreaterThanOrEqual(1, count($errors), 'expected at least one lockout error');
  193. // The single warning must record `failure_count = 1`.
  194. /** @var \Monolog\LogRecord $w */
  195. $w = array_values($warnings)[0];
  196. self::assertSame(1, $w->context['failure_count']);
  197. }
  198. public function testHighRateBruteForceDoesNotSpamPerFailureWarnings(): void
  199. {
  200. // 100 attempts from one IP for one username: pre-fix would
  201. // have emitted ~4 warnings per bucket (counts 1..4) before
  202. // lockout. With the rate cap, exactly 1 warning fires.
  203. // Subsequent attempts past the lockout are not recorded
  204. // (the controller-side `isLocked` check skips
  205. // `recordFailure`), so the test models the bucket-internal
  206. // behaviour by calling `recordFailure` directly 100 times —
  207. // we want to see the cap survive even if a future change
  208. // slipped past the controller-level guard.
  209. $handler = new TestHandler();
  210. $logger = new Logger('test');
  211. $logger->pushHandler($handler);
  212. $t = new LoginThrottle($logger);
  213. for ($i = 0; $i < 100; ++$i) {
  214. $t->recordFailure('admin', '10.0.0.1');
  215. }
  216. $warnings = array_filter(
  217. $handler->getRecords(),
  218. static fn ($r) => $r->level->name === 'Warning',
  219. );
  220. // No matter how many failures we drive into the same bucket,
  221. // we get a single warning. The error count is bounded by
  222. // the lockout ladder (5 / 10 / 15 IP-bucket triggers and
  223. // 25 / 50 / 100 username-bucket triggers).
  224. self::assertCount(1, $warnings);
  225. }
  226. public function testRecordFailureLogsFingerprintsNotRawIdentifiers(): void
  227. {
  228. // SEC_REVIEW F34: a SIEM operator reading these logs must not see
  229. // the attempted username (which can be a password typed in the
  230. // wrong field) or the raw client IP. They must see a stable
  231. // fingerprint instead so triage can still correlate.
  232. $handler = new TestHandler();
  233. $logger = new Logger('test');
  234. $logger->pushHandler($handler);
  235. $t = new LoginThrottle($logger);
  236. $rawUser = 'hunter2-typed-into-username-field';
  237. $rawIp = '198.51.100.77';
  238. for ($i = 0; $i < 5; ++$i) {
  239. $t->recordFailure($rawUser, $rawIp);
  240. }
  241. self::assertNotEmpty($handler->getRecords(), 'expected lockout/failure events to be logged');
  242. foreach ($handler->getRecords() as $record) {
  243. $serialized = json_encode([
  244. 'message' => $record->message,
  245. 'context' => $record->context,
  246. ], \JSON_THROW_ON_ERROR);
  247. self::assertStringNotContainsString($rawUser, $serialized);
  248. self::assertStringNotContainsString($rawIp, $serialized);
  249. self::assertArrayHasKey('username_fp', $record->context);
  250. self::assertArrayHasKey('source_ip_fp', $record->context);
  251. self::assertArrayNotHasKey('username', $record->context);
  252. self::assertArrayNotHasKey('source_ip', $record->context);
  253. }
  254. }
  255. private function throttle(?int $fixedTime = null): LoginThrottle
  256. {
  257. if ($fixedTime === null) {
  258. return new LoginThrottle($this->logger());
  259. }
  260. return new LoginThrottle($this->logger(), static fn (): int => $fixedTime);
  261. }
  262. private function logger(): LoggerInterface
  263. {
  264. $l = new Logger('test');
  265. $l->pushHandler(new NullHandler());
  266. return $l;
  267. }
  268. }