post($this->apiUrl, [ 'op' => 'perform-login', 'user' => 'test', 'password' => 'test', ]); $this->assertEquals(200, $status); // list is in csrfIgnore — should work without csrf_token [$status, $body] = $this->post($this->apiUrl, [ 'op' => 'list', ]); $this->assertEquals(200, $status); $this->assertArrayHasKey('books', $body); } // ── Non-ignored operations — CSRF required ─────────────────────────────── public function test_non_ignored_op_requires_csrf(): void { // Login to establish session [$status, $body] = $this->post($this->apiUrl, [ 'op' => 'perform-login', 'user' => 'test', 'password' => 'test', ]); $this->assertEquals(200, $status); // togglefav is NOT in csrfIgnore — should require csrf_token [$status, $body] = $this->post($this->apiUrl, [ 'op' => 'togglefav', 'id' => 1, 'csrf_token' => '', ]); $this->assertEquals(401, $status); $this->assertArrayHasKey('error', $body); $this->assertStringContainsString('CSRF', $body['error'] ?? ''); } public function test_non_ignored_op_with_valid_csrf(): void { // Login to establish session and get csrf_token [$status, $body] = $this->post($this->apiUrl, [ 'op' => 'perform-login', 'user' => 'test', 'password' => 'test', ]); $this->assertEquals(200, $status); $csrfToken = $body['csrf_token'] ?? ''; $this->assertNotEmpty($csrfToken); // togglefav with valid csrf_token should succeed [$status, $body] = $this->post($this->apiUrl, [ 'op' => 'togglefav', 'id' => 1, 'csrf_token' => $csrfToken, ]); $this->assertEquals(200, $status); $this->assertArrayHasKey('id', $body); } public function test_non_ignored_op_with_invalid_csrf(): void { // Login to establish session [$status, $body] = $this->post($this->apiUrl, [ 'op' => 'perform-login', 'user' => 'test', 'password' => 'test', ]); $this->assertEquals(200, $status); // togglefav with wrong csrf_token should fail [$status, $body] = $this->post($this->apiUrl, [ 'op' => 'togglefav', 'id' => 1, 'csrf_token' => 'invalid_token_12345', ]); $this->assertEquals(401, $status); $this->assertArrayHasKey('error', $body); $this->assertStringContainsString('CSRF', $body['error'] ?? ''); } // ── Unauthenticated — no CSRF check ───────────────────────────────────── public function test_unauthenticated_no_csrf_check(): void { // Without a session, CSRF middleware should skip its check // and let the handler deal with auth [$status, $body] = $this->post($this->apiUrl, [ 'op' => 'togglefav', 'id' => 1, ]); $this->assertEquals(401, $status); // Error should be about authentication, not CSRF $this->assertArrayHasKey('error', $body); $this->assertStringNotContainsString('CSRF', $body['error'] ?? ''); } }