StatsControllerTest.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests\Integration\Admin;
  4. use App\Domain\Auth\Role;
  5. use App\Domain\Auth\TokenKind;
  6. use App\Domain\Ip\IpAddress;
  7. use App\Tests\Integration\Support\AppTestCase;
  8. use Doctrine\DBAL\ParameterType;
  9. /**
  10. * Covers the dashboard endpoint shape: scalar counters, by-hour
  11. * histogram, top reporters/categories, jobs status. Cache TTL is 30s
  12. * but the test issues each request with fresh state — we don't
  13. * exercise the cache window directly here.
  14. */
  15. final class StatsControllerTest extends AppTestCase
  16. {
  17. public function testDashboardEmptyShape(): void
  18. {
  19. $token = $this->createToken(TokenKind::Admin, role: Role::Viewer);
  20. $response = $this->request('GET', '/api/v1/admin/stats/dashboard', [
  21. 'Authorization' => 'Bearer ' . $token,
  22. ]);
  23. self::assertSame(200, $response->getStatusCode());
  24. $body = $this->decode($response);
  25. foreach (['active_blocks', 'manual_blocks_count', 'allowlist_count', 'reports_24h'] as $k) {
  26. self::assertArrayHasKey($k, $body);
  27. self::assertSame(0, $body[$k]);
  28. }
  29. self::assertSame([], $body['reports_24h_by_hour']);
  30. self::assertSame([], $body['top_reporters_24h']);
  31. self::assertSame([], $body['top_categories_24h']);
  32. // blocked_ips_by_day_7d always emits 8 days (today + the 7 prior, zero-filled).
  33. self::assertArrayHasKey('blocked_ips_by_day_7d', $body);
  34. $blocked = $body['blocked_ips_by_day_7d'];
  35. self::assertArrayHasKey('days', $blocked);
  36. self::assertArrayHasKey('series', $blocked);
  37. self::assertCount(8, $blocked['days']);
  38. // Seeders create the default categories — every active one should
  39. // appear as a flat-zero series even with no reports yet.
  40. self::assertNotEmpty($blocked['series']);
  41. foreach ($blocked['series'] as $row) {
  42. self::assertArrayHasKey('category', $row);
  43. self::assertArrayHasKey('counts', $row);
  44. self::assertCount(8, $row['counts']);
  45. self::assertSame(0, array_sum(array_map('intval', $row['counts'])));
  46. }
  47. self::assertSame('moderate', $body['reference_policy']);
  48. }
  49. public function testDashboardCountsFromSeededReports(): void
  50. {
  51. // Use a fresh class-level container/session per test (setUp does this).
  52. $token = $this->createToken(TokenKind::Admin, role: Role::Viewer);
  53. $reporterId = $this->createReporter('rep-stats');
  54. for ($i = 0; $i < 3; ++$i) {
  55. $this->seedReport(sprintf('203.0.113.%d', 10 + $i), 'brute_force', $reporterId);
  56. }
  57. $this->seedReport('203.0.113.20', 'spam', $reporterId);
  58. $body = $this->decode($this->request('GET', '/api/v1/admin/stats/dashboard', [
  59. 'Authorization' => 'Bearer ' . $token,
  60. ]));
  61. self::assertSame(4, $body['reports_24h']);
  62. self::assertNotEmpty($body['reports_24h_by_hour']);
  63. self::assertSame('rep-stats', $body['top_reporters_24h'][0]['name']);
  64. self::assertSame(4, $body['top_reporters_24h'][0]['count']);
  65. $catSlugs = array_map(static fn (array $r): string => $r['slug'], $body['top_categories_24h']);
  66. self::assertContains('brute_force', $catSlugs);
  67. self::assertContains('spam', $catSlugs);
  68. }
  69. public function testManualBlocksAndAllowlistCounters(): void
  70. {
  71. $token = $this->createToken(TokenKind::Admin, role: Role::Viewer);
  72. $this->db->insert('manual_blocks', [
  73. 'kind' => 'ip',
  74. 'ip_bin' => IpAddress::fromString('203.0.113.5')->binary(),
  75. 'reason' => 'x',
  76. ], ['ip_bin' => ParameterType::LARGE_OBJECT]);
  77. $this->db->insert('allowlist', [
  78. 'kind' => 'ip',
  79. 'ip_bin' => IpAddress::fromString('203.0.113.6')->binary(),
  80. 'reason' => 'y',
  81. ], ['ip_bin' => ParameterType::LARGE_OBJECT]);
  82. $body = $this->decode($this->request('GET', '/api/v1/admin/stats/dashboard', [
  83. 'Authorization' => 'Bearer ' . $token,
  84. ]));
  85. self::assertSame(1, $body['manual_blocks_count']);
  86. self::assertSame(1, $body['allowlist_count']);
  87. }
  88. public function testBlockedIpsByDayBucketsByCategory(): void
  89. {
  90. $token = $this->createToken(TokenKind::Admin, role: Role::Viewer);
  91. $reporterId = $this->createReporter('rep-cat-bucket');
  92. // Two distinct IPs in `brute_force`, one in `spam`. The same IP
  93. // reported twice in `brute_force` must still count as one (the
  94. // sum is COUNT DISTINCT ip_bin per category per day).
  95. $this->seedReport('203.0.113.10', 'brute_force', $reporterId);
  96. $this->seedReport('203.0.113.10', 'brute_force', $reporterId);
  97. $this->seedReport('203.0.113.11', 'brute_force', $reporterId);
  98. $this->seedReport('203.0.113.20', 'spam', $reporterId);
  99. $body = $this->decode($this->request('GET', '/api/v1/admin/stats/dashboard', [
  100. 'Authorization' => 'Bearer ' . $token,
  101. ]));
  102. $blocked = $body['blocked_ips_by_day_7d'];
  103. self::assertCount(8, $blocked['days']);
  104. $byCategory = [];
  105. foreach ($blocked['series'] as $row) {
  106. $byCategory[$row['category']] = array_sum(array_map('intval', $row['counts']));
  107. }
  108. self::assertArrayHasKey('brute_force', $byCategory);
  109. self::assertArrayHasKey('spam', $byCategory);
  110. self::assertSame(2, $byCategory['brute_force']);
  111. self::assertSame(1, $byCategory['spam']);
  112. }
  113. private function seedReport(string $ip, string $categorySlug, int $reporterId): void
  114. {
  115. $catId = (int) $this->db->fetchOne('SELECT id FROM categories WHERE slug = :s', ['s' => $categorySlug]);
  116. $ipObj = IpAddress::fromString($ip);
  117. $stmt = $this->db->prepare(
  118. 'INSERT INTO reports (ip_bin, ip_text, category_id, reporter_id, weight_at_report, received_at, metadata_json) '
  119. . 'VALUES (:b, :t, :c, :r, :w, :now, NULL)'
  120. );
  121. $stmt->bindValue('b', $ipObj->binary(), ParameterType::LARGE_OBJECT);
  122. $stmt->bindValue('t', $ipObj->text());
  123. $stmt->bindValue('c', $catId, ParameterType::INTEGER);
  124. $stmt->bindValue('r', $reporterId, ParameterType::INTEGER);
  125. $stmt->bindValue('w', '1.00');
  126. $stmt->bindValue('now', (new \DateTimeImmutable('now'))->format('Y-m-d H:i:s'));
  127. $stmt->executeStatement();
  128. }
  129. }