MigrationsTest.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests\Integration;
  4. use App\Infrastructure\Db\ConnectionFactory;
  5. use Doctrine\DBAL\Connection;
  6. use Phinx\Config\Config;
  7. use Phinx\Migration\Manager;
  8. use PHPUnit\Framework\TestCase;
  9. use Symfony\Component\Console\Input\ArrayInput;
  10. use Symfony\Component\Console\Output\NullOutput;
  11. /**
  12. * Boots an in-memory SQLite database, runs every Phinx migration against it,
  13. * and asserts that the resulting schema has every SPEC §4 table with the
  14. * expected key columns. This catches gross mistakes (missing tables, missing
  15. * binary columns) without depending on MySQL being available locally.
  16. */
  17. final class MigrationsTest extends TestCase
  18. {
  19. private string $sqlitePath;
  20. private Connection $connection;
  21. protected function setUp(): void
  22. {
  23. $this->sqlitePath = sys_get_temp_dir() . '/irdb-migrations-' . bin2hex(random_bytes(6)) . '.sqlite';
  24. $config = new Config([
  25. 'paths' => [
  26. 'migrations' => __DIR__ . '/../../db/migrations',
  27. 'seeds' => __DIR__ . '/../../db/seeds',
  28. ],
  29. 'environments' => [
  30. 'default_migration_table' => 'phinxlog',
  31. 'default_environment' => 'test',
  32. 'test' => [
  33. 'adapter' => 'sqlite',
  34. 'name' => $this->sqlitePath,
  35. 'suffix' => '',
  36. ],
  37. ],
  38. 'version_order' => 'creation',
  39. ]);
  40. $manager = new Manager($config, new ArrayInput([]), new NullOutput());
  41. $manager->migrate('test');
  42. $manager->seed('test');
  43. $factory = new ConnectionFactory([
  44. 'driver' => 'sqlite',
  45. 'sqlite_path' => $this->sqlitePath,
  46. 'mysql_host' => '',
  47. 'mysql_port' => 3306,
  48. 'mysql_database' => '',
  49. 'mysql_username' => '',
  50. 'mysql_password' => '',
  51. ]);
  52. $this->connection = $factory->create();
  53. }
  54. protected function tearDown(): void
  55. {
  56. $this->connection->close();
  57. if (file_exists($this->sqlitePath)) {
  58. @unlink($this->sqlitePath);
  59. }
  60. }
  61. public function testEverySpecTableExists(): void
  62. {
  63. $expected = [
  64. 'users',
  65. 'oidc_role_mappings',
  66. 'reporters',
  67. 'consumers',
  68. 'policies',
  69. 'policy_category_thresholds',
  70. 'categories',
  71. 'api_tokens',
  72. 'reports',
  73. 'ip_scores',
  74. 'ip_enrichment',
  75. 'manual_blocks',
  76. 'allowlist',
  77. 'audit_log',
  78. 'job_locks',
  79. 'job_runs',
  80. ];
  81. $rows = $this->connection
  82. ->executeQuery("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
  83. ->fetchAllAssociative();
  84. $tables = array_column($rows, 'name');
  85. foreach ($expected as $name) {
  86. self::assertContains($name, $tables, "Missing table: {$name}");
  87. }
  88. }
  89. public function testReportsHasExpectedColumns(): void
  90. {
  91. $columns = $this->columnsOf('reports');
  92. foreach (['id', 'ip_bin', 'ip_text', 'category_id', 'reporter_id', 'weight_at_report', 'received_at', 'metadata_json'] as $col) {
  93. self::assertArrayHasKey($col, $columns, "reports missing column {$col}");
  94. }
  95. }
  96. public function testIpScoresHasCompositePrimaryKey(): void
  97. {
  98. $rows = $this->connection
  99. ->executeQuery('PRAGMA table_info(ip_scores)')
  100. ->fetchAllAssociative();
  101. $pkCols = [];
  102. foreach ($rows as $r) {
  103. if ((int) $r['pk'] > 0) {
  104. $pkCols[(int) $r['pk']] = $r['name'];
  105. }
  106. }
  107. ksort($pkCols);
  108. self::assertSame(['ip_bin', 'category_id'], array_values($pkCols));
  109. }
  110. public function testPolicyCategoryThresholdsHasCompositePrimaryKey(): void
  111. {
  112. $rows = $this->connection
  113. ->executeQuery('PRAGMA table_info(policy_category_thresholds)')
  114. ->fetchAllAssociative();
  115. $pkCols = [];
  116. foreach ($rows as $r) {
  117. if ((int) $r['pk'] > 0) {
  118. $pkCols[(int) $r['pk']] = $r['name'];
  119. }
  120. }
  121. ksort($pkCols);
  122. self::assertSame(['policy_id', 'category_id'], array_values($pkCols));
  123. }
  124. public function testJobLocksPkIsJobName(): void
  125. {
  126. $rows = $this->connection
  127. ->executeQuery('PRAGMA table_info(job_locks)')
  128. ->fetchAllAssociative();
  129. $pkCols = [];
  130. foreach ($rows as $r) {
  131. if ((int) $r['pk'] > 0) {
  132. $pkCols[(int) $r['pk']] = $r['name'];
  133. }
  134. }
  135. self::assertSame(['job_name'], array_values($pkCols));
  136. }
  137. public function testIpEnrichmentPkIsIpBin(): void
  138. {
  139. $rows = $this->connection
  140. ->executeQuery('PRAGMA table_info(ip_enrichment)')
  141. ->fetchAllAssociative();
  142. $pkCols = [];
  143. foreach ($rows as $r) {
  144. if ((int) $r['pk'] > 0) {
  145. $pkCols[(int) $r['pk']] = $r['name'];
  146. }
  147. }
  148. self::assertSame(['ip_bin'], array_values($pkCols));
  149. }
  150. public function testReportsHasIpBinIndex(): void
  151. {
  152. $rows = $this->connection
  153. ->executeQuery("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='reports'")
  154. ->fetchAllAssociative();
  155. $indexNames = array_column($rows, 'name');
  156. $matchesCompound = false;
  157. foreach ($indexNames as $n) {
  158. if (str_contains($n, 'ip_cat_received') || str_contains($n, 'ip_bin')) {
  159. $matchesCompound = true;
  160. }
  161. }
  162. self::assertTrue($matchesCompound, 'reports should have an index covering ip_bin');
  163. }
  164. public function testApiTokensCheckConstraintEnforced(): void
  165. {
  166. // valid: kind=admin, both NULL
  167. $this->connection->executeStatement(
  168. "INSERT INTO api_tokens (token_hash, token_prefix, kind) VALUES ('a', 'admxxxx', 'admin')"
  169. );
  170. // invalid: kind=reporter without reporter_id
  171. $threw = false;
  172. try {
  173. $this->connection->executeStatement(
  174. "INSERT INTO api_tokens (token_hash, token_prefix, kind) VALUES ('b', 'repxxxx', 'reporter')"
  175. );
  176. } catch (\Throwable) {
  177. $threw = true;
  178. }
  179. self::assertTrue($threw, 'CHECK constraint should reject kind=reporter without reporter_id');
  180. // invalid: kind=service with reporter_id set
  181. $threw = false;
  182. try {
  183. // Need a reporter row first for the FK to be satisfiable.
  184. $this->connection->executeStatement(
  185. "INSERT INTO reporters (name, trust_weight, is_active) VALUES ('rx', 1.0, 1)"
  186. );
  187. $rid = (int) $this->connection->lastInsertId();
  188. $this->connection->executeStatement(
  189. 'INSERT INTO api_tokens (token_hash, token_prefix, kind, reporter_id) VALUES (?, ?, ?, ?)',
  190. ['c', 'svcxxxx', 'service', $rid]
  191. );
  192. } catch (\Throwable) {
  193. $threw = true;
  194. }
  195. self::assertTrue($threw, 'CHECK constraint should reject kind=service with reporter_id set');
  196. }
  197. public function testForeignKeysEnforcedOnSqlite(): void
  198. {
  199. // foreign_keys PRAGMA must be on for the constraint to fire.
  200. $threw = false;
  201. try {
  202. $this->connection->executeStatement(
  203. 'INSERT INTO consumers (name, policy_id, is_active) VALUES (?, ?, ?)',
  204. ['x', 99999, 1]
  205. );
  206. } catch (\Throwable) {
  207. $threw = true;
  208. }
  209. self::assertTrue($threw, 'consumers.policy_id FK should reject unknown policy id');
  210. }
  211. public function testSeedsPopulatedDefaults(): void
  212. {
  213. $catCount = (int) $this->connection->fetchOne('SELECT COUNT(*) FROM categories');
  214. $polCount = (int) $this->connection->fetchOne('SELECT COUNT(*) FROM policies');
  215. $thrCount = (int) $this->connection->fetchOne('SELECT COUNT(*) FROM policy_category_thresholds');
  216. self::assertSame(5, $catCount);
  217. self::assertSame(3, $polCount);
  218. self::assertSame(15, $thrCount);
  219. }
  220. public function testSeedersAreIdempotent(): void
  221. {
  222. // Run seed again; counts must not change.
  223. $config = new Config([
  224. 'paths' => [
  225. 'migrations' => __DIR__ . '/../../db/migrations',
  226. 'seeds' => __DIR__ . '/../../db/seeds',
  227. ],
  228. 'environments' => [
  229. 'default_migration_table' => 'phinxlog',
  230. 'default_environment' => 'test',
  231. 'test' => [
  232. 'adapter' => 'sqlite',
  233. 'name' => $this->sqlitePath,
  234. 'suffix' => '',
  235. ],
  236. ],
  237. 'version_order' => 'creation',
  238. ]);
  239. $manager = new Manager($config, new ArrayInput([]), new NullOutput());
  240. $manager->seed('test');
  241. self::assertSame(5, (int) $this->connection->fetchOne('SELECT COUNT(*) FROM categories'));
  242. self::assertSame(3, (int) $this->connection->fetchOne('SELECT COUNT(*) FROM policies'));
  243. self::assertSame(15, (int) $this->connection->fetchOne('SELECT COUNT(*) FROM policy_category_thresholds'));
  244. }
  245. /**
  246. * @return array<string, array<string, mixed>>
  247. */
  248. private function columnsOf(string $table): array
  249. {
  250. $rows = $this->connection
  251. ->executeQuery(sprintf('PRAGMA table_info(%s)', $table))
  252. ->fetchAllAssociative();
  253. $cols = [];
  254. foreach ($rows as $r) {
  255. $cols[$r['name']] = $r;
  256. }
  257. return $cols;
  258. }
  259. }