AppTestCase.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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\Auth\OidcAuthenticator;
  7. use GuzzleHttp\ClientInterface as GuzzleClientInterface;
  8. use GuzzleHttp\Handler\MockHandler;
  9. use GuzzleHttp\HandlerStack;
  10. use GuzzleHttp\Middleware;
  11. use Monolog\Handler\NullHandler;
  12. use Monolog\Handler\TestHandler;
  13. use Monolog\Logger;
  14. use PHPUnit\Framework\TestCase;
  15. use Psr\Container\ContainerInterface;
  16. use Psr\Log\LoggerInterface;
  17. use Slim\App;
  18. use Slim\Psr7\Factory\ServerRequestFactory;
  19. use Slim\Psr7\Factory\StreamFactory;
  20. /**
  21. * Boots the UI Slim app with a Guzzle MockHandler swapped in for the
  22. * api-side calls. Sessions run in CLI-fallback mode (no headers); each
  23. * test gets a fresh `$_SESSION` superglobal.
  24. *
  25. * The mocked responses are queued via `enqueueApiResponse(...)` before
  26. * the request under test fires.
  27. */
  28. abstract class AppTestCase extends TestCase
  29. {
  30. protected ContainerInterface $container;
  31. protected App $app;
  32. protected MockHandler $mock;
  33. /** @var list<array{request: \Psr\Http\Message\RequestInterface, response: \Psr\Http\Message\ResponseInterface, error: mixed, options: array<string, mixed>}> */
  34. protected array $apiHistory = [];
  35. private ?string $throttlePath = null;
  36. protected function tearDown(): void
  37. {
  38. parent::tearDown();
  39. if ($this->throttlePath !== null) {
  40. @unlink($this->throttlePath);
  41. @unlink($this->throttlePath . '.lock');
  42. $this->throttlePath = null;
  43. }
  44. }
  45. /**
  46. * @param array<string, mixed> $overrides
  47. */
  48. protected function bootApp(array $overrides = []): void
  49. {
  50. // Reset the global session bag between tests.
  51. $_SESSION = [];
  52. $this->throttlePath = sys_get_temp_dir() . '/irdb_login_throttle_test_'
  53. . bin2hex(random_bytes(8)) . '.json';
  54. $defaults = [
  55. 'app_env' => 'development',
  56. 'log_level' => \Monolog\Level::Warning,
  57. 'public_url' => 'http://localhost:8080',
  58. 'api_base_url' => 'http://api:8081',
  59. 'ui_service_token' => 'irdb_svc_TESTTOKEN',
  60. 'api_timeout_seconds' => 1.0,
  61. 'oidc_enabled' => false,
  62. 'oidc_issuer' => '',
  63. 'oidc_client_id' => '',
  64. 'oidc_client_secret' => '',
  65. 'oidc_redirect_uri' => '',
  66. 'local_admin_enabled' => true,
  67. 'local_admin_username' => 'admin',
  68. 'local_admin_password_hash' => password_hash('test1234', PASSWORD_ARGON2ID),
  69. 'session_idle_seconds' => 28800,
  70. 'session_absolute_seconds' => 86400,
  71. 'login_throttle_path' => $this->throttlePath,
  72. ];
  73. $settings = array_replace($defaults, $overrides);
  74. $this->container = Container::build($settings);
  75. $this->mock = new MockHandler();
  76. $this->apiHistory = [];
  77. if (method_exists($this->container, 'set')) {
  78. /** @var \DI\Container $c */
  79. $c = $this->container;
  80. $handler = HandlerStack::create($this->mock);
  81. $handler->push(Middleware::history($this->apiHistory));
  82. $c->set(GuzzleClientInterface::class, new \GuzzleHttp\Client(['handler' => $handler]));
  83. // ApiClient closure-builds from the container; refresh the
  84. // bound instance with our mocked Guzzle client.
  85. $c->set(\App\ApiClient\ApiClient::class, new \App\ApiClient\ApiClient(
  86. http: $c->get(GuzzleClientInterface::class),
  87. serviceToken: (string) $c->get('settings.ui_service_token'),
  88. health: $c->get(\App\ApiClient\ApiHealth::class),
  89. ));
  90. // Quiet the logger so test output stays clean.
  91. $nullLogger = new Logger('test');
  92. $nullLogger->pushHandler(new NullHandler());
  93. $c->set(LoggerInterface::class, $nullLogger);
  94. }
  95. $this->app = AppFactory::build($this->container);
  96. }
  97. /**
  98. * @param array<string, mixed> $body
  99. */
  100. protected function enqueueApiResponse(int $status, array $body, string $contentType = 'application/json'): void
  101. {
  102. $this->mock->append(new \GuzzleHttp\Psr7\Response(
  103. $status,
  104. ['Content-Type' => $contentType],
  105. (string) json_encode($body),
  106. ));
  107. }
  108. protected function enqueueApiException(\Throwable $e): void
  109. {
  110. $this->mock->append($e);
  111. }
  112. /**
  113. * @param array<string, string> $headers
  114. * @param array<string, mixed> $serverParams
  115. */
  116. protected function request(
  117. string $method,
  118. string $path,
  119. array $headers = [],
  120. ?string $body = null,
  121. ?string $contentType = null,
  122. array $serverParams = [],
  123. ): \Psr\Http\Message\ResponseInterface {
  124. $factory = new ServerRequestFactory();
  125. $request = $factory->createServerRequest($method, $path, $serverParams);
  126. foreach ($headers as $name => $value) {
  127. $request = $request->withHeader($name, $value);
  128. }
  129. if ($contentType !== null) {
  130. $request = $request->withHeader('Content-Type', $contentType);
  131. }
  132. if ($body !== null) {
  133. $stream = (new StreamFactory())->createStream($body);
  134. $request = $request->withBody($stream);
  135. }
  136. return $this->app->handle($request);
  137. }
  138. /**
  139. * Swap in a Monolog `TestHandler` so a test can assert what reached
  140. * the logger. Re-builds controllers that captured the old logger
  141. * (currently just `OidcController`) so they pick up the new binding.
  142. */
  143. protected function captureLogs(): TestHandler
  144. {
  145. $handler = new TestHandler();
  146. $logger = new Logger('test');
  147. $logger->pushHandler($handler);
  148. if (method_exists($this->container, 'set')) {
  149. /** @var \DI\Container $c */
  150. $c = $this->container;
  151. $c->set(LoggerInterface::class, $logger);
  152. $c->set(\App\Auth\OidcController::class, new \App\Auth\OidcController(
  153. authenticator: $c->get(OidcAuthenticator::class),
  154. auth: $c->get(\App\ApiClient\AuthClient::class),
  155. sessions: $c->get(\App\Auth\SessionManager::class),
  156. logger: $logger,
  157. enabled: (bool) $c->get('settings.oidc_enabled'),
  158. ));
  159. $this->app = AppFactory::build($c);
  160. }
  161. return $handler;
  162. }
  163. /**
  164. * Replace the `OidcAuthenticator` binding with a fake callback that
  165. * the test controls. Lets us drive the OIDC controller's success +
  166. * failure paths without a real IdP.
  167. */
  168. protected function bindOidcAuthenticator(OidcAuthenticator $stub): void
  169. {
  170. if (method_exists($this->container, 'set')) {
  171. /** @var \DI\Container $c */
  172. $c = $this->container;
  173. $c->set(OidcAuthenticator::class, $stub);
  174. // Re-build the OidcController so it picks up the new binding.
  175. $c->set(\App\Auth\OidcController::class, new \App\Auth\OidcController(
  176. authenticator: $stub,
  177. auth: $c->get(\App\ApiClient\AuthClient::class),
  178. sessions: $c->get(\App\Auth\SessionManager::class),
  179. logger: $c->get(LoggerInterface::class),
  180. enabled: (bool) $c->get('settings.oidc_enabled'),
  181. ));
  182. $this->app = AppFactory::build($c);
  183. }
  184. }
  185. }