1
0

JobsEndpointsTest.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests\Integration\Internal;
  4. use App\Tests\Integration\Support\AppTestCase;
  5. /**
  6. * End-to-end coverage for `/internal/jobs/*`. The AppTestCase boots a Slim
  7. * app whose ServerRequestFactory does NOT populate REMOTE_ADDR — so we
  8. * inject one explicitly via the request() helper override below to satisfy
  9. * InternalNetworkMiddleware.
  10. */
  11. final class JobsEndpointsTest extends AppTestCase
  12. {
  13. private const TOKEN = 'test-internal-token';
  14. protected function setUp(): void
  15. {
  16. // Ensure the container picks up our internal token.
  17. putenv('INTERNAL_JOB_TOKEN=' . self::TOKEN);
  18. $_ENV['INTERNAL_JOB_TOKEN'] = self::TOKEN;
  19. $_SERVER['INTERNAL_JOB_TOKEN'] = self::TOKEN;
  20. parent::setUp();
  21. // Override the internal-token middleware in the container so the
  22. // running Slim app validates against our test token. The base
  23. // AppTestCase wires a settings bundle that doesn't include the
  24. // token, so we patch the InternalTokenMiddleware factory directly.
  25. if (method_exists($this->container, 'set')) {
  26. /** @var \DI\Container $container */
  27. $container = $this->container;
  28. $container->set(
  29. \App\Infrastructure\Http\Middleware\InternalTokenMiddleware::class,
  30. new \App\Infrastructure\Http\Middleware\InternalTokenMiddleware(
  31. new \Slim\Psr7\Factory\ResponseFactory(),
  32. self::TOKEN,
  33. ),
  34. );
  35. }
  36. // Rebuild the app so it picks up the patched middleware.
  37. $this->app = \App\App\AppFactory::build($this->container);
  38. }
  39. public function testTickRequiresToken(): void
  40. {
  41. $resp = $this->internalRequest('POST', '/internal/jobs/tick', headers: []);
  42. self::assertSame(401, $resp->getStatusCode());
  43. }
  44. public function testTickRejectsWrongToken(): void
  45. {
  46. $resp = $this->internalRequest(
  47. 'POST',
  48. '/internal/jobs/tick',
  49. headers: ['Authorization' => 'Bearer wrong'],
  50. );
  51. self::assertSame(401, $resp->getStatusCode());
  52. }
  53. public function testExternalSourceReturns404OpaquePerSpec(): void
  54. {
  55. $resp = $this->internalRequest(
  56. 'POST',
  57. '/internal/jobs/tick',
  58. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  59. remoteAddr: '8.8.8.8',
  60. );
  61. self::assertSame(404, $resp->getStatusCode());
  62. }
  63. public function testTickSuccessProducesEnvelope(): void
  64. {
  65. $resp = $this->internalRequest(
  66. 'POST',
  67. '/internal/jobs/tick',
  68. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  69. );
  70. self::assertSame(200, $resp->getStatusCode());
  71. $body = $this->decode($resp);
  72. self::assertSame('tick', $body['job']);
  73. self::assertSame('success', $body['status']);
  74. self::assertArrayHasKey('run_id', $body);
  75. self::assertArrayHasKey('duration_ms', $body);
  76. }
  77. public function testRecomputeSucceedsWithEmptyTables(): void
  78. {
  79. $resp = $this->internalRequest(
  80. 'POST',
  81. '/internal/jobs/recompute-scores',
  82. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  83. );
  84. self::assertSame(200, $resp->getStatusCode());
  85. $body = $this->decode($resp);
  86. self::assertSame('recompute-scores', $body['job']);
  87. self::assertSame('success', $body['status']);
  88. }
  89. public function testConcurrentRecomputeProducesOneSuccessOneSkipped(): void
  90. {
  91. // Pre-acquire the lock to simulate "another worker is busy". The
  92. // second HTTP call must come back 409 with skipped_locked.
  93. $now = (new \DateTimeImmutable('now', new \DateTimeZone('UTC')));
  94. $lockSql = 'INSERT INTO job_locks (job_name, acquired_by, acquired_at, expires_at) '
  95. . 'VALUES (:job, :owner, :acquired, :expires)';
  96. $this->db->executeStatement($lockSql, [
  97. 'job' => 'recompute-scores',
  98. 'owner' => 'OTHER',
  99. 'acquired' => $now->format('Y-m-d H:i:s'),
  100. 'expires' => $now->modify('+5 minutes')->format('Y-m-d H:i:s'),
  101. ]);
  102. $resp = $this->internalRequest(
  103. 'POST',
  104. '/internal/jobs/recompute-scores',
  105. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  106. body: '{"full": true}',
  107. );
  108. self::assertSame(409, $resp->getStatusCode());
  109. $body = $this->decode($resp);
  110. self::assertSame('skipped_locked', $body['status']);
  111. }
  112. public function testRefreshGeoipDoesNotShortCircuitOnDbipDefault(): void
  113. {
  114. // dbip is the default test provider; requiresCredential() is false.
  115. // dry_run avoids the actual download.
  116. $resp = $this->internalRequest(
  117. 'POST',
  118. '/internal/jobs/refresh-geoip?dry_run=1',
  119. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  120. );
  121. self::assertNotSame(412, $resp->getStatusCode());
  122. }
  123. public function testRefreshGeoipReturns412WithoutCredentialOnMaxmind(): void
  124. {
  125. // Patch the container's downloader to MaxMind without a key.
  126. $this->swapDownloader(new \App\Infrastructure\Enrichment\Downloaders\MaxMindDownloader(
  127. new \GuzzleHttp\Client(),
  128. licenseKey: '',
  129. ));
  130. $resp = $this->internalRequest(
  131. 'POST',
  132. '/internal/jobs/refresh-geoip',
  133. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  134. );
  135. self::assertSame(412, $resp->getStatusCode());
  136. $body = $this->decode($resp);
  137. self::assertSame('no_credential', $body['error']);
  138. self::assertSame('maxmind', $body['provider']);
  139. self::assertSame('MAXMIND_LICENSE_KEY', $body['missing']);
  140. }
  141. public function testRefreshGeoipReturns412WithoutTokenOnIpinfo(): void
  142. {
  143. $this->swapDownloader(new \App\Infrastructure\Enrichment\Downloaders\IPinfoDownloader(
  144. new \GuzzleHttp\Client(),
  145. token: '',
  146. ));
  147. $resp = $this->internalRequest(
  148. 'POST',
  149. '/internal/jobs/refresh-geoip',
  150. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  151. );
  152. self::assertSame(412, $resp->getStatusCode());
  153. $body = $this->decode($resp);
  154. self::assertSame('ipinfo', $body['provider']);
  155. self::assertSame('IPINFO_TOKEN', $body['missing']);
  156. }
  157. public function testEnrichPendingNoOpsCleanlyWithoutDbs(): void
  158. {
  159. $resp = $this->internalRequest(
  160. 'POST',
  161. '/internal/jobs/enrich-pending',
  162. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  163. );
  164. self::assertSame(200, $resp->getStatusCode());
  165. $body = $this->decode($resp);
  166. self::assertSame('enrich-pending', $body['job']);
  167. self::assertSame('success', $body['status']);
  168. self::assertSame(0, $body['items_processed']);
  169. }
  170. public function testStatusListsAllRegisteredJobs(): void
  171. {
  172. $resp = $this->internalRequest(
  173. 'GET',
  174. '/internal/jobs/status',
  175. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  176. );
  177. self::assertSame(200, $resp->getStatusCode());
  178. $body = $this->decode($resp);
  179. self::assertArrayHasKey('jobs', $body);
  180. self::assertArrayHasKey('recompute-scores', $body['jobs']);
  181. self::assertArrayHasKey('cleanup-audit', $body['jobs']);
  182. self::assertArrayHasKey('enrich-pending', $body['jobs']);
  183. self::assertArrayHasKey('refresh-geoip', $body['jobs']);
  184. self::assertArrayHasKey('tick', $body['jobs']);
  185. }
  186. private function swapDownloader(\App\Infrastructure\Enrichment\Downloaders\GeoIpDownloader $downloader): void
  187. {
  188. if (!method_exists($this->container, 'set')) {
  189. return;
  190. }
  191. /** @var \DI\Container $container */
  192. $container = $this->container;
  193. $container->set(\App\Infrastructure\Enrichment\Downloaders\GeoIpDownloader::class, $downloader);
  194. // PHP-DI caches singletons, so JobsController already holds the
  195. // previous downloader. Replace it with a freshly built one
  196. // (via container->make) so it picks up the new binding.
  197. $container->set(\App\Application\Internal\JobsController::class, $container->make(\App\Application\Internal\JobsController::class));
  198. $this->app = \App\App\AppFactory::build($this->container);
  199. }
  200. public function testCleanupAuditSucceedsAndRecordsRun(): void
  201. {
  202. $resp = $this->internalRequest(
  203. 'POST',
  204. '/internal/jobs/cleanup-audit',
  205. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  206. );
  207. self::assertSame(200, $resp->getStatusCode());
  208. $body = $this->decode($resp);
  209. self::assertSame('cleanup-audit', $body['job']);
  210. self::assertSame('success', $body['status']);
  211. $row = $this->db->fetchAssociative(
  212. "SELECT triggered_by, status FROM job_runs WHERE job_name = 'cleanup-audit'"
  213. );
  214. self::assertNotFalse($row);
  215. self::assertSame('schedule', $row['triggered_by']);
  216. self::assertSame('success', $row['status']);
  217. }
  218. /**
  219. * @param array<string, string> $headers
  220. */
  221. private function internalRequest(
  222. string $method,
  223. string $path,
  224. array $headers = [],
  225. ?string $body = null,
  226. string $remoteAddr = '127.0.0.1',
  227. ): \Psr\Http\Message\ResponseInterface {
  228. $factory = new \Slim\Psr7\Factory\ServerRequestFactory();
  229. $request = $factory->createServerRequest($method, $path, ['REMOTE_ADDR' => $remoteAddr]);
  230. foreach ($headers as $name => $value) {
  231. $request = $request->withHeader($name, $value);
  232. }
  233. if ($body !== null) {
  234. $stream = (new \Slim\Psr7\Factory\StreamFactory())->createStream($body);
  235. $request = $request->withBody($stream);
  236. $request = $request->withHeader('Content-Type', 'application/json');
  237. }
  238. return $this->app->handle($request);
  239. }
  240. }