Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
fix: check the delete in delete-before-replace save pairs (#1197)
thorstenhornung1c0a2cb777d18
diff --git a/api/fixer/set_fixer.php b/api/fixer/set_fixer.phpindex 0c8abcc..d9cada8 100644--- a/api/fixer/set_fixer.php+++ b/api/fixer/set_fixer.php@@ -138,10 +138,25 @@ if ($provider === 1 && isset($http_response_header)) {$apiData = json_decode($response, true);if (isset($apiData['success']) && $apiData['success'] == true) {// Delete existing settings first+ //+ // The same statement sixty lines up, on the clearing path, reads its+ // result. This copy did not, while the insert that replaces the row it+ // removes did - so a failed delete answered "saved successfully" over a+ // fixer table that now holds two keys for one user.$removeSql = "DELETE FROM fixer WHERE user_id = :userId";$removeStmt = $db->prepare($removeSql);$removeStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $removeStmt->execute();+ $removeResult = $removeStmt->execute();++ if ($removeResult === false) {+ echo json_encode([+ 'success' => false,+ 'title' => 'Database error',+ 'message' => 'Failed to save Fixer API settings.'+ ]);+ $db->close();+ exit;+ }// Insert new settings$insertSql = "INSERT INTO fixer (api_key, provider, user_id) VALUES (:api_key, :provider, :userId)";diff --git a/endpoints/ai/save_settings.php b/endpoints/ai/save_settings.phpindex 976e1be..95b4caa 100644--- a/endpoints/ai/save_settings.php+++ b/endpoints/ai/save_settings.php@@ -61,11 +61,22 @@ if (in_array($aiType, ['ollama', 'openai-compatible'])) {}// Save settings+//+// The insert below replaces this row and its result is read; this one's was+// dropped. Two rows in ai_settings for one user is worse than a stale colour:+// includes/ai_client.php and settings.php both take the first row they are+// handed, so the account can go on talking to the provider and the key it just+// replaced - after being told the new one was saved.$stmt = $db->prepare("DELETE FROM ai_settings WHERE user_id = ?");$stmt->bindValue(1, $userId, SQLITE3_INTEGER);-$stmt->execute();+$deleted = $stmt->execute();$stmt->close();+if ($deleted === false) {+ echo json_encode(["success" => false, "message" => translate('error', $i18n)]);+ exit;+}+$stmt = $db->prepare("INSERT INTO ai_settings (user_id, type, enabled, api_key, model, url, run_schedule)VALUES (:user_id, :type, :enabled, :api_key, :model, :url, :run_schedule)diff --git a/endpoints/currency/fixer_api_key.php b/endpoints/currency/fixer_api_key.phpindex 65ed59b..5696fa2 100644--- a/endpoints/currency/fixer_api_key.php+++ b/endpoints/currency/fixer_api_key.php@@ -5,10 +5,22 @@ require_once '../../includes/validate_endpoint.php';$newApiKey = isset($_POST["api_key"]) ? trim($_POST["api_key"]) : "";$provider = isset($_POST["provider"]) ? $_POST["provider"] : 0;+// The insert further down replaces this row and its result decides the answer;+// this one's was dropped. Two rows in fixer for one user means the exchange+// rate update reads whichever key it is handed first, which can be the one the+// user replaced because it had stopped working - and the settings page shows+// the usage of one row while the cron job spends the quota of the other.$removeOldKey = "DELETE FROM fixer WHERE user_id = :userId";$stmt = $db->prepare($removeOldKey);$stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);-$stmt->execute();++if ($stmt->execute() === false) {+ echo json_encode([+ "success" => false,+ "message" => translate('failed_to_store_api_key', $i18n)+ ]);+ exit;+}if ($provider == 1) {$testKeyUrl = "https://api.apilayer.com/fixer/latest?base=USD&symbols=EUR";diff --git a/endpoints/settings/customcss.php b/endpoints/settings/customcss.phpindex bb2b6b2..3f6a0e4 100644--- a/endpoints/settings/customcss.php+++ b/endpoints/settings/customcss.php@@ -8,9 +8,20 @@ $data = json_decode($postData, true);$customCss = $data['customCss'];+// The insert below replaces the row this delete removes, and only the insert+// was checked. A delete that fails while the insert succeeds leaves two rows+// for one user, and the readers of this table take whichever row they are+// handed first, so the page can go on serving the css this request replaced -+// after telling the user it was saved.$stmt = $db->prepare('DELETE FROM custom_css_style WHERE user_id = :userId');$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);-$stmt->execute();++if ($stmt->execute() === false) {+ die(json_encode([+ "success" => false,+ "message" => translate("error", $i18n)+ ]));+}$stmt = $db->prepare('INSERT INTO custom_css_style (css, user_id) VALUES (:customCss, :userId)');$stmt->bindParam(':customCss', $customCss, SQLITE3_TEXT);diff --git a/endpoints/settings/customtheme.php b/endpoints/settings/customtheme.phpindex 8e6e37d..b10e9b7 100644--- a/endpoints/settings/customtheme.php+++ b/endpoints/settings/customtheme.php@@ -25,9 +25,19 @@ if ($main_color == $accent_color) {]));}+// Same pair as in customcss.php, and the same asymmetry: the insert that+// replaces this row was checked, the delete was not. Two rows for one user+// mean the colors the user just chose are one of two answers to the same+// question, and nothing decides which one the next page load gets.$stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :userId');$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);-$stmt->execute();++if ($stmt->execute() === false) {+ die(json_encode([+ "success" => false,+ "message" => translate("error", $i18n)+ ]));+}$stmt = $db->prepare('INSERT INTO custom_colors (main_color, accent_color, hover_color, user_id) VALUES (:main_color, :accent_color, :hover_color, :userId)');$stmt->bindParam(':main_color', $main_color, SQLITE3_TEXT);diff --git a/endpoints/settings/google_search.php b/endpoints/settings/google_search.phpindex e619d6a..f2ebd2a 100644--- a/endpoints/settings/google_search.php+++ b/endpoints/settings/google_search.php@@ -4,10 +4,21 @@ require_once '../../includes/validate_endpoint.php';$apiKey = isset($_POST['api_key']) ? trim($_POST['api_key']) : '';+// This delete carries both paths: it clears the key when the field is empty,+// and it makes room for the insert further down when it is not. Only the+// insert was checked. So a failed delete either reports a key as cleared while+// it is still there and still being spent, or leaves the old key beside the new+// one for the reader to pick between.$removeOldCredentials = "DELETE FROM google_search WHERE user_id = :userId";$stmt = $db->prepare($removeOldCredentials);$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);-$stmt->execute();++if ($stmt->execute() === false) {+ die(json_encode([+ "success" => false,+ "message" => translate('error', $i18n)+ ]));+}// An empty field clears the key and disables the Google sectionif ($apiKey === '') {diff --git a/tests/cases/delete_before_replace_test.php b/tests/cases/delete_before_replace_test.phpnew file mode 100644index 0000000..dfd9c80--- /dev/null+++ b/tests/cases/delete_before_replace_test.php@@ -0,0 +1,265 @@+<?php+/*+ A replace pair is checked as a pair.++ Several places save a per-user row by deleting the old one and inserting the+ new one. The insert's result decided the answer the user got. The delete's+ result was thrown away.++ Nothing in the schema stops the second row: none of these tables has a unique+ index on user_id. So a delete that fails while the insert succeeds leaves two+ rows for one user, every reader of those tables takes whichever row it is+ handed first, and the endpoint has already answered "saved". The setting the+ user just replaced goes on being served, and there is nothing anywhere to+ suggest why.++ The guard finds the pairs by their shape rather than from a list, so a copy+ written next year is covered on the day it appears. It is deliberately about+ the asymmetry: where the insert's result is read, the delete's has to be read+ too. A pair that reads neither half is a different and larger repair - those+ need the two writes to become one unit of work, not one more if - and this+ guard leaves them alone rather than half-describing them.+*/++/**+ * Every PHP file of the application itself.+ *+ * libs/ is vendored third-party code and tests/ is this suite.+ *+ * @return string[]+ */+function delete_before_replace_files()+{+ $files = [];+ $walk = new RecursiveIteratorIterator(+ new RecursiveDirectoryIterator(WALLOS_ROOT, FilesystemIterator::SKIP_DOTS)+ );++ foreach ($walk as $file) {+ $path = $file->getPathname();++ if (substr($path, -4) !== '.php') {+ continue;+ }++ $relative = ltrim(substr($path, strlen(WALLOS_ROOT)), '/');++ if (strpos($relative, 'libs/') === 0 || strpos($relative, 'tests/') === 0) {+ continue;+ }++ $files[] = $relative;+ }++ sort($files);++ return $files;+}++/**+ * Whether the value a statement returned is looked at.+ *+ * @param string[] $lines+ * @param int $index Line holding the execute() call.+ * @return bool+ */+function delete_before_replace_result_is_read($lines, $index)+{+ $line = $lines[$index];++ // A statement of its own, with nothing done to what it returns.+ if (preg_match('/^\s*\$\w+(?:->\w+)*->execute\s*\(\s*\)\s*;\s*$/', $line) === 1) {+ return false;+ }++ // Assigned to a name: that name has to reach a condition, otherwise the+ // assignment is only a longer way of dropping the result.+ if (preg_match('/(\$\w+)\s*=\s*@?\$\w+(?:->\w+)*->execute\s*\(/', $line, $match) === 1) {+ $window = implode("\n", array_slice($lines, $index, 12));+ $name = preg_quote($match[1], '/');++ return preg_match('/\b(?:if|while)\s*\(\s*!?\s*' . $name . '\b/', $window) === 1+ || preg_match('/' . $name . '\s*(?:===|!==|==|!=)/', $window) === 1;+ }++ // if ($stmt->execute()), $stmt->execute() === false, and the like.+ return true;+}++/**+ * The first execute() belonging to the statement that starts at $index.+ *+ * @param string[] $lines+ * @param int $index+ * @param int $reach How many lines a bind block may take.+ * @return int|null+ */+function delete_before_replace_execute_line($lines, $index, $reach = 16)+{+ $last = min(count($lines) - 1, $index + $reach);++ for ($i = $index; $i <= $last; $i++) {+ if (strpos($lines[$i], '->execute(') !== false) {+ return $i;+ }+ }++ return null;+}++/**+ * Every delete that a later insert into the same table replaces.+ *+ * @param string $source+ * @return array[] table, delete/insert line numbers and whether each is read+ */+function delete_before_replace_pairs($source)+{+ $lines = preg_split('/\R/', $source);+ $count = count($lines);+ $pairs = [];++ foreach ($lines as $number => $line) {+ if (preg_match('/DELETE\s+FROM\s+["\'`]?(\w+)["\'`]?/i', $line, $match) !== 1) {+ continue;+ }++ $table = $match[1];+ $deleteExecute = delete_before_replace_execute_line($lines, $number);++ if ($deleteExecute === null) {+ continue;+ }++ // The insert that puts the row back. It can be a long way down - in+ // google_search.php a whole API call sits between the two - but a+ // second delete of the same table in between means the insert belongs+ // to that one instead, as on the clearing path in api/fixer.+ $insert = null;+ $quoted = preg_quote($table, '/');+ $pattern = '/INSERT\s+(?:OR\s+\w+\s+)?INTO\s+["\'`]?' . $quoted . '["\'`]?\W/i';++ for ($i = $deleteExecute + 1; $i < $count; $i++) {+ if (preg_match('/DELETE\s+FROM\s+["\'`]?' . $quoted . '["\'`]?\W/i', $lines[$i]) === 1) {+ break;+ }++ if (preg_match($pattern, $lines[$i]) === 1) {+ $insert = $i;+ break;+ }+ }++ if ($insert === null) {+ continue;+ }++ $insertExecute = delete_before_replace_execute_line($lines, $insert);++ if ($insertExecute === null) {+ continue;+ }++ $pairs[] = [+ 'table' => $table,+ 'delete' => $number + 1,+ 'insert' => $insert + 1,+ 'deleteIsRead' => delete_before_replace_result_is_read($lines, $deleteExecute),+ 'insertIsRead' => delete_before_replace_result_is_read($lines, $insertExecute),+ ];+ }++ return $pairs;+}++wallos_test('a delete is checked wherever the insert that replaces it is', function () {+ $governed = 0;++ foreach (delete_before_replace_files() as $path) {+ foreach (delete_before_replace_pairs(file_get_contents(WALLOS_ROOT . '/' . $path)) as $pair) {+ if (!$pair['insertIsRead']) {+ // Neither half is read. Left alone on purpose: adding a check+ // to the delete alone would not make that file honest, and this+ // guard would then be calling it fixed.+ continue;+ }++ $governed++;++ assert_true($pair['deleteIsRead'],+ $path . ' line ' . $pair['delete'] . ': the delete from ' . $pair['table']+ . ' drops its result, while the insert that replaces the row on line '+ . $pair['insert'] . ' reads its own. A failed delete then answers "saved" '+ . 'over two rows for one user.');+ }+ }++ // A guard that finds nothing passes every assertion above it.+ assert_true($governed >= 6,+ 'the tree was swept and the replace pairs were found (' . $governed . ' found)');+});++wallos_test('the second row really does get in, and reading the result is what stops it', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'theme');++ $save = function ($colour) use ($db) {+ $stmt = $db->prepare('INSERT INTO custom_colors (main_color, accent_color, hover_color, user_id)+ VALUES (:main, :accent, :hover, 1)');+ $stmt->bindValue(':main', $colour, SQLITE3_TEXT);+ $stmt->bindValue(':accent', '#00ffff', SQLITE3_TEXT);+ $stmt->bindValue(':hover', '#00008b', SQLITE3_TEXT);+ $stmt->execute();+ };++ $rows = function () use ($db) {+ return (int) $db->querySingle('SELECT COUNT(*) FROM custom_colors WHERE user_id = 1');+ };++ $refuseDeletes = function () use ($db) {+ // A delete fails for reasons the endpoint cannot see coming: a database+ // locked by another request, a disk that is full or has gone read-only.+ // SQLite reports all of them the same way, through the statement+ // result, so a trigger that refuses the delete reproduces the case+ // exactly and without waiting for a race.+ $db->exec("CREATE TRIGGER wallos_test_refuse_delete BEFORE DELETE ON custom_colors+ BEGIN SELECT RAISE(ABORT, 'refused'); END");+ };++ // What the user saved last week.+ $save('#000000');+ $refuseDeletes();++ // The shape these endpoints had. The @ only silences the warning SQLite3+ // prints beside the return value the caller is about to ignore.+ $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = 1');+ $dropped = @$stmt->execute();+ $save('#ff0000');++ assert_true($dropped === false, 'the delete did fail, so the rest of this test means something');+ assert_same(2, $rows(),+ 'unchecked, a failed delete leaves the replacement beside the row it should have replaced');++ // Which of the two any page gets is decided by nothing: every reader of+ // this table selects by user_id and takes the first row of the result.+ $reader = $db->query('SELECT * FROM custom_colors WHERE user_id = 1');+ assert_true($reader->fetchArray(SQLITE3_ASSOC) !== false,+ 'and the reader answers with one of them without being able to say which');++ // Back to one row, then the shape they have now.+ $db->exec('DROP TRIGGER wallos_test_refuse_delete');+ $db->exec('DELETE FROM custom_colors WHERE user_id = 1');+ $save('#000000');+ $refuseDeletes();++ $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = 1');++ if (@$stmt->execute() !== false) {+ $save('#ff0000');+ }++ assert_same(1, $rows(),+ 'checked, the request stops instead of adding a second row, and the user is told so');++ $db->close();+});