Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
fix(api): a refused endpoint request answers with a status, not 200
thorstenhornung1a924db337fb4
diff --git a/includes/validate_endpoint.php b/includes/validate_endpoint.phpindex c20d1b9..973d762 100644--- a/includes/validate_endpoint.php+++ b/includes/validate_endpoint.php@@ -1,22 +1,36 @@-<?php-// All requests should be POST requests-// CSRF Token must be included and match the token stored on the session-// User must be logged in--require_once __DIR__ . '/../libs/csrf.php';--if ($_SERVER['REQUEST_METHOD'] !== 'POST') {- echo json_encode(["success" => false, "message" => "Invalid request method"]);- exit;-}--$csrf = $_POST['csrf_token'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');-if (!verify_csrf_token($csrf)) {- echo json_encode(["success" => false, "message" => "Invalid CSRF token"]);- exit;-}--if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {- echo json_encode(["success" => false, "message" => translate('session_expired', $i18n)]);- exit;-}\ No newline at end of file+<?php+// All requests should be POST requests+// CSRF Token must be included and match the token stored on the session+// User must be logged in+//+// Each refusal says so in the status line as well as in the body. It used to+// answer 200 with success: false, which is a refusal only a reader who parses+// the body can see: fetch() resolves, response.ok is true, a proxy or a log+// records a successful request, and a session that has expired is+// indistinguishable from a save that went through until somebody looks at the+// JSON. The body is unchanged, so every caller that reads it keeps working.++require_once __DIR__ . '/../libs/csrf.php';++if ($_SERVER['REQUEST_METHOD'] !== 'POST') {+ // 405: the endpoint exists, the method does not belong to it.+ http_response_code(405);+ echo json_encode(["success" => false, "message" => "Invalid request method"]);+ exit;+}++$csrf = $_POST['csrf_token'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');+if (!verify_csrf_token($csrf)) {+ // 403: the request is understood and refused. Not 401 - the credential+ // that is missing here is not one a browser can be asked to supply.+ http_response_code(403);+ echo json_encode(["success" => false, "message" => "Invalid CSRF token"]);+ exit;+}++if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {+ // 401: there is no session, and signing in is what changes that.+ http_response_code(401);+ echo json_encode(["success" => false, "message" => translate('session_expired', $i18n)]);+ exit;+}diff --git a/includes/validate_endpoint_admin.php b/includes/validate_endpoint_admin.phpindex 4068b72..658e5d2 100644--- a/includes/validate_endpoint_admin.php+++ b/includes/validate_endpoint_admin.php@@ -1,9 +1,13 @@-<?php-require_once __DIR__ . '/validate_endpoint.php';-// Check that user is an admin-if ($userId !== 1) {- die(json_encode([- "success" => false,- "message" => translate('error', $i18n)- ]));-}\ No newline at end of file+<?php+require_once __DIR__ . '/validate_endpoint.php';+// Check that user is an admin+if ($userId !== 1) {+ // 403: signed in, and not allowed. Answering 200 here made an+ // administrative endpoint look to every log and proxy exactly like one+ // that had done the work.+ http_response_code(403);+ die(json_encode([+ "success" => false,+ "message" => translate('error', $i18n)+ ]));+}diff --git a/tests/cases/endpoint_refusal_status_test.php b/tests/cases/endpoint_refusal_status_test.phpnew file mode 100644index 0000000..698c705--- /dev/null+++ b/tests/cases/endpoint_refusal_status_test.php@@ -0,0 +1,67 @@+<?php+/*+ A refused endpoint request says so in the status line.++ includes/validate_endpoint.php is twenty-two lines and, before this, had no+ http_response_code in it at all: a request with the wrong method, a missing+ CSRF token or an expired session was answered 200 with success: false in the+ body. That is a refusal only a reader who parses the body can see.++ What that costs is not theoretical. fetch() resolves and response.ok is true,+ so a caller that checks the response rather than the payload treats it as+ done; a reverse proxy's access log records a successful request; and an+ expired session is indistinguishable from a save that went through until+ somebody opens the JSON. The same applies to the admin guard, where a request+ from a non-admin looked exactly like one that had done the work.++ The bodies are unchanged, so every existing caller keeps working.+*/++wallos_test('every refusal in the endpoint guard sets a status code', function () {+ $source = file_get_contents(WALLOS_ROOT . '/includes/validate_endpoint.php');++ $refusals = substr_count($source, 'echo json_encode(["success" => false');+ $statuses = substr_count($source, 'http_response_code(');++ assert_same(3, $refusals, 'the guard still has its three refusals');+ assert_same(3, $statuses, 'and each of them sets a status code');++ assert_contains('http_response_code(405)', $source, 'the wrong method is 405');+ assert_contains('http_response_code(403)', $source, 'a bad CSRF token is 403');+ assert_contains('http_response_code(401)', $source, 'no session is 401');+});++wallos_test('the status is set before the body, or it is not sent at all', function () {+ // PHP sends the headers with the first byte of output, so a status set+ // after echo is silently ignored. This is the ordering that makes the+ // change work at all.+ $source = file_get_contents(WALLOS_ROOT . '/includes/validate_endpoint.php');++ foreach (['405', '403', '401'] as $code) {+ $status = strpos($source, 'http_response_code(' . $code . ')');+ $body = strpos($source, 'echo json_encode', $status);++ assert_true($status !== false && $body !== false && $status < $body,+ $code . ' is set before its body is written');+ }+});++wallos_test('an administrative endpoint refuses a non-admin with a status too', function () {+ $source = file_get_contents(WALLOS_ROOT . '/includes/validate_endpoint_admin.php');++ assert_contains('http_response_code(403)', $source, 'the admin guard answers 403');+ assert_true(+ strpos($source, 'http_response_code(403)') < strpos($source, 'die(json_encode('),+ 'before the body, so the header is actually sent'+ );+});++wallos_test('the refusal bodies are unchanged', function () {+ // The point of keeping them: every caller in the application reads+ // data.success, and this change must not ask any of them to be updated.+ $source = file_get_contents(WALLOS_ROOT . '/includes/validate_endpoint.php');++ assert_contains('"message" => "Invalid request method"', $source, 'the method message is as it was');+ assert_contains('"message" => "Invalid CSRF token"', $source, 'and the CSRF one');+ assert_contains("translate('session_expired', \$i18n)", $source, 'and the session one');+});