1
0

LocalLoginTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests\Integration\Auth;
  4. use App\Auth\LoginThrottle;
  5. use App\Http\CsrfMiddleware;
  6. use App\Tests\Integration\Support\AppTestCase;
  7. /**
  8. * Drive the local-admin login flow against the real Slim app + a mocked
  9. * api-side `upsertLocal` response. Exercises CSRF, throttle, redirect,
  10. * session-set, and api-down handling.
  11. */
  12. final class LocalLoginTest extends AppTestCase
  13. {
  14. protected function setUp(): void
  15. {
  16. $this->bootApp();
  17. }
  18. public function testGetLoginRendersForm(): void
  19. {
  20. $response = $this->request('GET', '/login');
  21. self::assertSame(200, $response->getStatusCode());
  22. $body = (string) $response->getBody();
  23. self::assertStringContainsString('Sign in', $body);
  24. // Local sign-in toggle present (oidc disabled in this fixture).
  25. self::assertStringContainsString('name="username"', $body);
  26. self::assertStringContainsString('csrf_token', $body);
  27. }
  28. public function testCorrectCredentialsLogInAndRedirectToMe(): void
  29. {
  30. $this->enqueueApiResponse(200, [
  31. 'user_id' => 1,
  32. 'role' => 'admin',
  33. 'email' => null,
  34. 'display_name' => 'Local Admin',
  35. 'is_local' => true,
  36. ]);
  37. // Need a session + csrf token; first GET /login to set one up.
  38. $this->request('GET', '/login');
  39. $token = (string) ($_SESSION[CsrfMiddleware::SESSION_KEY] ?? '');
  40. self::assertNotEmpty($token);
  41. $body = http_build_query(['csrf_token' => $token, 'username' => 'admin', 'password' => 'test1234']);
  42. $response = $this->request('POST', '/login/local', [], $body, 'application/x-www-form-urlencoded');
  43. self::assertSame(303, $response->getStatusCode());
  44. self::assertSame('/app/dashboard', $response->getHeaderLine('Location'));
  45. self::assertNotNull($_SESSION['_user'] ?? null);
  46. self::assertSame('admin', $_SESSION['_user']['role']);
  47. }
  48. public function testWrongPasswordRedirectsBackToLoginWithFlash(): void
  49. {
  50. $this->request('GET', '/login');
  51. $token = (string) ($_SESSION[CsrfMiddleware::SESSION_KEY] ?? '');
  52. $body = http_build_query(['csrf_token' => $token, 'username' => 'admin', 'password' => 'WRONG']);
  53. $response = $this->request('POST', '/login/local', [], $body, 'application/x-www-form-urlencoded');
  54. self::assertSame(303, $response->getStatusCode());
  55. self::assertSame('/login', $response->getHeaderLine('Location'));
  56. $flash = $_SESSION['_flash'] ?? [];
  57. self::assertNotEmpty($flash);
  58. self::assertSame('error', $flash[0]['type']);
  59. }
  60. public function testWrongUsernameAlsoRecordsFailure(): void
  61. {
  62. $this->request('GET', '/login');
  63. $token = (string) ($_SESSION[CsrfMiddleware::SESSION_KEY] ?? '');
  64. $body = http_build_query(['csrf_token' => $token, 'username' => 'someone', 'password' => 'test1234']);
  65. $this->request('POST', '/login/local', [], $body, 'application/x-www-form-urlencoded');
  66. // Failure recorded on the LoginThrottle (not in the session).
  67. // Five more attempts from the same IP for the same bogus user
  68. // would lock the bucket; one shot doesn't, so we just verify
  69. // the next attempt isn't locked yet.
  70. /** @var LoginThrottle $throttle */
  71. $throttle = $this->container->get(LoginThrottle::class);
  72. self::assertFalse($throttle->isLocked('someone', ''));
  73. }
  74. public function testWrongUsernameTriggersPasswordVerify(): void
  75. {
  76. // SEC_REVIEW F7: a wrong username must still go through
  77. // password_verify against an Argon2id hash, so timing does not
  78. // distinguish "username matches" from "username does not match".
  79. // We assert a generous lower bound (10 ms) — well above the
  80. // microsecond cost of a path that skips password_verify, and
  81. // well below PHP's default PASSWORD_ARGON2ID cost (~50 ms+).
  82. $this->request('GET', '/login');
  83. $token = (string) ($_SESSION[CsrfMiddleware::SESSION_KEY] ?? '');
  84. $body = http_build_query([
  85. 'csrf_token' => $token,
  86. 'username' => 'definitely_not_the_admin',
  87. 'password' => 'irrelevant',
  88. ]);
  89. $start = hrtime(true);
  90. $response = $this->request('POST', '/login/local', [], $body, 'application/x-www-form-urlencoded');
  91. $elapsedNs = hrtime(true) - $start;
  92. self::assertSame(303, $response->getStatusCode());
  93. self::assertGreaterThan(
  94. 10_000_000,
  95. $elapsedNs,
  96. 'wrong-username path took <10ms; password_verify likely skipped (F7 regression)',
  97. );
  98. }
  99. public function testUnconfiguredLocalPasswordHashStillRunsPasswordVerify(): void
  100. {
  101. // SEC_REVIEW F7 defence-in-depth: even when LOCAL_ADMIN_PASSWORD_HASH
  102. // is empty, the login path must run password_verify against the
  103. // dummy Argon2id hash so an attacker cannot probe whether a local
  104. // admin password is configured by timing.
  105. $this->bootApp(['local_admin_password_hash' => '']);
  106. $this->request('GET', '/login');
  107. $token = (string) ($_SESSION[CsrfMiddleware::SESSION_KEY] ?? '');
  108. $body = http_build_query([
  109. 'csrf_token' => $token,
  110. 'username' => 'admin',
  111. 'password' => 'whatever',
  112. ]);
  113. $start = hrtime(true);
  114. $response = $this->request('POST', '/login/local', [], $body, 'application/x-www-form-urlencoded');
  115. $elapsedNs = hrtime(true) - $start;
  116. self::assertSame(303, $response->getStatusCode());
  117. self::assertSame('/login', $response->getHeaderLine('Location'));
  118. self::assertGreaterThan(
  119. 10_000_000,
  120. $elapsedNs,
  121. 'unconfigured-hash path took <10ms; dummy password_verify likely skipped (F7 regression)',
  122. );
  123. }
  124. public function testCsrfMissingIs403(): void
  125. {
  126. $this->request('GET', '/login');
  127. $body = http_build_query(['username' => 'admin', 'password' => 'test1234']);
  128. $response = $this->request('POST', '/login/local', [], $body, 'application/x-www-form-urlencoded');
  129. self::assertSame(403, $response->getStatusCode());
  130. }
  131. public function testFiveFailuresLockOutNextAttempt(): void
  132. {
  133. $this->request('GET', '/login');
  134. $token = (string) ($_SESSION[CsrfMiddleware::SESSION_KEY] ?? '');
  135. $bad = http_build_query(['csrf_token' => $token, 'username' => 'admin', 'password' => 'WRONG']);
  136. for ($i = 0; $i < 5; ++$i) {
  137. $this->request('POST', '/login/local', [], $bad, 'application/x-www-form-urlencoded');
  138. }
  139. // 6th attempt — even with correct credentials — gets the lockout flash.
  140. $this->enqueueApiResponse(200, [
  141. 'user_id' => 1, 'role' => 'admin', 'email' => null, 'display_name' => 'Local Admin', 'is_local' => true,
  142. ]);
  143. $good = http_build_query(['csrf_token' => $token, 'username' => 'admin', 'password' => 'test1234']);
  144. $response = $this->request('POST', '/login/local', [], $good, 'application/x-www-form-urlencoded');
  145. self::assertSame(303, $response->getStatusCode());
  146. self::assertSame('/login', $response->getHeaderLine('Location'));
  147. $flash = $_SESSION['_flash'] ?? [];
  148. self::assertNotEmpty($flash);
  149. self::assertStringContainsStringIgnoringCase('too many', $flash[0]['message']);
  150. }
  151. public function testRotatingXForwardedForDoesNotEvadePerIpLockout(): void
  152. {
  153. // SEC_REVIEW F1: an attacker spoofing X-Forwarded-For per request
  154. // must NOT mint a fresh throttle bucket. The per-IP bucket is keyed
  155. // on REMOTE_ADDR, which is constant here — so 5 failures should
  156. // still trip the lockout regardless of XFF rotation.
  157. $this->request('GET', '/login');
  158. $token = (string) ($_SESSION[CsrfMiddleware::SESSION_KEY] ?? '');
  159. $bad = http_build_query(['csrf_token' => $token, 'username' => 'admin', 'password' => 'WRONG']);
  160. for ($i = 0; $i < 5; ++$i) {
  161. $this->request(
  162. 'POST',
  163. '/login/local',
  164. ['X-Forwarded-For' => '203.0.113.' . $i],
  165. $bad,
  166. 'application/x-www-form-urlencoded',
  167. ['REMOTE_ADDR' => '198.51.100.7'],
  168. );
  169. }
  170. // 6th attempt with correct credentials but a fresh XFF still gets the
  171. // lockout flash because the per-(user, REMOTE_ADDR) bucket is full.
  172. $this->enqueueApiResponse(200, [
  173. 'user_id' => 1, 'role' => 'admin', 'email' => null, 'display_name' => 'Local Admin', 'is_local' => true,
  174. ]);
  175. $good = http_build_query(['csrf_token' => $token, 'username' => 'admin', 'password' => 'test1234']);
  176. $response = $this->request(
  177. 'POST',
  178. '/login/local',
  179. ['X-Forwarded-For' => '203.0.113.99'],
  180. $good,
  181. 'application/x-www-form-urlencoded',
  182. ['REMOTE_ADDR' => '198.51.100.7'],
  183. );
  184. self::assertSame(303, $response->getStatusCode());
  185. self::assertSame('/login', $response->getHeaderLine('Location'));
  186. $flash = $_SESSION['_flash'] ?? [];
  187. self::assertNotEmpty($flash);
  188. self::assertStringContainsStringIgnoringCase('too many', $flash[0]['message']);
  189. }
  190. public function testRotatingRemoteAddrEventuallyHitsPerUsernameLockout(): void
  191. {
  192. // SEC_REVIEW F2: even with proper REMOTE_ADDR, an attacker on a
  193. // residential proxy pool gets a fresh per-IP bucket per request.
  194. // The per-username (cross-IP) bucket must catch this at 25 failures.
  195. $this->request('GET', '/login');
  196. $token = (string) ($_SESSION[CsrfMiddleware::SESSION_KEY] ?? '');
  197. $bad = http_build_query(['csrf_token' => $token, 'username' => 'admin', 'password' => 'WRONG']);
  198. for ($i = 0; $i < 25; ++$i) {
  199. $this->request(
  200. 'POST',
  201. '/login/local',
  202. [],
  203. $bad,
  204. 'application/x-www-form-urlencoded',
  205. ['REMOTE_ADDR' => '198.51.100.' . $i],
  206. );
  207. }
  208. // Next attempt from yet another IP — even with correct credentials —
  209. // gets the lockout flash because the per-username bucket is full.
  210. $this->enqueueApiResponse(200, [
  211. 'user_id' => 1, 'role' => 'admin', 'email' => null, 'display_name' => 'Local Admin', 'is_local' => true,
  212. ]);
  213. $good = http_build_query(['csrf_token' => $token, 'username' => 'admin', 'password' => 'test1234']);
  214. $response = $this->request(
  215. 'POST',
  216. '/login/local',
  217. [],
  218. $good,
  219. 'application/x-www-form-urlencoded',
  220. ['REMOTE_ADDR' => '198.51.100.250'],
  221. );
  222. self::assertSame(303, $response->getStatusCode());
  223. self::assertSame('/login', $response->getHeaderLine('Location'));
  224. $flash = $_SESSION['_flash'] ?? [];
  225. self::assertNotEmpty($flash);
  226. self::assertStringContainsStringIgnoringCase('too many', $flash[0]['message']);
  227. }
  228. public function testFailuresArePersistedToConfiguredFilePath(): void
  229. {
  230. // SEC_REVIEW F6: confirm production wiring writes throttle state
  231. // to the on-disk path (so a worker recycle cannot wipe it). Drives
  232. // a failure through the full Slim stack, then asserts the file
  233. // exists and decodes to the expected per-IP/per-username buckets.
  234. // The cross-instance persistence guarantee itself is covered in
  235. // FileThrottleStoreTest.
  236. $this->request('GET', '/login');
  237. $token = (string) ($_SESSION[CsrfMiddleware::SESSION_KEY] ?? '');
  238. $bad = http_build_query(['csrf_token' => $token, 'username' => 'admin', 'password' => 'WRONG']);
  239. $this->request('POST', '/login/local', [], $bad, 'application/x-www-form-urlencoded');
  240. /** @var \DI\Container $c */
  241. $c = $this->container;
  242. $path = (string) $c->get('settings.login_throttle_path');
  243. self::assertFileExists($path);
  244. $decoded = json_decode((string) file_get_contents($path), true);
  245. self::assertIsArray($decoded);
  246. self::assertArrayHasKey('ip', $decoded);
  247. self::assertArrayHasKey('username', $decoded);
  248. self::assertArrayHasKey('admin', $decoded['username']);
  249. self::assertSame(1, $decoded['username']['admin']['count']);
  250. // And the live LoginThrottle (built via the container) sees that
  251. // count too — i.e., it shares the same store.
  252. /** @var LoginThrottle $live */
  253. $live = $c->get(LoginThrottle::class);
  254. self::assertFalse($live->isLocked('admin', '0.0.0.0'));
  255. // Top up to the per-IP threshold — uses the SAME file the prior
  256. // request wrote to.
  257. for ($i = 0; $i < 4; ++$i) {
  258. $live->recordFailure('admin', '');
  259. }
  260. self::assertTrue($live->isLocked('admin', ''));
  261. }
  262. public function testApiDownDuringUpsertFlashesError(): void
  263. {
  264. $this->enqueueApiException(new \GuzzleHttp\Exception\ConnectException(
  265. 'connection refused',
  266. new \GuzzleHttp\Psr7\Request('POST', '/api/v1/auth/users/upsert-local'),
  267. ));
  268. $this->enqueueApiException(new \GuzzleHttp\Exception\ConnectException(
  269. 'connection refused',
  270. new \GuzzleHttp\Psr7\Request('POST', '/api/v1/auth/users/upsert-local'),
  271. ));
  272. $this->request('GET', '/login');
  273. $token = (string) ($_SESSION[CsrfMiddleware::SESSION_KEY] ?? '');
  274. $body = http_build_query(['csrf_token' => $token, 'username' => 'admin', 'password' => 'test1234']);
  275. $response = $this->request('POST', '/login/local', [], $body, 'application/x-www-form-urlencoded');
  276. self::assertSame(303, $response->getStatusCode());
  277. self::assertSame('/login', $response->getHeaderLine('Location'));
  278. $flash = $_SESSION['_flash'] ?? [];
  279. self::assertNotEmpty($flash);
  280. self::assertStringContainsStringIgnoringCase('api', $flash[0]['message']);
  281. }
  282. }