AppTestCase.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests\Integration\Support;
  4. use App\App\AppFactory;
  5. use App\App\Container;
  6. use App\Domain\Auth\Role;
  7. use App\Domain\Auth\TokenHasher;
  8. use App\Domain\Auth\TokenIssuer;
  9. use App\Domain\Auth\TokenKind;
  10. use App\Infrastructure\Auth\TokenRecord;
  11. use App\Infrastructure\Auth\TokenRepository;
  12. use Doctrine\DBAL\Connection;
  13. use Monolog\Handler\NullHandler;
  14. use Monolog\Logger;
  15. use Phinx\Config\Config;
  16. use Phinx\Migration\Manager;
  17. use PHPUnit\Framework\TestCase;
  18. use Psr\Container\ContainerInterface;
  19. use Psr\Log\LoggerInterface;
  20. use Slim\App;
  21. use Slim\Psr7\Factory\ServerRequestFactory;
  22. use Slim\Psr7\Factory\StreamFactory;
  23. use Symfony\Component\Console\Input\ArrayInput;
  24. use Symfony\Component\Console\Output\NullOutput;
  25. /**
  26. * Boots a fresh on-disk SQLite database, runs every migration + seeder
  27. * against it, and exposes helpers for hitting the Slim app from tests.
  28. *
  29. * On-disk (not :memory:) because Phinx runs in a separate connection from
  30. * our DBAL Connection — :memory: would give us two empty databases.
  31. *
  32. * Each test gets its own DB, container, and Slim app so state never leaks.
  33. */
  34. abstract class AppTestCase extends TestCase
  35. {
  36. protected ContainerInterface $container;
  37. protected App $app;
  38. protected Connection $db;
  39. protected string $sqlitePath;
  40. protected function setUp(): void
  41. {
  42. $this->sqlitePath = sys_get_temp_dir() . '/irdb-auth-' . bin2hex(random_bytes(6)) . '.sqlite';
  43. touch($this->sqlitePath);
  44. $config = new Config([
  45. 'paths' => [
  46. 'migrations' => __DIR__ . '/../../../db/migrations',
  47. 'seeds' => __DIR__ . '/../../../db/seeds',
  48. ],
  49. 'environments' => [
  50. 'default_migration_table' => 'phinxlog',
  51. 'default_environment' => 'test',
  52. 'test' => [
  53. 'adapter' => 'sqlite',
  54. 'name' => $this->sqlitePath,
  55. 'suffix' => '',
  56. ],
  57. ],
  58. 'version_order' => 'creation',
  59. ]);
  60. $manager = new Manager($config, new ArrayInput([]), new NullOutput());
  61. $manager->migrate('test');
  62. $manager->seed('test');
  63. $settings = [
  64. 'app_env' => 'development',
  65. 'log_level' => \Monolog\Level::Warning,
  66. 'app_secret' => 'test',
  67. 'db' => [
  68. 'driver' => 'sqlite',
  69. 'sqlite_path' => $this->sqlitePath,
  70. 'mysql_host' => '',
  71. 'mysql_port' => 3306,
  72. 'mysql_database' => '',
  73. 'mysql_username' => '',
  74. 'mysql_password' => '',
  75. ],
  76. 'ui_service_token' => '',
  77. 'internal_job_token' => '',
  78. 'ui_origin' => 'http://localhost:8080',
  79. 'oidc_default_role' => Role::Viewer,
  80. 'score_hard_cutoff_days' => 365,
  81. 'rate_limit_per_second' => 1000,
  82. 'cidr_evaluator_ttl_seconds' => 0,
  83. 'blocklist_cache_ttl_seconds' => 0,
  84. 'geoip' => [
  85. 'enabled' => true,
  86. 'provider' => 'dbip',
  87. 'country_db' => sys_get_temp_dir() . '/irdb-geoip-missing-country.mmdb',
  88. 'asn_db' => sys_get_temp_dir() . '/irdb-geoip-missing-asn.mmdb',
  89. 'maxmind_license_key' => '',
  90. 'ipinfo_token' => '',
  91. 'refresh_interval_days' => 7,
  92. ],
  93. ];
  94. $this->container = Container::build($settings);
  95. // Replace the logger with a null sink so integration tests don't spam
  96. // stdout (PHPUnit treats unexpected output as a "risky" outcome).
  97. if (method_exists($this->container, 'set')) {
  98. $nullLogger = new Logger('test');
  99. $nullLogger->pushHandler(new NullHandler());
  100. /** @var \DI\Container $container */
  101. $container = $this->container;
  102. $container->set(LoggerInterface::class, $nullLogger);
  103. }
  104. /** @var Connection $conn */
  105. $conn = $this->container->get(Connection::class);
  106. $this->db = $conn;
  107. $this->app = AppFactory::build($this->container);
  108. }
  109. protected function tearDown(): void
  110. {
  111. $this->db->close();
  112. if (file_exists($this->sqlitePath)) {
  113. @unlink($this->sqlitePath);
  114. }
  115. }
  116. /**
  117. * Issues a token of the given kind, persists it, and returns the raw
  118. * string. The caller can then send it as `Authorization: Bearer …`.
  119. */
  120. protected function createToken(
  121. TokenKind $kind,
  122. ?Role $role = null,
  123. ?int $reporterId = null,
  124. ?int $consumerId = null,
  125. ?int $userId = null,
  126. ): string {
  127. /** @var TokenIssuer $issuer */
  128. $issuer = $this->container->get(TokenIssuer::class);
  129. /** @var TokenHasher $hasher */
  130. $hasher = $this->container->get(TokenHasher::class);
  131. /** @var TokenRepository $repo */
  132. $repo = $this->container->get(TokenRepository::class);
  133. $raw = $issuer->issue($kind);
  134. $repo->create(new TokenRecord(
  135. id: null,
  136. kind: $kind,
  137. hash: $hasher->hash($raw),
  138. prefix: substr($raw, 0, 8),
  139. reporterId: $reporterId,
  140. consumerId: $consumerId,
  141. role: $role,
  142. expiresAt: null,
  143. revokedAt: null,
  144. lastUsedAt: null,
  145. userId: $userId,
  146. ));
  147. return $raw;
  148. }
  149. /**
  150. * Inserts a row in `users` with the given role and returns the id.
  151. * Pass `disabled: true` to seed a disabled row (SEC_REVIEW F11 tests).
  152. */
  153. protected function createUser(
  154. Role $role,
  155. bool $isLocal = false,
  156. ?string $subject = null,
  157. bool $disabled = false,
  158. ): int {
  159. $this->db->insert('users', [
  160. 'subject' => $subject,
  161. 'email' => $isLocal ? null : 'user@example.com',
  162. 'display_name' => $isLocal ? 'admin' : 'OIDC User',
  163. 'role' => $role->value,
  164. 'is_local' => $isLocal ? 1 : 0,
  165. 'disabled_at' => $disabled
  166. ? (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s')
  167. : null,
  168. ]);
  169. return (int) $this->db->lastInsertId();
  170. }
  171. protected function createReporter(string $name = 'rep-test'): int
  172. {
  173. $this->db->insert('reporters', [
  174. 'name' => $name,
  175. 'trust_weight' => '1.00',
  176. 'is_active' => 1,
  177. ]);
  178. return (int) $this->db->lastInsertId();
  179. }
  180. /**
  181. * @param array<string, string> $headers
  182. */
  183. protected function request(string $method, string $path, array $headers = [], ?string $body = null): \Psr\Http\Message\ResponseInterface
  184. {
  185. $reqFactory = new ServerRequestFactory();
  186. $request = $reqFactory->createServerRequest($method, $path);
  187. foreach ($headers as $name => $value) {
  188. $request = $request->withHeader($name, $value);
  189. }
  190. if ($body !== null) {
  191. $stream = (new StreamFactory())->createStream($body);
  192. $request = $request->withBody($stream);
  193. }
  194. return $this->app->handle($request);
  195. }
  196. /**
  197. * @return array<string, mixed>
  198. */
  199. protected function decode(\Psr\Http\Message\ResponseInterface $response): array
  200. {
  201. $raw = (string) $response->getBody();
  202. $decoded = json_decode($raw, true);
  203. self::assertIsArray($decoded, 'response body was not JSON: ' . $raw);
  204. return $decoded;
  205. }
  206. }